├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values-v21
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── drawable-nodpi
│ │ │ │ ├── emoji_1f60a.png
│ │ │ │ ├── emoji_1f60d.png
│ │ │ │ └── emoji_1f61f.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── drawable-hdpi
│ │ │ │ ├── ic_delete_24dp.png
│ │ │ │ ├── ic_add_white_24dp.png
│ │ │ │ ├── ic_mode_edit_24dp.png
│ │ │ │ ├── ic_send_white_24dp.png
│ │ │ │ └── ic_mode_edit_white_24dp.png
│ │ │ ├── drawable-mdpi
│ │ │ │ ├── ic_delete_24dp.png
│ │ │ │ ├── ic_add_white_24dp.png
│ │ │ │ ├── ic_mode_edit_24dp.png
│ │ │ │ ├── ic_send_white_24dp.png
│ │ │ │ └── ic_mode_edit_white_24dp.png
│ │ │ ├── drawable-xhdpi
│ │ │ │ ├── ic_delete_24dp.png
│ │ │ │ ├── ic_add_white_24dp.png
│ │ │ │ ├── ic_mode_edit_24dp.png
│ │ │ │ ├── ic_send_white_24dp.png
│ │ │ │ └── ic_mode_edit_white_24dp.png
│ │ │ ├── drawable-xxhdpi
│ │ │ │ ├── ic_delete_24dp.png
│ │ │ │ ├── ic_add_white_24dp.png
│ │ │ │ ├── ic_mode_edit_24dp.png
│ │ │ │ ├── ic_send_white_24dp.png
│ │ │ │ └── ic_mode_edit_white_24dp.png
│ │ │ ├── drawable-xxxhdpi
│ │ │ │ ├── ic_delete_24dp.png
│ │ │ │ ├── ic_add_white_24dp.png
│ │ │ │ ├── ic_mode_edit_24dp.png
│ │ │ │ ├── ic_send_white_24dp.png
│ │ │ │ └── ic_mode_edit_white_24dp.png
│ │ │ ├── values
│ │ │ │ ├── int.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── strings.xml
│ │ │ ├── drawable
│ │ │ │ ├── mode_background.xml
│ │ │ │ └── button_ripple_effect_circle.xml
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ ├── drawable-v21
│ │ │ │ └── button_ripple_effect_circle.xml
│ │ │ ├── menu
│ │ │ │ ├── menu_send.xml
│ │ │ │ ├── menu_edit.xml
│ │ │ │ └── menu_default.xml
│ │ │ └── layout
│ │ │ │ ├── activity_edit_user_profile.xml
│ │ │ │ ├── activity_sign_up.xml
│ │ │ │ ├── activity_sign_in.xml
│ │ │ │ ├── activity_create_or_edit_tweet.xml
│ │ │ │ ├── tweet_row.xml
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── atahani
│ │ │ │ └── retrofit_sample
│ │ │ │ ├── models
│ │ │ │ ├── ErrorModel.java
│ │ │ │ ├── AuthenticationResponseModel.java
│ │ │ │ ├── UserModel.java
│ │ │ │ ├── TokenModel.java
│ │ │ │ ├── TweetModel.java
│ │ │ │ ├── RefreshTokenRequestModel.java
│ │ │ │ ├── SignInRequestModel.java
│ │ │ │ └── SignUpRequestModel.java
│ │ │ │ ├── adapter
│ │ │ │ ├── OperationResultModel.java
│ │ │ │ └── TweetAdapter.java
│ │ │ │ ├── TApplication.java
│ │ │ │ ├── utility
│ │ │ │ ├── ClientConfigs.java
│ │ │ │ ├── Constants.java
│ │ │ │ ├── ErrorUtils.java
│ │ │ │ ├── CropCircleTransformation.java
│ │ │ │ ├── AppPreferenceTools.java
│ │ │ │ └── AndroidUtilities.java
│ │ │ │ ├── network
│ │ │ │ ├── UTCDateTypeAdapter.java
│ │ │ │ ├── FakeTwitterService.java
│ │ │ │ └── FakeTwitterProvider.java
│ │ │ │ └── ui
│ │ │ │ ├── EditUserProfile.java
│ │ │ │ ├── SignUpActivity.java
│ │ │ │ ├── SignInActivity.java
│ │ │ │ ├── CreateOrEditTweet.java
│ │ │ │ └── MainActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── atahani
│ │ │ └── retrofit_sample
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── atahani
│ │ └── retrofit_sample
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── LICENSE
├── README.md
├── .gitignore
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-nodpi/emoji_1f60a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-nodpi/emoji_1f60a.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-nodpi/emoji_1f60d.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-nodpi/emoji_1f60d.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-nodpi/emoji_1f61f.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-nodpi/emoji_1f61f.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_delete_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-hdpi/ic_delete_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_delete_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-mdpi/ic_delete_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_add_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-hdpi/ic_add_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_mode_edit_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-hdpi/ic_mode_edit_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_add_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-mdpi/ic_add_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_mode_edit_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-mdpi/ic_mode_edit_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_delete_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xhdpi/ic_delete_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_delete_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxhdpi/ic_delete_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_delete_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxxhdpi/ic_delete_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_send_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-hdpi/ic_send_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_send_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-mdpi/ic_send_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_add_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xhdpi/ic_add_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_mode_edit_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xhdpi/ic_mode_edit_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_send_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xhdpi/ic_send_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_add_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxhdpi/ic_add_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_mode_edit_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxhdpi/ic_mode_edit_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_send_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxhdpi/ic_send_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_add_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxxhdpi/ic_add_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_mode_edit_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxxhdpi/ic_mode_edit_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_send_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxxhdpi/ic_send_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_mode_edit_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-hdpi/ic_mode_edit_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_mode_edit_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-mdpi/ic_mode_edit_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_mode_edit_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xhdpi/ic_mode_edit_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_mode_edit_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxhdpi/ic_mode_edit_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_mode_edit_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/atahani/retrofit-sample/HEAD/app/src/main/res/drawable-xxxhdpi/ic_mode_edit_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/values/int.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 0x1F60A
4 | 0x1F60D
5 | 0x1F61F
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/models/ErrorModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.models;
2 |
3 | /**
4 | * Error Model when error happened in http like 404
5 | */
6 | public class ErrorModel {
7 |
8 | public String type;
9 | public String description;
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/adapter/OperationResultModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.adapter;
2 |
3 | /**
4 | * operation result model like delete something
5 | */
6 | public class OperationResultModel {
7 | public String type;
8 | public String description;
9 | }
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/mode_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/models/AuthenticationResponseModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.models;
2 |
3 | /**
4 | * Authentication response Model used as response model in sign in and sign up request
5 | */
6 | public class AuthenticationResponseModel {
7 | public TokenModel token;
8 | public UserModel user_profile;
9 | }
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/models/UserModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.models;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * User Model
7 | */
8 | public class UserModel {
9 | public String id;
10 | public String email;
11 | public String name;
12 | @SerializedName("image")
13 | public String imageUrl;
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v21/button_ripple_effect_circle.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | -
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_send.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/test/java/com/atahani/retrofit_sample/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/models/TokenModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.models;
2 |
3 | import java.util.Date;
4 |
5 | /**
6 | * Token Model used in sign in, sign up and refresh token response
7 | */
8 | public class TokenModel {
9 | public String access_token;
10 | public Long expire_in_sec;
11 | public Date expire_at;
12 | public String refresh_token;
13 | public String app_id;
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 | #9FA8DA
7 | #E8EAF6
8 | #F2717171
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_edit.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/atahani/retrofit_sample/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/TApplication.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | /**
7 | * extend application class
8 | */
9 | public class TApplication extends Application {
10 |
11 | public static volatile Context applicationContext;
12 |
13 | @Override
14 | public void onCreate() {
15 | super.onCreate();
16 | applicationContext = getApplicationContext();
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/button_ripple_effect_circle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 | -
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/models/TweetModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.models;
2 |
3 | import java.util.Date;
4 |
5 | /**
6 | * Tweet Model to send new tweet for request body and get in in response
7 | * NOTE: all of the attr should define as public and also the name should match in REST API
8 | */
9 | public class TweetModel {
10 | public String id;
11 | public String feel;
12 | public String body;
13 | public Date created_at;
14 | public Date updated_at;
15 | public UserModel user;
16 | }
17 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/models/RefreshTokenRequestModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.models;
2 |
3 | import com.atahani.retrofit_sample.utility.ClientConfigs;
4 |
5 | /**
6 | * used in refresh token request
7 | */
8 | public class RefreshTokenRequestModel {
9 | public String client_id;
10 | public String client_key;
11 | public String refresh_token;
12 |
13 | public RefreshTokenRequestModel() {
14 | this.client_id = ClientConfigs.CLIENT_ID;
15 | this.client_key = ClientConfigs.CLIENT_KEY;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/models/SignInRequestModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.models;
2 |
3 | import com.atahani.retrofit_sample.utility.ClientConfigs;
4 |
5 | /**
6 | * Sgin in Requst model used in sign in request
7 | */
8 | public class SignInRequestModel {
9 | public String client_id;
10 | public String client_key;
11 | public String email;
12 | public String password;
13 |
14 | public SignInRequestModel() {
15 | this.client_id = ClientConfigs.CLIENT_ID;
16 | this.client_key = ClientConfigs.CLIENT_KEY;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/models/SignUpRequestModel.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.models;
2 |
3 | import com.atahani.retrofit_sample.utility.ClientConfigs;
4 |
5 | /**
6 | * Sign up Request model used in sign up Request
7 | */
8 | public class SignUpRequestModel {
9 | public String client_id;
10 | public String client_key;
11 | public String name;
12 | public String email;
13 | public String password;
14 |
15 | public SignUpRequestModel() {
16 | this.client_id = ClientConfigs.CLIENT_ID;
17 | this.client_key = ClientConfigs.CLIENT_KEY;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/utility/ClientConfigs.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.utility;
2 |
3 | /**
4 | * contain client information such as BASE_URL || client information
5 | */
6 | public class ClientConfigs {
7 | //TODO: should get network ip address like 192.168.1.2 and replace inside REST_API_BASE_URL
8 | public static final String REST_API_BASE_URL = "http://IP_ADDRESS:8081/api/v1/";
9 | //TODO: create new Client with postman in http://localshot:/api/v1/client with body {"name":"android client app"} and set these values with client_id and client_key
10 | public static final String CLIENT_ID = "";
11 | public static final String CLIENT_KEY = "";
12 | }
13 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Applications/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/utility/Constants.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.utility;
2 |
3 | /**
4 | * Constant used in this retrofit sample
5 | */
6 | public class Constants {
7 |
8 | //request codes
9 | public static final int CREATE_OR_EDIT_TWEET_REQUEST_CODE = 7;
10 | public static final int UPDATE_USER_PROFILE_REQUEST_CODE = 8;
11 | public static final int GALLERY_REQUEST_CODE = 12;
12 | public static final int FOR_OPEN_GALLERY_REQUEST_WRITE_EXTERNAL_STORAGE_PER = 13;
13 |
14 | //keys
15 | public static final String ACTION_TO_DO_KEY = "ACTION_TO_DO_KEY";
16 | public static final String TWEET_ID_KEY = "TWEET_ID_KEY";
17 |
18 | //type of actions
19 | public static final int DO_NOTHING = 0;
20 | public static final int UPDATE_FROM_NET = 1;
21 | public static final int EDIT_TWEET = 2;
22 | public static final int NEW_TWEET = 3;
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Fake Twitter
3 | pref_access_token
4 | pref_expire_in_sec
5 | pref_expire_at
6 | pref_refresh_token
7 | pref_app_id
8 | pref_user_id
9 | pref_user_email
10 | pref_user_name
11 | pref_user_image_url
12 | Sign in
13 | SignUpActivity
14 |
15 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "com.atahani.retrofit_sample"
9 | minSdkVersion 17
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.2.1'
26 | compile 'com.android.support:design:23.2.1'
27 | compile 'com.android.support:recyclerview-v7:23.2.1'
28 | compile('com.squareup.retrofit2:retrofit:2.0.0-beta4') {
29 | exclude module: 'okhttp'
30 | }
31 | compile 'com.squareup.okhttp3:okhttp:3.0.0'
32 | compile 'com.squareup.picasso:picasso:2.5.2'
33 | compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
34 | }
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2016 Ahmad Tahani
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 | SOFTWARE.
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_default.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/utility/ErrorUtils.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.utility;
2 |
3 | import com.atahani.retrofit_sample.models.ErrorModel;
4 | import com.atahani.retrofit_sample.network.FakeTwitterProvider;
5 |
6 | import java.io.IOException;
7 | import java.lang.annotation.Annotation;
8 |
9 | import okhttp3.ResponseBody;
10 | import retrofit2.Converter;
11 | import retrofit2.Response;
12 |
13 | /**
14 | * this class help to parse the response to ErrorModel when using from Retrofit
15 | */
16 | public class ErrorUtils {
17 |
18 | public static ErrorModel parseError(Response> response) {
19 | FakeTwitterProvider fakeTwitterProvider = new FakeTwitterProvider();
20 |
21 | //using Converter for convert error response body into Error Model
22 | Converter converter = fakeTwitterProvider.getRetrofitClient().responseBodyConverter(ErrorModel.class, new Annotation[0]);
23 |
24 | ErrorModel errorModel;
25 |
26 | try {
27 | errorModel = converter.convert(response.errorBody());
28 |
29 | } catch (IOException e) {
30 | return new ErrorModel();
31 | }
32 |
33 | return errorModel;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_edit_user_profile.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
15 |
16 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/utility/CropCircleTransformation.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.utility;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.BitmapShader;
5 | import android.graphics.Canvas;
6 | import android.graphics.Paint;
7 |
8 | import com.squareup.picasso.Transformation;
9 |
10 | /**
11 | * Circle transformation for picasso
12 | */
13 | public class CropCircleTransformation implements Transformation {
14 | @Override
15 | public Bitmap transform(Bitmap source) {
16 | int size = Math.min(source.getWidth(), source.getHeight());
17 |
18 | int x = (source.getWidth() - size) / 2;
19 | int y = (source.getHeight() - size) / 2;
20 |
21 | Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
22 | if (squaredBitmap != source) {
23 | source.recycle();
24 | }
25 |
26 | Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
27 |
28 | Canvas canvas = new Canvas(bitmap);
29 | Paint paint = new Paint();
30 | BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
31 | paint.setShader(shader);
32 | paint.setAntiAlias(true);
33 |
34 | float r = size / 2f;
35 | canvas.drawCircle(r, r, r, paint);
36 |
37 | squaredBitmap.recycle();
38 | return bitmap;
39 | }
40 |
41 | @Override
42 | public String key() {
43 | return "circle";
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### Retrofit Sample Project
2 |
3 | this project create for [Retrofit Tutorial](https://www.youtube.com/playlist?list=PL-0EQDLPE23N3WkenBrZzTLfnOIAIybKm), fake Twitter client with these feature :
4 |
5 | * user can post new tweet
6 | * user can edit or delete tweet
7 | * custom gson converter
8 | * custom error handling
9 | * sign up / sign in with email address
10 | * refresh token when access token expired
11 | * update user profile
12 | * upload image user
13 | * search in tweets by feel
14 |
15 | ### how can use from this project
16 |
17 | 1- the backend deploy with `Node.js`, install [Node.js](nodejs.org) then clone [this repo](https://github.com/atahani/rest-api-sample) and checkout related branch, remember install `Node.js Module` via `npm`
18 |
19 | ```
20 | $ git clone https://github.com/atahani/rest-api-sample
21 | $ cd rest-api-sample
22 | $ git branch -a | grep -v HEAD | perl -ne 'chomp($_); s|^\*?\s*||; if (m|(.+)/(.+)| && not $d{$2}) {print qq(git branch --track $2 $1/$2\n)} else {$d{$_}=1}' | csh -xfs
23 | $ git checkout simple_rest_api
24 | $ npm install
25 | $ node server.js
26 | ```
27 |
28 | 2 - repo contain different branches in multiple steps, so you should clone this repo and checkout related branch
29 |
30 | ```
31 | $ git clone https://github.com/atahani/retrofit-sample
32 | $ cd retrofit-sample
33 | $ git branch -a | grep -v HEAD | perl -ne 'chomp($_); s|^\*?\s*||; if (m|(.+)/(.+)| && not $d{$2}) {print qq(git branch --track $2 $1/$2\n)} else {$d{$_}=1}' | csh -xfs
34 | $ git checkout 01_configure_project
35 | ```
36 |
37 | 3- set the `REST_API_BASE_URL`, `CLIENT_ID` and `CLIENT_KEY` values inside `ClientConfigs.java` class
38 |
39 | NOTE: this application just create to demonstrate how we can use from [Retrofit](square.github.io/retrofit/) to talk with REST API
40 |
41 | ### for more information see the slide and videos
42 |
43 | * [Youtube Playlist link](https://www.youtube.com/playlist?list=PL-0EQDLPE23N3WkenBrZzTLfnOIAIybKm)
44 | * [Slides on Google Slide](https://goo.gl/lzwXys)
45 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/network/UTCDateTypeAdapter.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.network;
2 |
3 | import com.google.gson.JsonDeserializationContext;
4 | import com.google.gson.JsonDeserializer;
5 | import com.google.gson.JsonElement;
6 | import com.google.gson.JsonPrimitive;
7 | import com.google.gson.JsonSerializationContext;
8 | import com.google.gson.JsonSerializer;
9 | import com.google.gson.JsonSyntaxException;
10 |
11 | import java.lang.reflect.Type;
12 | import java.text.DateFormat;
13 | import java.text.ParseException;
14 | import java.text.SimpleDateFormat;
15 | import java.util.Date;
16 | import java.util.Locale;
17 | import java.util.TimeZone;
18 |
19 | /**
20 | * define UTCDateTypeAdapterDateAdapter as convert JSON DateTime as Date Value with UTC format
21 | */
22 | public class UTCDateTypeAdapter implements JsonSerializer,
23 | JsonDeserializer {
24 | private final DateFormat dateFormat;
25 |
26 | UTCDateTypeAdapter() {
27 | dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
28 | dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
29 | }
30 |
31 | @Override
32 | public synchronized JsonElement serialize(Date date, Type type,
33 | JsonSerializationContext jsonSerializationContext) {
34 | synchronized (dateFormat) {
35 | String dateFormatAsString = dateFormat.format(date);
36 | return new JsonPrimitive(dateFormatAsString);
37 | }
38 | }
39 |
40 | @Override
41 | public synchronized Date deserialize(JsonElement jsonElement, Type type,
42 | JsonDeserializationContext jsonDeserializationContext) {
43 | try {
44 | synchronized (dateFormat) {
45 | return dateFormat.parse(jsonElement.getAsString());
46 | }
47 | } catch (ParseException e) {
48 | throw new JsonSyntaxException(jsonElement.getAsString(), e);
49 | }
50 | }
51 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_sign_up.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
15 |
16 |
24 |
25 |
31 |
32 |
38 |
39 |
45 |
46 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_sign_in.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
15 |
16 |
24 |
25 |
26 |
32 |
33 |
39 |
40 |
45 |
46 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/osx,android,intellij
3 |
4 | ### OSX ###
5 | .DS_Store
6 | .AppleDouble
7 | .LSOverride
8 |
9 | # Icon must end with two \r
10 | Icon
11 |
12 |
13 | # Thumbnails
14 | ._*
15 |
16 | # Files that might appear in the root of a volume
17 | .DocumentRevisions-V100
18 | .fseventsd
19 | .Spotlight-V100
20 | .TemporaryItems
21 | .Trashes
22 | .VolumeIcon.icns
23 |
24 | # Directories potentially created on remote AFP share
25 | .AppleDB
26 | .AppleDesktop
27 | Network Trash Folder
28 | Temporary Items
29 | .apdisk
30 |
31 |
32 | ### Android ###
33 | # Built application files
34 | *.apk
35 | *.ap_
36 |
37 | # Files for the Dalvik VM
38 | *.dex
39 |
40 | # Java class files
41 | *.class
42 |
43 | # Generated files
44 | bin/
45 | gen/
46 | out/
47 |
48 | # Gradle files
49 | .gradle/
50 | build/
51 |
52 | # Local configuration file (sdk path, etc)
53 | local.properties
54 |
55 | # Proguard folder generated by Eclipse
56 | proguard/
57 |
58 | # Log Files
59 | *.log
60 |
61 | # Android Studio Navigation editor temp files
62 | .navigation/
63 |
64 | # Android Studio captures folder
65 | captures/
66 |
67 | # Intellij
68 | *.iml
69 |
70 | ### Android Patch ###
71 | gen-external-apklibs
72 |
73 |
74 | ### Intellij ###
75 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
76 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
77 | .idea/*
78 | # User-specific stuff:
79 | .idea/workspace.xml
80 | .idea/tasks.xml
81 | .idea/dictionaries
82 | .idea/vcs.xml
83 | .idea/jsLibraryMappings.xml
84 |
85 | # Sensitive or high-churn files:
86 | .idea/dataSources.ids
87 | .idea/dataSources.xml
88 | .idea/dataSources.local.xml
89 | .idea/sqlDataSources.xml
90 | .idea/dynamic.xml
91 | .idea/uiDesigner.xml
92 |
93 | # Gradle:
94 | .idea/gradle.xml
95 | .idea/libraries
96 |
97 | # Mongo Explorer plugin:
98 | .idea/mongoSettings.xml
99 |
100 | ## File-based project format:
101 | *.iws
102 |
103 | ## Plugin-specific files:
104 |
105 | # IntelliJ
106 | /out/
107 |
108 | # mpeltonen/sbt-idea plugin
109 | .idea_modules/
110 |
111 | # JIRA plugin
112 | atlassian-ide-plugin.xml
113 |
114 | # Crashlytics plugin (for Android Studio and IntelliJ)
115 | com_crashlytics_export_strings.xml
116 | crashlytics.properties
117 | crashlytics-build.properties
118 | fabric.properties
119 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/network/FakeTwitterService.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.network;
2 |
3 | import com.atahani.retrofit_sample.adapter.OperationResultModel;
4 | import com.atahani.retrofit_sample.models.AuthenticationResponseModel;
5 | import com.atahani.retrofit_sample.models.RefreshTokenRequestModel;
6 | import com.atahani.retrofit_sample.models.SignInRequestModel;
7 | import com.atahani.retrofit_sample.models.SignUpRequestModel;
8 | import com.atahani.retrofit_sample.models.TokenModel;
9 | import com.atahani.retrofit_sample.models.TweetModel;
10 | import com.atahani.retrofit_sample.models.UserModel;
11 |
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | import okhttp3.RequestBody;
16 | import retrofit2.Call;
17 | import retrofit2.http.Body;
18 | import retrofit2.http.DELETE;
19 | import retrofit2.http.GET;
20 | import retrofit2.http.Header;
21 | import retrofit2.http.Multipart;
22 | import retrofit2.http.POST;
23 | import retrofit2.http.PUT;
24 | import retrofit2.http.PartMap;
25 | import retrofit2.http.Path;
26 | import retrofit2.http.Query;
27 |
28 | /**
29 | * the interface implements REST API routes
30 | */
31 | public interface FakeTwitterService {
32 |
33 | @POST("tweet")
34 | Call createNewTweet(@Body TweetModel tweetModel);
35 |
36 | @GET("tweet")
37 | Call> getTweets();
38 |
39 | @GET("tweet/{id}")
40 | Call getTweetById(@Path("id") String tweetId);
41 |
42 | @PUT("tweet/{id}")
43 | Call updateTweetById(@Path("id") String tweetId, @Body TweetModel tweetModel);
44 |
45 | @DELETE("tweet/{id}")
46 | Call deleteTweetById(@Path("id") String tweetId);
47 |
48 | @POST("signup")
49 | Call signUp(@Body SignUpRequestModel signUpRequestModel);
50 |
51 | @POST("signin")
52 | Call signIn(@Body SignInRequestModel signInRequestModel);
53 |
54 | @DELETE("user/app")
55 | Call terminateApp();
56 |
57 | @PUT("user/profile")
58 | Call updateUserProfile(@Body UserModel userModel);
59 |
60 | @Multipart
61 | @POST("user/profile/image")
62 | Call uploadUserProfileImage(@Header("Authorization") String authHeader, @PartMap Map map);
63 |
64 | @DELETE("tokens")
65 | Call removeAllAccessToken();
66 |
67 | @POST("refreshtoken")
68 | Call getRefreshToken(@Body RefreshTokenRequestModel refreshTokenRequestModel);
69 |
70 | @GET("tweet")
71 | Call> getTweetsByFeel(@Query("feel") String feel);
72 | }
73 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_create_or_edit_tweet.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
15 |
16 |
24 |
25 |
33 |
34 |
42 |
43 |
51 |
52 |
53 |
64 |
65 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/tweet_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
16 |
17 |
29 |
30 |
41 |
42 |
53 |
54 |
64 |
65 |
66 |
73 |
74 |
81 |
82 |
83 |
89 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
21 |
22 |
30 |
31 |
41 |
42 |
43 |
44 |
45 |
53 |
54 |
62 |
63 |
71 |
72 |
80 |
81 |
82 |
87 |
88 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/ui/EditUserProfile.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.ui;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.support.v7.widget.AppCompatEditText;
6 | import android.support.v7.widget.Toolbar;
7 | import android.view.Menu;
8 | import android.view.MenuItem;
9 | import android.widget.Toast;
10 |
11 | import com.atahani.retrofit_sample.R;
12 | import com.atahani.retrofit_sample.models.ErrorModel;
13 | import com.atahani.retrofit_sample.models.UserModel;
14 | import com.atahani.retrofit_sample.network.FakeTwitterProvider;
15 | import com.atahani.retrofit_sample.network.FakeTwitterService;
16 | import com.atahani.retrofit_sample.utility.AppPreferenceTools;
17 | import com.atahani.retrofit_sample.utility.Constants;
18 | import com.atahani.retrofit_sample.utility.ErrorUtils;
19 |
20 | import retrofit2.Call;
21 | import retrofit2.Callback;
22 | import retrofit2.Response;
23 |
24 | public class EditUserProfile extends AppCompatActivity {
25 |
26 | private AppCompatEditText mETxName;
27 | private AppPreferenceTools mAppPreferenceTools;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_edit_user_profile);
33 | mAppPreferenceTools = new AppPreferenceTools(this);
34 | Toolbar toolbar = (Toolbar) findViewById(R.id.default_toolbar);
35 | setSupportActionBar(toolbar);
36 | getSupportActionBar().setTitle("");
37 | getSupportActionBar().setDisplayHomeAsUpEnabled(true);
38 | mETxName = (AppCompatEditText) findViewById(R.id.etx_name);
39 | //bind the name to edit text
40 | mETxName.setText(mAppPreferenceTools.getUserName());
41 | }
42 |
43 | @Override
44 | public boolean onCreateOptionsMenu(Menu menu) {
45 | getMenuInflater().inflate(R.menu.menu_edit, menu);
46 | return super.onCreateOptionsMenu(menu);
47 | }
48 |
49 | @Override
50 | public boolean onOptionsItemSelected(MenuItem item) {
51 | int id = item.getItemId();
52 | if (id == android.R.id.home) {
53 | onBackPressed();
54 | } else if (id == R.id.action_edit) {
55 | //check is name is not empty
56 | if (mETxName.getText().toString().trim().length() > 0) {
57 | //should update the name
58 | UserModel userModel = new UserModel();
59 | userModel.name = mETxName.getText().toString();
60 | //provide the service
61 | FakeTwitterProvider provider = new FakeTwitterProvider();
62 | FakeTwitterService tService = provider.getTService();
63 | //make call
64 | Call call = tService.updateUserProfile(userModel);
65 | call.enqueue(new Callback() {
66 | @Override
67 | public void onResponse(Call call, Response response) {
68 | //
69 | if (response.isSuccess()) {
70 | //update the value in pref
71 | mAppPreferenceTools.saveUserModel(response.body());
72 | //navigate to parent activity set result to update name value
73 | setResult(RESULT_OK);
74 | //finish this activity
75 | finish();
76 | } else {
77 | ErrorModel errorModel = ErrorUtils.parseError(response);
78 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
79 | }
80 | }
81 |
82 | @Override
83 | public void onFailure(Call call, Throwable t) {
84 | //occur when fail to deserialize || no network connection || server unavailable
85 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
86 | }
87 | });
88 | } else {
89 | Toast.makeText(getBaseContext(), "name field is empty", Toast.LENGTH_SHORT).show();
90 | }
91 | }
92 | return super.onContextItemSelected(item);
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/ui/SignUpActivity.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.ui;
2 |
3 | import android.content.Intent;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.support.v7.widget.AppCompatButton;
7 | import android.support.v7.widget.AppCompatEditText;
8 | import android.view.View;
9 | import android.widget.Toast;
10 |
11 | import com.atahani.retrofit_sample.R;
12 | import com.atahani.retrofit_sample.models.AuthenticationResponseModel;
13 | import com.atahani.retrofit_sample.models.ErrorModel;
14 | import com.atahani.retrofit_sample.models.SignUpRequestModel;
15 | import com.atahani.retrofit_sample.network.FakeTwitterProvider;
16 | import com.atahani.retrofit_sample.network.FakeTwitterService;
17 | import com.atahani.retrofit_sample.utility.AppPreferenceTools;
18 | import com.atahani.retrofit_sample.utility.ErrorUtils;
19 |
20 | import retrofit2.Call;
21 | import retrofit2.Callback;
22 | import retrofit2.Response;
23 |
24 | public class SignUpActivity extends AppCompatActivity {
25 |
26 | private AppCompatEditText mETxName;
27 | private AppCompatEditText mETxEmail;
28 | private AppCompatEditText mETxPassword;
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 | setContentView(R.layout.activity_sign_up);
34 | mETxName = (AppCompatEditText) findViewById(R.id.etx_name);
35 | mETxEmail = (AppCompatEditText) findViewById(R.id.etx_email);
36 | mETxPassword = (AppCompatEditText) findViewById(R.id.etx_password);
37 | AppCompatButton btnSignUp = (AppCompatButton) findViewById(R.id.btn_sign_up);
38 | if (btnSignUp != null) {
39 | btnSignUp.setOnClickListener(new View.OnClickListener() {
40 | @Override
41 | public void onClick(View v) {
42 | //check fields not empty
43 | if (mETxName.getText().toString().trim().length() > 0 && mETxEmail.getText().toString().trim().length() > 0 && mETxPassword.getText().toString().trim().length() > 3) {
44 | //sign up the new user
45 | SignUpRequestModel requestModel = new SignUpRequestModel();
46 | requestModel.email = mETxEmail.getText().toString();
47 | requestModel.name = mETxName.getText().toString();
48 | requestModel.password = mETxPassword.getText().toString();
49 | //provide service
50 | FakeTwitterProvider provider = new FakeTwitterProvider();
51 | FakeTwitterService tService = provider.getTService();
52 | //make call
53 | Call call = tService.signUp(requestModel);
54 | call.enqueue(new Callback() {
55 | @Override
56 | public void onResponse(Call call, Response response) {
57 | if (response.isSuccess()) {
58 | //save the authorization information into pref
59 | AppPreferenceTools appPreferenceTools = new AppPreferenceTools(getBaseContext());
60 | appPreferenceTools.saveUserAuthenticationInfo(response.body());
61 | //navigate to main activity
62 | startActivity(new Intent(getBaseContext(),MainActivity.class));
63 | //finish this activity
64 | finish();
65 | } else {
66 | ErrorModel errorModel = ErrorUtils.parseError(response);
67 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
68 | }
69 | }
70 |
71 | @Override
72 | public void onFailure(Call call, Throwable t) {
73 | //occur when fail to deserialize || no network connection || server unavailable
74 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
75 | }
76 | });
77 | } else {
78 | Toast.makeText(getBaseContext(), "fields are empty, password should 4 char", Toast.LENGTH_SHORT).show();
79 | }
80 | }
81 | });
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/ui/SignInActivity.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.ui;
2 |
3 | import android.content.Intent;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.support.v7.widget.AppCompatButton;
7 | import android.support.v7.widget.AppCompatEditText;
8 | import android.view.View;
9 | import android.widget.Toast;
10 |
11 | import com.atahani.retrofit_sample.R;
12 | import com.atahani.retrofit_sample.models.AuthenticationResponseModel;
13 | import com.atahani.retrofit_sample.models.ErrorModel;
14 | import com.atahani.retrofit_sample.models.SignInRequestModel;
15 | import com.atahani.retrofit_sample.network.FakeTwitterProvider;
16 | import com.atahani.retrofit_sample.network.FakeTwitterService;
17 | import com.atahani.retrofit_sample.utility.AppPreferenceTools;
18 | import com.atahani.retrofit_sample.utility.ErrorUtils;
19 |
20 | import retrofit2.Call;
21 | import retrofit2.Callback;
22 | import retrofit2.Response;
23 |
24 | public class SignInActivity extends AppCompatActivity {
25 |
26 | private AppCompatEditText mETxEmail;
27 | private AppCompatEditText mETxPassword;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_sign_in);
33 | mETxEmail = (AppCompatEditText) findViewById(R.id.etx_email);
34 | mETxPassword = (AppCompatEditText) findViewById(R.id.etx_password);
35 | AppCompatButton btnSignIn = (AppCompatButton) findViewById(R.id.btn_sign_in);
36 | if (btnSignIn != null) {
37 | btnSignIn.setOnClickListener(new View.OnClickListener() {
38 | @Override
39 | public void onClick(View v) {
40 | //check field are not empty
41 | if (mETxEmail.getText().toString().trim().length() > 0 && mETxPassword.getText().toString().trim().length() > 3) {
42 | //send information to sign in
43 | SignInRequestModel signInRequestModel = new SignInRequestModel();
44 | signInRequestModel.email = mETxEmail.getText().toString();
45 | signInRequestModel.password = mETxPassword.getText().toString();
46 | //provide service
47 | FakeTwitterProvider provider = new FakeTwitterProvider();
48 | FakeTwitterService tService = provider.getTService();
49 | //make call
50 | Call call = tService.signIn(signInRequestModel);
51 | call.enqueue(new Callback() {
52 | @Override
53 | public void onResponse(Call call, Response response) {
54 | if (response.isSuccess()) {
55 | AppPreferenceTools appPreferenceTools = new AppPreferenceTools(getBaseContext());
56 | appPreferenceTools.saveUserAuthenticationInfo(response.body());
57 | //navigate to main activity
58 | startActivity(new Intent(getBaseContext(), MainActivity.class));
59 | //finish this activity
60 | finish();
61 | } else {
62 | ErrorModel errorModel = ErrorUtils.parseError(response);
63 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
64 | }
65 | }
66 |
67 | @Override
68 | public void onFailure(Call call, Throwable t) {
69 | //occur when fail to deserialize || no network connection || server unavailable
70 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
71 | }
72 | });
73 | } else {
74 | Toast.makeText(getBaseContext(), "fields are empty", Toast.LENGTH_SHORT).show();
75 | }
76 | }
77 | });
78 | AppCompatButton btnGoToSignUp = (AppCompatButton) findViewById(R.id.btn_go_to_sign_up);
79 | if (btnGoToSignUp != null) {
80 | btnGoToSignUp.setOnClickListener(new View.OnClickListener() {
81 | @Override
82 | public void onClick(View v) {
83 | //navigate to sign up activity
84 | startActivity(new Intent(getBaseContext(),SignUpActivity.class));
85 | //finish this activity
86 | finish();
87 | }
88 | });
89 | }
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/utility/AppPreferenceTools.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.utility;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 |
6 | import com.atahani.retrofit_sample.R;
7 | import com.atahani.retrofit_sample.models.AuthenticationResponseModel;
8 | import com.atahani.retrofit_sample.models.TokenModel;
9 | import com.atahani.retrofit_sample.models.UserModel;
10 |
11 | /**
12 | * for better management of preference in application
13 | * like authentication information
14 | */
15 | public class AppPreferenceTools {
16 |
17 | private SharedPreferences mPreference;
18 | private Context mContext;
19 | public static final String STRING_PREF_UNAVAILABLE = "string preference unavailable";
20 |
21 | public AppPreferenceTools(Context context) {
22 | this.mContext = context;
23 | this.mPreference = this.mContext.getSharedPreferences("app_preference", Context.MODE_PRIVATE);
24 | }
25 |
26 | /**
27 | * save the user authentication model to pref at sing up || sign in
28 | *
29 | * @param authModel
30 | */
31 | public void saveUserAuthenticationInfo(AuthenticationResponseModel authModel) {
32 | mPreference.edit()
33 | .putString(this.mContext.getString(R.string.pref_access_token), authModel.token.access_token)
34 | .putLong(this.mContext.getString(R.string.pref_expire_in_sec), authModel.token.expire_in_sec)
35 | .putLong(this.mContext.getString(R.string.pref_expire_at), authModel.token.expire_at.getTime())
36 | .putString(this.mContext.getString(R.string.pref_refresh_token), authModel.token.refresh_token)
37 | .putString(this.mContext.getString(R.string.pref_app_id), authModel.token.app_id)
38 | .putString(this.mContext.getString(R.string.pref_user_id), authModel.user_profile.id)
39 | .putString(this.mContext.getString(R.string.pref_user_email), authModel.user_profile.email)
40 | .putString(this.mContext.getString(R.string.pref_user_name), authModel.user_profile.name)
41 | .putString(this.mContext.getString(R.string.pref_user_image_url), authModel.user_profile.imageUrl)
42 | .apply();
43 | }
44 |
45 | /**
46 | * save the user model when user profile updated
47 | *
48 | * @param userModel
49 | */
50 | public void saveUserModel(UserModel userModel) {
51 | mPreference.edit()
52 | .putString(this.mContext.getString(R.string.pref_user_id), userModel.id)
53 | .putString(this.mContext.getString(R.string.pref_user_email), userModel.email)
54 | .putString(this.mContext.getString(R.string.pref_user_name), userModel.name)
55 | .putString(this.mContext.getString(R.string.pref_user_image_url), userModel.imageUrl)
56 | .apply();
57 | }
58 |
59 | /**
60 | * save token model used in refresh token
61 | * @param tokenModel
62 | */
63 | public void saveTokenModel(TokenModel tokenModel) {
64 | mPreference.edit()
65 | .putString(this.mContext.getString(R.string.pref_access_token), tokenModel.access_token)
66 | .putLong(this.mContext.getString(R.string.pref_expire_in_sec), tokenModel.expire_in_sec)
67 | .putLong(this.mContext.getString(R.string.pref_expire_at), tokenModel.expire_at.getTime())
68 | .putString(this.mContext.getString(R.string.pref_refresh_token), tokenModel.refresh_token)
69 | .putString(this.mContext.getString(R.string.pref_app_id), tokenModel.app_id)
70 | .apply();
71 | }
72 |
73 | /**
74 | * get access token
75 | *
76 | * @return
77 | */
78 | public String getAccessToken() {
79 | return mPreference.getString(this.mContext.getString(R.string.pref_access_token), STRING_PREF_UNAVAILABLE);
80 | }
81 |
82 | /**
83 | * detect is user sign in
84 | *
85 | * @return
86 | */
87 | public boolean isAuthorized() {
88 | return !getAccessToken().equals(STRING_PREF_UNAVAILABLE);
89 | }
90 |
91 |
92 | /**
93 | * get user name
94 | *
95 | * @return
96 | */
97 | public String getUserName() {
98 | return mPreference.getString(this.mContext.getString(R.string.pref_user_name), "");
99 | }
100 |
101 | public String getImageProfileUrl() {
102 | return mPreference.getString(this.mContext.getString(R.string.pref_user_image_url), "");
103 | }
104 |
105 | public String getUserId() {
106 | return mPreference.getString(this.mContext.getString(R.string.pref_user_id), "");
107 | }
108 |
109 | /**
110 | * get refresh token
111 | *
112 | * @return
113 | */
114 | public String getRefreshToken() {
115 | return mPreference.getString(this.mContext.getString(R.string.pref_refresh_token), "");
116 | }
117 |
118 | /**
119 | * remove all prefs in logout
120 | */
121 | public void removeAllPrefs() {
122 | mPreference.edit().clear().apply();
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/network/FakeTwitterProvider.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.network;
2 |
3 |
4 | import com.atahani.retrofit_sample.TApplication;
5 | import com.atahani.retrofit_sample.models.RefreshTokenRequestModel;
6 | import com.atahani.retrofit_sample.models.TokenModel;
7 | import com.atahani.retrofit_sample.utility.AppPreferenceTools;
8 | import com.atahani.retrofit_sample.utility.ClientConfigs;
9 | import com.google.gson.Gson;
10 | import com.google.gson.GsonBuilder;
11 |
12 | import java.io.IOException;
13 | import java.util.Date;
14 |
15 | import okhttp3.Authenticator;
16 | import okhttp3.Interceptor;
17 | import okhttp3.OkHttpClient;
18 | import okhttp3.Request;
19 | import okhttp3.Response;
20 | import okhttp3.Route;
21 | import retrofit2.Call;
22 | import retrofit2.Retrofit;
23 | import retrofit2.converter.gson.GsonConverterFactory;
24 |
25 | /**
26 | * this class make Retrofit API Service
27 | */
28 | public class FakeTwitterProvider {
29 |
30 | private FakeTwitterService mTService;
31 | private Retrofit mRetrofitClient;
32 | private AppPreferenceTools mAppPreferenceTools;
33 |
34 | /**
35 | * config Retrofit in initialization
36 | */
37 | public FakeTwitterProvider() {
38 | this.mAppPreferenceTools = new AppPreferenceTools(TApplication.applicationContext);
39 | OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
40 | //add http interceptor to add headers to each request
41 | httpClient.addInterceptor(new Interceptor() {
42 | @Override
43 | public Response intercept(Chain chain) throws IOException {
44 | Request original = chain.request();
45 | String originalPath = original.url().url().getPath();
46 | if (originalPath.endsWith("user/profile/image") || originalPath.endsWith("refreshtoken")) {
47 | return chain.proceed(original);
48 | } else {
49 | //build request
50 | Request.Builder requestBuilder = original.newBuilder();
51 | //add header for all of the request
52 | requestBuilder.addHeader("Accept", "application/json");
53 | //check is user logged in , if yes should add authorization header to every request
54 | if (mAppPreferenceTools.isAuthorized()) {
55 | requestBuilder.addHeader("Authorization", "bearer " + mAppPreferenceTools.getAccessToken());
56 | }
57 | requestBuilder.method(original.method(), original.body());
58 | Request request = requestBuilder.build();
59 | return chain.proceed(request);
60 | }
61 | }
62 | });
63 | //when request get 401 http error code this method run and get refreshToken and send original request again
64 | httpClient.authenticator(new Authenticator() {
65 | @Override
66 | public Request authenticate(Route route, Response response) throws IOException {
67 | if (mAppPreferenceTools.isAuthorized()) {
68 | //make the refresh token request model
69 | RefreshTokenRequestModel requestModel = new RefreshTokenRequestModel();
70 | requestModel.refresh_token = mAppPreferenceTools.getRefreshToken();
71 | //make call
72 | Call call = mTService.getRefreshToken(requestModel);
73 | retrofit2.Response tokenModelResponse = call.execute();
74 | if (tokenModelResponse.isSuccess()) {
75 | mAppPreferenceTools.saveTokenModel(tokenModelResponse.body());
76 | return response.request().newBuilder()
77 | .removeHeader("Authorization")
78 | .addHeader("Authorization", "bearer " + mAppPreferenceTools.getAccessToken())
79 | .build();
80 | } else {
81 | return null;
82 | }
83 | } else {
84 | return null;
85 | }
86 | }
87 | });
88 | //create new gson object to define custom converter on Date type
89 | Gson gson = new GsonBuilder()
90 | .registerTypeAdapter(Date.class, new UTCDateTypeAdapter())
91 | .create();
92 |
93 | mRetrofitClient = new Retrofit.Builder()
94 | .baseUrl(ClientConfigs.REST_API_BASE_URL) // set Base URL , should end with '/'
95 | .client(httpClient.build()) // add http client
96 | .addConverterFactory(GsonConverterFactory.create(gson))//add gson converter
97 | .build();
98 | mTService = mRetrofitClient.create(FakeTwitterService.class);
99 | }
100 |
101 | /**
102 | * can get Retrofit Service
103 | *
104 | * @return
105 | */
106 | public FakeTwitterService getTService() {
107 | return mTService;
108 | }
109 |
110 | /**
111 | * get Retrofit client
112 | * used in ErrorUtil class
113 | *
114 | * @return
115 | */
116 | public Retrofit getRetrofitClient() {
117 | return mRetrofitClient;
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/utility/AndroidUtilities.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.utility;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.ContentUris;
5 | import android.content.Context;
6 | import android.database.Cursor;
7 | import android.net.Uri;
8 | import android.os.Build;
9 | import android.os.Environment;
10 | import android.provider.DocumentsContract;
11 | import android.provider.MediaStore;
12 | import android.util.Log;
13 |
14 | import com.atahani.retrofit_sample.TApplication;
15 |
16 | import java.io.File;
17 | import java.text.SimpleDateFormat;
18 | import java.util.Date;
19 | import java.util.Locale;
20 |
21 | /**
22 | *
23 | */
24 | public class AndroidUtilities {
25 |
26 | private static File getAlbumDir() {
27 | File storageDir = null;
28 | if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
29 | storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Telepathy");
30 | if (!storageDir.mkdirs()) {
31 | if (!storageDir.exists()) {
32 | Log.d("android_utilities", "failed to create directory");
33 | return null;
34 | }
35 | }
36 | } else {
37 | Log.d("android_utilities", "External storage is not mounted READ/WRITE.");
38 | }
39 | return storageDir;
40 | }
41 |
42 | public static File generateImagePath() {
43 | try {
44 | File storageDir = getAlbumDir();
45 | String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
46 | return new File(storageDir, "IMG_" + timeStamp + ".jpeg");
47 | } catch (Exception e) {
48 | Log.d("android_utilities", "the error is " + e);
49 | }
50 | return null;
51 | }
52 |
53 | public static boolean isExternalStorageDocument(Uri uri) {
54 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
55 | }
56 |
57 | public static boolean isDownloadsDocument(Uri uri) {
58 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
59 | }
60 |
61 | public static boolean isMediaDocument(Uri uri) {
62 | return "com.android.providers.media.documents".equals(uri.getAuthority());
63 | }
64 |
65 | @SuppressLint("NewApi")
66 | public static String getPath(final Uri uri) {
67 | try {
68 | final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
69 | if (isKitKat && DocumentsContract.isDocumentUri(TApplication.applicationContext, uri)) {
70 | if (isExternalStorageDocument(uri)) {
71 | final String docId = DocumentsContract.getDocumentId(uri);
72 | final String[] split = docId.split(":");
73 | final String type = split[0];
74 | if ("primary".equalsIgnoreCase(type)) {
75 | return Environment.getExternalStorageDirectory() + "/" + split[1];
76 | }
77 | } else if (isDownloadsDocument(uri)) {
78 | final String id = DocumentsContract.getDocumentId(uri);
79 | final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
80 | return getDataColumn(TApplication.applicationContext, contentUri, null, null);
81 | } else if (isMediaDocument(uri)) {
82 | final String docId = DocumentsContract.getDocumentId(uri);
83 | final String[] split = docId.split(":");
84 | final String type = split[0];
85 |
86 | Uri contentUri = null;
87 | switch (type) {
88 | case "image":
89 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
90 | break;
91 | case "video":
92 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
93 | break;
94 | case "audio":
95 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
96 | break;
97 | }
98 |
99 | final String selection = "_id=?";
100 | final String[] selectionArgs = new String[]{
101 | split[1]
102 | };
103 |
104 | return getDataColumn(TApplication.applicationContext, contentUri, selection, selectionArgs);
105 | }
106 | } else if ("content".equalsIgnoreCase(uri.getScheme())) {
107 | return getDataColumn(TApplication.applicationContext, uri, null, null);
108 | } else if ("file".equalsIgnoreCase(uri.getScheme())) {
109 | return uri.getPath();
110 | }
111 | } catch (Exception e) {
112 | Log.d("android_utilities", "the error is " + e);
113 | }
114 | return null;
115 | }
116 |
117 | public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
118 |
119 | Cursor cursor = null;
120 | final String column = "_data";
121 | final String[] projection = {
122 | column
123 | };
124 |
125 | try {
126 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
127 | if (cursor != null && cursor.moveToFirst()) {
128 | final int column_index = cursor.getColumnIndexOrThrow(column);
129 | return cursor.getString(column_index);
130 | }
131 | } catch (Exception e) {
132 | Log.d("android_utilities", "the error is " + e);
133 | } finally {
134 | if (cursor != null) {
135 | cursor.close();
136 | }
137 | }
138 | return null;
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/adapter/TweetAdapter.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.adapter;
2 |
3 | import android.content.Context;
4 | import android.support.v4.content.ContextCompat;
5 | import android.support.v7.widget.AppCompatImageButton;
6 | import android.support.v7.widget.AppCompatTextView;
7 | import android.support.v7.widget.RecyclerView;
8 | import android.view.LayoutInflater;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 | import android.widget.ImageView;
12 | import android.widget.LinearLayout;
13 |
14 | import com.atahani.retrofit_sample.R;
15 | import com.atahani.retrofit_sample.models.TweetModel;
16 | import com.atahani.retrofit_sample.utility.AppPreferenceTools;
17 | import com.atahani.retrofit_sample.utility.CropCircleTransformation;
18 | import com.squareup.picasso.Picasso;
19 |
20 | import java.util.Collections;
21 | import java.util.List;
22 |
23 | /**
24 | * Tweet Adapter show tweet in Recycler view
25 | */
26 | public class TweetAdapter extends RecyclerView.Adapter {
27 |
28 | private Context mContext;
29 | private LayoutInflater mLayoutInflater;
30 | private List mData = Collections.emptyList();
31 | private TweetEventHandler mTweetEventHandler;
32 | private AppPreferenceTools mAppPreferenceTools;
33 |
34 | public TweetAdapter(Context context, TweetEventHandler tweetEventHandler) {
35 | this.mContext = context;
36 | this.mLayoutInflater = LayoutInflater.from(context);
37 | this.mTweetEventHandler = tweetEventHandler;
38 | mAppPreferenceTools = new AppPreferenceTools(this.mContext);
39 | }
40 |
41 | public void updateAdapterData(List data) {
42 | this.mData = data;
43 | }
44 |
45 |
46 | @Override
47 | public TweetViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
48 | View view = mLayoutInflater.inflate(R.layout.tweet_row, parent, false);
49 | return new TweetViewHolder(view);
50 | }
51 |
52 | @Override
53 | public void onBindViewHolder(TweetViewHolder holder, int position) {
54 | TweetModel currentModel = mData.get(position);
55 | holder.mTxTweetBody.setText(currentModel.body);
56 | //convert char string into Hex code point
57 | int currentModeCodePoint = currentModel.feel.codePointAt(0);
58 | //produce the name of emoji drawable
59 | String drawable_name = "emoji_" + Integer.toHexString(currentModeCodePoint);
60 | //get the drawable resource id
61 | int icon = mContext.getResources().getIdentifier(drawable_name, "drawable", mContext.getPackageName());
62 | holder.mImMode.setImageDrawable(ContextCompat.getDrawable(mContext, icon));
63 | //check is user owner of this tweet can delete or edit
64 | if (currentModel.user.id.equals(mAppPreferenceTools.getUserId())) {
65 | holder.mLyAction.setVisibility(View.VISIBLE);
66 | holder.mTxUserDisplayName.setText(mAppPreferenceTools.getUserName());
67 | //load image via Picasso
68 | Picasso.with(this.mContext).load(mAppPreferenceTools.getImageProfileUrl())
69 | .transform(new CropCircleTransformation())
70 | .into(holder.mImUserImageProfile);
71 | } else {
72 | holder.mTxUserDisplayName.setText(currentModel.user.name);
73 | //load image via Picasso
74 | Picasso.with(this.mContext).load(currentModel.user.imageUrl)
75 | .transform(new CropCircleTransformation())
76 | .into(holder.mImUserImageProfile);
77 | holder.mLyAction.setVisibility(View.GONE);
78 | }
79 | }
80 |
81 |
82 | @Override
83 | public int getItemCount() {
84 | return mData.size();
85 | }
86 |
87 | /**
88 | * view holder for tweet adapter we have one view as tweet_row.xml layout
89 | */
90 | public class TweetViewHolder extends RecyclerView.ViewHolder {
91 |
92 | private LinearLayout mLyAction;
93 | private ImageView mImUserImageProfile;
94 | private AppCompatTextView mTxUserDisplayName;
95 | private AppCompatTextView mTxTweetBody;
96 | private AppCompatImageButton mImEdit;
97 | private AppCompatImageButton mImDelete;
98 | private ImageView mImMode;
99 |
100 | public TweetViewHolder(View itemView) {
101 | super(itemView);
102 | mLyAction = (LinearLayout) itemView.findViewById(R.id.ly_action);
103 | mImUserImageProfile = (ImageView) itemView.findViewById(R.id.im_image_profile);
104 | mTxUserDisplayName = (AppCompatTextView) itemView.findViewById(R.id.tx_user_display_name);
105 | mTxTweetBody = (AppCompatTextView) itemView.findViewById(R.id.tx_tweet_body);
106 | mImEdit = (AppCompatImageButton) itemView.findViewById(R.id.im_edit);
107 | mImDelete = (AppCompatImageButton) itemView.findViewById(R.id.im_delete);
108 | mImMode = (ImageView) itemView.findViewById(R.id.im_mode);
109 | mImDelete.setOnClickListener(new View.OnClickListener() {
110 | @Override
111 | public void onClick(View v) {
112 | if (mTweetEventHandler != null) {
113 | mTweetEventHandler.onDeleteTweet(mData.get(getAdapterPosition()).id, getAdapterPosition());
114 | }
115 | }
116 | });
117 |
118 | mImEdit.setOnClickListener(new View.OnClickListener() {
119 | @Override
120 | public void onClick(View v) {
121 | if (mTweetEventHandler != null) {
122 | mTweetEventHandler.onEditTweet(mData.get(getAdapterPosition()).id, getAdapterPosition());
123 | }
124 | }
125 | });
126 | }
127 | }
128 |
129 |
130 | /**
131 | * define interface to handle events
132 | */
133 | public interface TweetEventHandler {
134 | void onEditTweet(String tweetId, int position);
135 |
136 | void onDeleteTweet(String tweetId, int position);
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/ui/CreateOrEditTweet.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.ui;
2 |
3 | import android.support.v4.content.ContextCompat;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.support.v7.widget.AppCompatEditText;
7 | import android.support.v7.widget.Toolbar;
8 | import android.view.Menu;
9 | import android.view.MenuItem;
10 | import android.view.View;
11 | import android.widget.ImageButton;
12 | import android.widget.Toast;
13 |
14 | import com.atahani.retrofit_sample.R;
15 | import com.atahani.retrofit_sample.models.ErrorModel;
16 | import com.atahani.retrofit_sample.models.TweetModel;
17 | import com.atahani.retrofit_sample.network.FakeTwitterProvider;
18 | import com.atahani.retrofit_sample.network.FakeTwitterService;
19 | import com.atahani.retrofit_sample.utility.Constants;
20 | import com.atahani.retrofit_sample.utility.ErrorUtils;
21 |
22 | import retrofit2.Call;
23 | import retrofit2.Callback;
24 | import retrofit2.Response;
25 |
26 | public class CreateOrEditTweet extends AppCompatActivity {
27 |
28 | private String mSelectedMode = "";
29 | private AppCompatEditText mETxTweetBody;
30 | private ImageButton mImHappy;
31 | private ImageButton mImLoveMode;
32 | private ImageButton mImUnHappyMode;
33 | private int mActionToDo = Constants.NEW_TWEET;
34 | private String mTweetIdInEditMode;
35 | private FakeTwitterService mTService;
36 |
37 | @Override
38 | protected void onCreate(Bundle savedInstanceState) {
39 | super.onCreate(savedInstanceState);
40 | setContentView(R.layout.activity_create_or_edit_tweet);
41 | //get argument and check is in edit mode
42 | Bundle args = getIntent().getExtras();
43 | if (args != null) {
44 | mActionToDo = args.getInt(Constants.ACTION_TO_DO_KEY, Constants.NEW_TWEET);
45 | if (mActionToDo == Constants.EDIT_TWEET) {
46 | mTweetIdInEditMode = args.getString(Constants.TWEET_ID_KEY, "");
47 | }
48 | }
49 | Toolbar toolbar = (Toolbar) findViewById(R.id.default_toolbar);
50 | setSupportActionBar(toolbar);
51 | getSupportActionBar().setTitle("");
52 | getSupportActionBar().setDisplayHomeAsUpEnabled(true);
53 | mImHappy = (ImageButton) findViewById(R.id.im_happy_mode);
54 | mImLoveMode = (ImageButton) findViewById(R.id.im_love_mode);
55 | mImUnHappyMode = (ImageButton) findViewById(R.id.im_unhappy_mode);
56 | mETxTweetBody = (AppCompatEditText) findViewById(R.id.etx_tweet_body);
57 | //the default mode is happy so we selected
58 | mImHappy.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background_when_selected));
59 | mSelectedMode = getStringOfEmojiCode(getResources().getInteger(R.integer.mode_happy));
60 | mImHappy.setOnClickListener(new View.OnClickListener() {
61 | @Override
62 | public void onClick(View v) {
63 | selectTheFeel(getResources().getInteger(R.integer.mode_happy));
64 | }
65 | });
66 | mImLoveMode.setOnClickListener(new View.OnClickListener() {
67 | @Override
68 | public void onClick(View v) {
69 | selectTheFeel(getResources().getInteger(R.integer.mode_love));
70 | }
71 | });
72 | mImUnHappyMode.setOnClickListener(new View.OnClickListener() {
73 | @Override
74 | public void onClick(View v) {
75 | selectTheFeel(getResources().getInteger(R.integer.mode_unhappy));
76 | }
77 | });
78 | //first create new instant of FakeTwitterProvider
79 | FakeTwitterProvider provider = new FakeTwitterProvider();
80 | //get the FakeTwitterService interface to call API routes
81 | mTService = provider.getTService();
82 |
83 | //check if in edit mode get tweet information from server and assign in
84 | //NOTE: this is just for test , in real world should save tweet in db and now get from db !
85 | if (mActionToDo == Constants.EDIT_TWEET && !mTweetIdInEditMode.equals("")) {
86 | //get tweet by id from server
87 | Call call = mTService.getTweetById(mTweetIdInEditMode);
88 | call.enqueue(new Callback() {
89 | @Override
90 | public void onResponse(Call call, Response response) {
91 | if (response.isSuccess()) {
92 | //bind value to fields
93 | mETxTweetBody.setText(response.body().body);
94 | //get code point of emoji
95 | int currentModeCodePoint = response.body().feel.codePointAt(0);
96 | selectTheFeel(currentModeCodePoint);
97 |
98 | } else {
99 | ErrorModel errorModel = ErrorUtils.parseError(response);
100 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
101 | }
102 | }
103 |
104 | @Override
105 | public void onFailure(Call call, Throwable t) {
106 | //occur when fail to deserialize || no network connection || server unavailable
107 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
108 | }
109 | });
110 | }
111 | }
112 |
113 | @Override
114 | public boolean onCreateOptionsMenu(Menu menu) {
115 | if (mActionToDo == Constants.EDIT_TWEET) {
116 | getMenuInflater().inflate(R.menu.menu_edit, menu);
117 | } else {
118 | getMenuInflater().inflate(R.menu.menu_send, menu);
119 | }
120 | return super.onCreateOptionsMenu(menu);
121 | }
122 |
123 | @Override
124 | public boolean onOptionsItemSelected(MenuItem item) {
125 | int id = item.getItemId();
126 | if (id == R.id.action_send) {
127 | //Send tweet
128 | //create Tweet Model
129 | TweetModel tweetModel = new TweetModel();
130 | //assign tweet model values
131 | tweetModel.body = mETxTweetBody.getText().toString();
132 | tweetModel.feel = mSelectedMode;
133 |
134 | //create call generic class to send request to server
135 | Call call = mTService.createNewTweet(tweetModel);
136 | //Async request
137 | //NOTE: you should always send Async request since the sync request cause crash in your application
138 | call.enqueue(new Callback() {
139 | @Override
140 | public void onResponse(Call call, Response response) {
141 | if (response.isSuccess()) {
142 | Toast.makeText(getBaseContext(), "Successfully post new tweet", Toast.LENGTH_LONG).show();
143 | //finish this activity with result OK to refresh the data from server
144 | setResult(RESULT_OK);
145 | finish();
146 | } else {
147 | ErrorModel errorModel = ErrorUtils.parseError(response);
148 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
149 | }
150 | }
151 |
152 | @Override
153 | public void onFailure(Call call, Throwable t) {
154 | //occur when fail to deserialize || no network connection || server unavailable
155 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
156 | }
157 | });
158 |
159 | } else if (id == R.id.action_edit) {
160 | //edit this tweet
161 | TweetModel tweetModel = new TweetModel();
162 | //assign tweet model values
163 | tweetModel.body = mETxTweetBody.getText().toString();
164 | tweetModel.feel = mSelectedMode;
165 |
166 | Call call = mTService.updateTweetById(mTweetIdInEditMode, tweetModel);
167 | call.enqueue(new Callback() {
168 | @Override
169 | public void onResponse(Call call, Response response) {
170 | if (response.isSuccess()) {
171 | Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
172 | //finish this activity with result OK to refresh the data from server
173 | setResult(RESULT_OK);
174 | finish();
175 | } else {
176 | ErrorModel errorModel = ErrorUtils.parseError(response);
177 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
178 | }
179 | }
180 |
181 | @Override
182 | public void onFailure(Call call, Throwable t) {
183 | //occur when fail to deserialize || no network connection || server unavailable
184 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
185 | }
186 | });
187 |
188 | } else if (id == android.R.id.home) {
189 | //back to main activity
190 | onBackPressed();
191 | }
192 | return super.onOptionsItemSelected(item);
193 | }
194 |
195 | /**
196 | * get String from emoji hex unicode
197 | *
198 | * @param emojiCode
199 | * @return
200 | */
201 | private String getStringOfEmojiCode(int emojiCode) {
202 | StringBuilder sb = new StringBuilder();
203 | sb.append(Character.toChars(emojiCode));
204 | return sb.toString();
205 | }
206 |
207 | private void selectTheFeel(int emojiCodePoint) {
208 | if (emojiCodePoint == getResources().getInteger(R.integer.mode_happy)) {
209 | mImHappy.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background_when_selected));
210 | mImLoveMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
211 | mImUnHappyMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
212 | mSelectedMode = getStringOfEmojiCode(getResources().getInteger(R.integer.mode_happy));
213 | } else if (emojiCodePoint == getResources().getInteger(R.integer.mode_love)) {
214 | mImLoveMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background_when_selected));
215 | mImHappy.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
216 | mImUnHappyMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
217 | mSelectedMode = getStringOfEmojiCode(getResources().getInteger(R.integer.mode_love));
218 |
219 | } else if (emojiCodePoint == getResources().getInteger(R.integer.mode_unhappy)) {
220 | mImUnHappyMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background_when_selected));
221 | mImHappy.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
222 | mImLoveMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
223 | mSelectedMode = getStringOfEmojiCode(getResources().getInteger(R.integer.mode_unhappy));
224 | }
225 | }
226 | }
227 |
--------------------------------------------------------------------------------
/app/src/main/java/com/atahani/retrofit_sample/ui/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.atahani.retrofit_sample.ui;
2 |
3 | import android.Manifest;
4 | import android.app.ProgressDialog;
5 | import android.content.Intent;
6 | import android.content.pm.PackageManager;
7 | import android.net.Uri;
8 | import android.support.annotation.NonNull;
9 | import android.support.v4.app.ActivityCompat;
10 | import android.support.v4.content.ContextCompat;
11 | import android.support.v7.app.AppCompatActivity;
12 | import android.os.Bundle;
13 | import android.support.v7.widget.AppCompatTextView;
14 | import android.support.v7.widget.LinearLayoutManager;
15 | import android.support.v7.widget.RecyclerView;
16 | import android.support.v7.widget.Toolbar;
17 | import android.util.Log;
18 | import android.view.Menu;
19 | import android.view.MenuItem;
20 | import android.view.View;
21 | import android.widget.ImageButton;
22 | import android.widget.ImageView;
23 | import android.widget.Toast;
24 |
25 | import com.atahani.retrofit_sample.R;
26 | import com.atahani.retrofit_sample.TApplication;
27 | import com.atahani.retrofit_sample.adapter.OperationResultModel;
28 | import com.atahani.retrofit_sample.adapter.TweetAdapter;
29 | import com.atahani.retrofit_sample.models.ErrorModel;
30 | import com.atahani.retrofit_sample.models.TweetModel;
31 | import com.atahani.retrofit_sample.models.UserModel;
32 | import com.atahani.retrofit_sample.network.FakeTwitterProvider;
33 | import com.atahani.retrofit_sample.network.FakeTwitterService;
34 | import com.atahani.retrofit_sample.utility.AndroidUtilities;
35 | import com.atahani.retrofit_sample.utility.AppPreferenceTools;
36 | import com.atahani.retrofit_sample.utility.Constants;
37 | import com.atahani.retrofit_sample.utility.CropCircleTransformation;
38 | import com.atahani.retrofit_sample.utility.ErrorUtils;
39 | import com.squareup.picasso.Picasso;
40 |
41 | import java.io.File;
42 | import java.io.FileOutputStream;
43 | import java.io.InputStream;
44 | import java.io.OutputStream;
45 | import java.util.Arrays;
46 | import java.util.HashMap;
47 | import java.util.List;
48 | import java.util.Map;
49 |
50 | import okhttp3.MediaType;
51 | import okhttp3.RequestBody;
52 | import retrofit2.Call;
53 | import retrofit2.Callback;
54 | import retrofit2.Response;
55 |
56 | public class MainActivity extends AppCompatActivity {
57 |
58 | private TweetAdapter mAdapter;
59 | private FakeTwitterService mTService;
60 | private RecyclerView mRyTweets;
61 | private AppCompatTextView mTxDisplayName;
62 | private ImageView mImImageProfile;
63 | private AppPreferenceTools mAppPreferenceTools;
64 | private ProgressDialog mProgressDialog;
65 | private PermissionEventListener mPermissionEventListener;
66 |
67 | private ImageButton mImHappy;
68 | private ImageButton mImLoveMode;
69 | private ImageButton mImUnHappyMode;
70 | private int mCurrentCodePointMode = 0;
71 |
72 | @Override
73 | protected void onCreate(Bundle savedInstanceState) {
74 | super.onCreate(savedInstanceState);
75 | setContentView(R.layout.activity_main);
76 | mProgressDialog = new ProgressDialog(this);
77 | mProgressDialog.setCancelable(false);
78 | mProgressDialog.setCanceledOnTouchOutside(false);
79 | //check is user logged it or not
80 | mAppPreferenceTools = new AppPreferenceTools(this);
81 | if (mAppPreferenceTools.isAuthorized()) {
82 | Toolbar toolbar = (Toolbar) findViewById(R.id.default_toolbar);
83 | setSupportActionBar(toolbar);
84 | getSupportActionBar().setTitle("");
85 | //bind user image and name to toolbar
86 | mTxDisplayName = (AppCompatTextView) toolbar.findViewById(R.id.tx_display_name);
87 | mImImageProfile = (ImageView) toolbar.findViewById(R.id.im_image_profile);
88 | mTxDisplayName.setText(mAppPreferenceTools.getUserName());
89 | //load user image with Picasso
90 | Picasso.with(this).load(mAppPreferenceTools.getImageProfileUrl())
91 | .transform(new CropCircleTransformation()).into(mImImageProfile);
92 | //get the provider
93 | FakeTwitterProvider provider = new FakeTwitterProvider();
94 | mTService = provider.getTService();
95 | //config recycler view
96 | mRyTweets = (RecyclerView) findViewById(R.id.ry_tweets);
97 | mRyTweets.setLayoutManager(new LinearLayoutManager(this));
98 | mAdapter = new TweetAdapter(this, new TweetAdapter.TweetEventHandler() {
99 | @Override
100 | public void onEditTweet(String tweetId, int position) {
101 | //start activity to edit tweet
102 | Intent editTweetIntent = new Intent(getBaseContext(), CreateOrEditTweet.class);
103 | editTweetIntent.putExtra(Constants.ACTION_TO_DO_KEY, Constants.EDIT_TWEET);
104 | editTweetIntent.putExtra(Constants.TWEET_ID_KEY, tweetId);
105 | startActivityForResult(editTweetIntent, Constants.CREATE_OR_EDIT_TWEET_REQUEST_CODE);
106 | }
107 |
108 | @Override
109 | public void onDeleteTweet(String tweetId, final int position) {
110 | Call call = mTService.deleteTweetById(tweetId);
111 | //async request
112 | call.enqueue(new Callback() {
113 | @Override
114 | public void onResponse(Call call, Response response) {
115 | if (response.isSuccess()) {
116 | //get tweets from server just for test
117 | getTweetsFromServer();
118 | } else {
119 | ErrorModel errorModel = ErrorUtils.parseError(response);
120 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
121 | }
122 | }
123 |
124 | @Override
125 | public void onFailure(Call call, Throwable t) {
126 | //occur when fail to deserialize || no network connection || server unavailable
127 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
128 | }
129 | });
130 | }
131 | });
132 | mRyTweets.setAdapter(mAdapter);
133 | //get tweets in load
134 | getTweetsFromServer();
135 |
136 | //these lines for modes
137 | mImHappy = (ImageButton) findViewById(R.id.im_happy_mode);
138 | mImLoveMode = (ImageButton) findViewById(R.id.im_love_mode);
139 | mImUnHappyMode = (ImageButton) findViewById(R.id.im_unhappy_mode);
140 | mImHappy.setOnClickListener(new View.OnClickListener() {
141 | @Override
142 | public void onClick(View v) {
143 | onClickOnModeBtn(getResources().getInteger(R.integer.mode_happy));
144 | }
145 | });
146 | mImLoveMode.setOnClickListener(new View.OnClickListener() {
147 | @Override
148 | public void onClick(View v) {
149 | onClickOnModeBtn(getResources().getInteger(R.integer.mode_love));
150 | }
151 | });
152 | mImUnHappyMode.setOnClickListener(new View.OnClickListener() {
153 | @Override
154 | public void onClick(View v) {
155 | onClickOnModeBtn(getResources().getInteger(R.integer.mode_unhappy));
156 | }
157 | });
158 | } else {
159 | //the user is not logged in so should navigate to sing in activity
160 | startActivity(new Intent(this, SignInActivity.class));
161 | finish();
162 | }
163 | }
164 |
165 | private void onClickOnModeBtn(int modeCodePoint) {
166 | if (mCurrentCodePointMode != modeCodePoint) {
167 | selectTheFeel(modeCodePoint);
168 | getTweetsByMode(modeCodePoint);
169 | } else {
170 | //de select all of mode and get tweet without any query
171 | deSelectAllOfMode();
172 | getTweetsFromServer();
173 | }
174 | }
175 |
176 | /**
177 | * get tweets from server
178 | */
179 | private void getTweetsFromServer() {
180 | Call> call = mTService.getTweets();
181 | call.enqueue(new Callback>() {
182 | @Override
183 | public void onResponse(Call> call, Response> response) {
184 |
185 | if (response.isSuccess()) {
186 | //update the adapter data
187 | mAdapter.updateAdapterData(response.body());
188 | mAdapter.notifyDataSetChanged();
189 | } else {
190 | ErrorModel errorModel = ErrorUtils.parseError(response);
191 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
192 | }
193 | }
194 |
195 | @Override
196 | public void onFailure(Call> call, Throwable t) {
197 | //occur when fail to deserialize || no network connection || server unavailable
198 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
199 | }
200 | });
201 | }
202 |
203 | private void getTweetsByMode(int modeCodePoint) {
204 | //make call
205 | Call> call = mTService.getTweetsByFeel(getStringOfEmojiCode(modeCodePoint));
206 | call.enqueue(new Callback>() {
207 | @Override
208 | public void onResponse(Call> call, Response> response) {
209 | if (response.isSuccess()) {
210 | //update the adapter data
211 | mAdapter.updateAdapterData(response.body());
212 | mAdapter.notifyDataSetChanged();
213 | } else {
214 | ErrorModel errorModel = ErrorUtils.parseError(response);
215 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
216 | }
217 | }
218 |
219 | @Override
220 | public void onFailure(Call> call, Throwable t) {
221 | //occur when fail to deserialize || no network connection || server unavailable
222 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
223 | }
224 | });
225 | }
226 |
227 | @Override
228 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
229 |
230 | if (requestCode == Constants.CREATE_OR_EDIT_TWEET_REQUEST_CODE && resultCode == RESULT_OK) {
231 | getTweetsFromServer();
232 | } else if (requestCode == Constants.UPDATE_USER_PROFILE_REQUEST_CODE && resultCode == RESULT_OK) {
233 | //update the value of name in toolbar and re create the tweets Adapter
234 | mTxDisplayName.setText(mAppPreferenceTools.getUserName());
235 | mAdapter.notifyDataSetChanged();
236 | } else if (requestCode == Constants.GALLERY_REQUEST_CODE && resultCode == RESULT_OK) {
237 | try {
238 | Uri selectedImageUri = data.getData();
239 | String extractUriFrom = selectedImageUri.toString();
240 | //check is from google photos or google drive
241 | if (extractUriFrom.contains("com.google.android.apps.photos.contentprovider") || extractUriFrom.contains("com.google.android.apps.docs.storage")) {
242 | final int chunkSize = 1024; // We'll read in one kB at a time
243 | byte[] imageData = new byte[chunkSize];
244 | File imageFile = AndroidUtilities.generateImagePath();
245 | InputStream in = null;
246 | OutputStream out = null;
247 | mProgressDialog.setMessage("Loading ...");
248 | mProgressDialog.show();
249 | try {
250 | in = getContentResolver().openInputStream(selectedImageUri);
251 | out = new FileOutputStream(imageFile);
252 | int bytesRead;
253 | while ((bytesRead = in.read(imageData)) > 0) {
254 | out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
255 | }
256 | uploadImageProfile(imageFile.getAbsolutePath());
257 | if (mProgressDialog.isShowing()) {
258 | mProgressDialog.dismiss();
259 | }
260 | // navigateToPhotoCropActivity();
261 | } catch (Exception ex) {
262 | if (mProgressDialog.isShowing()) {
263 | mProgressDialog.dismiss();
264 | }
265 | Toast.makeText(getBaseContext(), "can not get this image :|", Toast.LENGTH_SHORT).show();
266 | Log.e("Something went wrong.", ex.toString());
267 | } finally {
268 | if (in != null) {
269 | in.close();
270 | }
271 | if (out != null) {
272 | out.close();
273 | }
274 | if (mProgressDialog.isShowing()) {
275 | mProgressDialog.dismiss();
276 | }
277 | }
278 | } else {
279 | uploadImageProfile(AndroidUtilities.getPath(selectedImageUri));
280 | }
281 | } catch (Exception ex) {
282 | Toast.makeText(getBaseContext(), "something wrong :|", Toast.LENGTH_SHORT).show();
283 | }
284 | }
285 | super.onActivityResult(requestCode, resultCode, data);
286 | }
287 |
288 | /**
289 | * upload image profile and is success load it into ImageView
290 | *
291 | * @param imagePath
292 | */
293 | private void uploadImageProfile(String imagePath) {
294 | File imageFile = new File(imagePath);
295 | if (imageFile.exists()) {
296 | //create request body
297 | Map map = new HashMap<>();
298 | RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imageFile);
299 | map.put("photo\"; filename=\"" + imageFile.getName() + "\"", requestBody);
300 | //make call
301 | Call call = mTService.uploadUserProfileImage("bearer " + mAppPreferenceTools.getAccessToken(), map);
302 | call.enqueue(new Callback() {
303 | @Override
304 | public void onResponse(Call call, Response response) {
305 | if (response.isSuccess()) {
306 | //save the user model to pref
307 | mAppPreferenceTools.saveUserModel(response.body());
308 | //load new image
309 | Picasso.with(getBaseContext()).load(mAppPreferenceTools.getImageProfileUrl())
310 | .transform(new CropCircleTransformation())
311 | .into(mImImageProfile);
312 | //reload the adapter since the user image profile changed
313 | mAdapter.notifyDataSetChanged();
314 | } else {
315 | ErrorModel errorModel = ErrorUtils.parseError(response);
316 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
317 | }
318 | }
319 |
320 | @Override
321 | public void onFailure(Call call, Throwable t) {
322 | //occur when fail to deserialize || no network connection || server unavailable
323 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
324 | }
325 | });
326 | } else {
327 | Toast.makeText(getBaseContext(), "can not upload file since the file is not exist :|", Toast.LENGTH_SHORT).show();
328 | }
329 | }
330 |
331 | @Override
332 | public boolean onCreateOptionsMenu(Menu menu) {
333 | getMenuInflater().inflate(R.menu.menu_default, menu);
334 | return super.onCreateOptionsMenu(menu);
335 | }
336 |
337 | @Override
338 | public boolean onOptionsItemSelected(MenuItem item) {
339 | int id = item.getItemId();
340 | if (id == R.id.action_tweet) {
341 | //start new activity to send tweet
342 | Intent postNewTweetIntent = new Intent(this, CreateOrEditTweet.class);
343 | postNewTweetIntent.putExtra(Constants.ACTION_TO_DO_KEY, Constants.NEW_TWEET);
344 | startActivityForResult(postNewTweetIntent, Constants.CREATE_OR_EDIT_TWEET_REQUEST_CODE);
345 | } else if (id == R.id.action_log_out) {
346 | //send request to server to terminate this application
347 | Call call = mTService.terminateApp();
348 | call.enqueue(new Callback() {
349 | @Override
350 | public void onResponse(Call call, Response response) {
351 | if (response.isSuccess()) {
352 | //remove all authentication information such as accessToken and others
353 | mAppPreferenceTools.removeAllPrefs();
354 | //navigate to sign in activity
355 | startActivity(new Intent(getBaseContext(), SignInActivity.class));
356 | //finish this
357 | finish();
358 | }
359 | }
360 |
361 | @Override
362 | public void onFailure(Call call, Throwable t) {
363 | //occur when fail to deserialize || no network connection || server unavailable
364 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
365 | }
366 | });
367 | } else if (id == R.id.action_update_profile) {
368 | //navigate to update user profile activity
369 | startActivityForResult(new Intent(getBaseContext(), EditUserProfile.class), Constants.UPDATE_USER_PROFILE_REQUEST_CODE);
370 | } else if (id == R.id.action_upload_image) {
371 | //open gallery to select single picture as image profile
372 | //before that check runtime permission
373 | if (checkRunTimePermissionIsGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
374 | startGalleryIntent();
375 | } else {
376 | //request write external permission for open camera intent
377 | requestRunTimePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Constants.FOR_OPEN_GALLERY_REQUEST_WRITE_EXTERNAL_STORAGE_PER, new PermissionEventListener() {
378 | @Override
379 | public void onGranted(int requestCode, String[] permissions) {
380 | startGalleryIntent();
381 | }
382 |
383 | @Override
384 | public void onFailure(int requestCode, String[] permissions) {
385 | Toast.makeText(getBaseContext(), "Can not pick photo without this permission", Toast.LENGTH_SHORT).show();
386 | }
387 | });
388 | }
389 | } else if (id == R.id.action_expire_access_tokens) {
390 | //send request to remove all access tokens
391 | //make call
392 | Call call = mTService.removeAllAccessToken();
393 | call.enqueue(new Callback() {
394 | @Override
395 | public void onResponse(Call call, Response response) {
396 | //
397 | if (response.isSuccess()) {
398 | Toast.makeText(getBaseContext(), "all access token removed", Toast.LENGTH_SHORT).show();
399 | } else {
400 | ErrorModel errorModel = ErrorUtils.parseError(response);
401 | Toast.makeText(getBaseContext(), "Error type is " + errorModel.type + " , description " + errorModel.description, Toast.LENGTH_SHORT).show();
402 | }
403 | }
404 |
405 | @Override
406 | public void onFailure(Call call, Throwable t) {
407 | //occur when fail to deserialize || no network connection || server unavailable
408 | Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
409 | }
410 | });
411 |
412 | }
413 | return super.onOptionsItemSelected(item);
414 | }
415 |
416 | /**
417 | * start gallery intent to pick photo
418 | */
419 | private void startGalleryIntent() {
420 | Intent intent = new Intent();
421 | intent.setType("image/*");
422 | intent.setAction(Intent.ACTION_GET_CONTENT);
423 | startActivityForResult(Intent.createChooser(intent, "Select Picture"), Constants.GALLERY_REQUEST_CODE);
424 | }
425 |
426 | private void requestRunTimePermission(String permissionType, int requestCode, PermissionEventListener permissionEventListener) {
427 | ActivityCompat.requestPermissions(this, new String[]{permissionType}, requestCode);
428 | mPermissionEventListener = permissionEventListener;
429 | }
430 |
431 | private boolean checkRunTimePermissionIsGranted(String permissionType) {
432 | return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(TApplication.applicationContext, permissionType);
433 | }
434 |
435 | @Override
436 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
437 | if (mPermissionEventListener != null) {
438 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
439 | mPermissionEventListener.onGranted(requestCode, permissions);
440 | } else {
441 | mPermissionEventListener.onFailure(requestCode, permissions);
442 | }
443 | }
444 |
445 | }
446 |
447 | private String getStringOfEmojiCode(int emojiCode) {
448 | StringBuilder sb = new StringBuilder();
449 | sb.append(Character.toChars(emojiCode));
450 | return sb.toString();
451 | }
452 |
453 | private void selectTheFeel(int emojiCodePoint) {
454 | mCurrentCodePointMode = emojiCodePoint;
455 | if (emojiCodePoint == getResources().getInteger(R.integer.mode_happy)) {
456 | mImHappy.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background_when_selected));
457 | mImLoveMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
458 | mImUnHappyMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
459 | } else if (emojiCodePoint == getResources().getInteger(R.integer.mode_love)) {
460 | mImLoveMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background_when_selected));
461 | mImHappy.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
462 | mImUnHappyMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
463 | } else if (emojiCodePoint == getResources().getInteger(R.integer.mode_unhappy)) {
464 | mImUnHappyMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background_when_selected));
465 | mImHappy.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
466 | mImLoveMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
467 | }
468 | }
469 |
470 | private void deSelectAllOfMode() {
471 | mCurrentCodePointMode = 0;
472 | mImHappy.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
473 | mImLoveMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
474 | mImUnHappyMode.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.mode_background));
475 | }
476 |
477 |
478 | public interface PermissionEventListener {
479 | void onGranted(int requestCode, String[] permissions);
480 |
481 | void onFailure(int requestCode, String[] permissions);
482 | }
483 | }
484 |
--------------------------------------------------------------------------------