How the steps? What should be prepared? Let's start!
Compile the several libraries below in your build.gradle (apps):
compile 'com.google.code.gson:gson:2.6.2' compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2'
In your AndroidManifest.xml, add uses permission look like the following:
Create the several layouts :
- activity_main.xml > Display the main page
- item_answer.xml > Display the aswers of FAQ
- item_question.xml > Display the questions of FAQ
- MainActivity.java > All the login process and passing value will done here
- ApiClient.java > Create the Retrofit's client and interceptors
- Inteface ApiService.java > Initialized of retrofit's POST method
- LoggingInterceptors.java > To help you see the output of the process in Logcat
- FaqModel.java > To store the response of Questions and answers
- ListFaqModel.java > To store list of FAQ
- ExpandAdapter.java > To set questions and answers on exapandable
Why we need LoggingInterceptors.java? Because in retrofit we'll difficult to detect the output of the process. If we find an error, it will be hard to debug. So we need this class :
You have to know how the form of the JSON of your target. It used to make us easy to create its model.
Your URL Target :
http://private-fc41f-myprofile2.apiary-mock.com/loginsaya
With required field username dan password
The JSON of the response after you success do login :
Now time to create time the code of the Layouts.
Create new xml file and give it name as activity_main.xml. Paste the following code :
Create new xml file and give it name as item_answer.xml. Paste the following code:
Create new xml file and give it name as item_questions.xml. Paste the following code :
Next, Create all the java classes.
Create new java file and give it name as ApiClient.java. Paste the following code :
Create new java file and give it name as ApiService.java. Paste the following code :
Create new java file and give it name as LoggingInterceptor.java. Paste the following code :
Create new java class that will store the object of FAQ, give it name as FaqModel.java. Paste the following code :
Because the form of the API required List to cover FaqModel.java, so we must create a new class called ListFaqModel.java. Paste the following code :
After that, create new adapter class. This class will set the the data to the model. Give it name as ExpandAdapter.java. Paste the following code :
Next is MainActivity.java, paste the following code :
If has done, run your project. Hope it will works well. I have tried before i post here and it running well.
*****
because we use LoggingInterceptors.java, so we can see the process on your Android Studio's logcat. :
You can clone the real project here GITHUB
OK, That's all about how to do POST using retrofit 2.0. Hope it helps.
EmoticonEmoticon