Android Retrofit Post Data - android

I am working with an Android Recyclerview with Retrofit, it is working without any Post Data. I need to post some data in my current Code.
Below is my Current ApiInterface
public interface ApiInterface {
#GET("mypage.php")
Call<Pojo> getData();
}
And in my activity I am calling this by below code
ApiInterface apiInterface = (ApiInterface) RetrofitClient.getRetrofitInstance().create(ApiInterface.class);
Call<Pojo> listingdata = apiInterface.getData();
listingdata.enqueue(new Callback<Pojo>() {
#Override
public void onResponse(Call<Pojo> call, Response<Pojo> response) {
if(response.isSuccessful()){
recycleradpter recycleradpter = new recycleradpter(response.body().getData());
recyclerView.setAdapter(recycleradpter);
progressbar2.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<Pojo> call, Throwable t) {
//System.out.println("12345678934567890234567890");
//Toast.makeText(getActivity(), "No Connected internet", Toast.LENGTH_SHORT).show();
progressbar2.setVisibility(View.GONE);
dialogfunction();
}
});
How Can I get data based on passed data in above code

If you want to send a post request then you have to create a method like below. The calling of the method will be similar to that of get request. Just pass the parameters of your post body. You can for details here.
#POST("mypage.php")
Call<Pojo> postData(
#Field("param1") String param1,
#Field("param2") int param2
);

#FormUrlEncoded
#POST("your_php_file.php")
Call<ResponseBody> getLanguageCall(#Field("lang_code") String lang_code, #Field("app_id") String app_id);
private void getLanguageCall() {
progressDialog.setVisibility(VISIBLE);
Call<ResponseBody> call = ApiClient.getClient().create(ApiInterface.class).getLanguageCall(PreferenceManager.getStringPreference(SplashActivity.this, appLanguage), PreferenceManager.getStringPreference(SplashActivity.this, PreferenceManager.APP_ID));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
progressDialog.setVisibility(View.GONE);
if (!response.isSuccessful()) {
showToast(response.code() + " : " + response.message());
return;
}
try {
JSONObject root = new JSONObject(response.body().string());
HashMap<String, String> list = new HashMap<String, String>();
JSONArray keyData = root.getJSONArray("key_data");
for (int i = 0; i < keyData.length(); i++) {
JSONObject obj = keyData.getJSONObject(i);
list.put(obj.getString("Key_Name").toLowerCase(), obj.getString("Key_Value"));
}
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
progressDialog.setVisibility(View.GONE);
showToast("Error ! Server Error.");
}
});
}

Related

Post an array using retrofit 2

I need to post an array of attendees as shown in the image above. I tried using Hashmap but it gives some errors and I don't know if it is server-side error or retrofit.
Here is my code :
API interface
#FormUrlEncoded
#POST("vendor/event/{id}/checkin")
Call<DefaultResponse> updateAttendance(
#Path("id") int id,
#QueryMap Map<String,String> attendees,
#Field("token") String token);
Response class
String message;
public DefaultResponse(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
And here is the code of my Activity
final Map<String,String> attendees = new HashMap<>();
for (int i = 0; i < attendeesTables.size(); i++){
attendees.put("id", String.valueOf(attendeesTables.get(i).getId()));
attendees.put("arrival_time",
attendeesTables.get(i).getArrival_time());
}
if (attendeesTables.size() > 0) {
Call<DefaultResponse> call = RetrofitClient.getmInstance().getApi().updateAttendance(event_id,attendees,token);
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
Toast.makeText(EventsDetailsActivity.this, response.code()+"", Toast.LENGTH_SHORT).show();
Toast.makeText(EventsDetailsActivity.this, response.isSuccessful()+"", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
Toast.makeText(EventsDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Am I doing everything in the right way?
I get request code 400(bad request)
You params are not correct that's why you getting 400 error. try like below
Request :
#FormUrlEncoded
#POST("vendor/event/{id}/checkin")
Call<DefaultResponse> updateAttendance(
#Path("id") int id,
#Field("attendees") String attendees,
#Field("token") String token);
Api Call :
JSONArray attendeesArray=new JSONArray();
for (int i = 0; i < attendeesTables.size(); i++){
JSONObject jsonObject=new JSONObject();
jsonObject.put("id",String.valueOf(attendeesTables.get(i).getId()));
jsonObject.put("arrival_time",String.valueOf(attendeesTables.get(i).getArrival_time()));
attendeesArray.put(jsonObject);
}
if (attendeesTables.size() > 0) {
Call<DefaultResponse> call = RetrofitClient.getmInstance().getApi().updateAttendance(event_id,attendeesArray.toString(),token);
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
Toast.makeText(EventsDetailsActivity.this, response.code()+"", Toast.LENGTH_SHORT).show();
Toast.makeText(EventsDetailsActivity.this, response.isSuccessful()+"", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
Toast.makeText(EventsDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

retrofit2 get json object without jsonArray name

I want to take jsonobject using retrofit without class definition, the result is null. How about this ?
I have a get query with JSON response :
[{"Kuota":"12"}]
This my code get data JSONObject .
public void GetKuota(String Key) {
IBookingService iBookingService = APIClient.getClient().create(IBookingService.class);
Call<ResponseBody> call = iBookingService.getKuota(Key);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(!response.isSuccessful()) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(response.body().toString());
// Log.d(jsonObject.getString("Kuota"));
datas =String.valueOf(jsonObject.getInt("Kuota"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
Suggestion:
Create a model class, lets say Kuota
public class Kuota {
public int Kuota;
}
Then rewrite the Retrofit callback like this.
iBookingService.getKuota(Key).enqueue(new Callback<List<Kuota>>() {
#Override
public void onResponse(Call<List<Kuota>> call, Response<List<Kuota>> response) {
if(response.code() == 200 && response.body() != null) {
try {
for(Kuota k: response.body()) {
Log.d("Kuota Value" , " " + k.kuota);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<List<Kuota>> call, Throwable t) {
}
});
Replace iBookingService data holder from ResponseBody to List< Kuota >
if not added, please add the JSON serializer while setting up Retrofit instance.
new Retrofit.Builder()
.......
.addConverterFactory(GsonConverterFactory.create())
.build();
And also add the dependency
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Retrofit response showing

I tried to post raw data to server using retrofit method, but I receive the failure response like resĀ fail: Response{protocol=http/1.1, code=500, message=Internal Server Error, url=http://192.168.1.9:8000/api/deviceinfo}
apiService = RetrofitSingleton.createService(ApiService.class);
spyApp = new SpyApp();
Call<ModelResponse> call = apiService.eventsUpdate(jsonObj);
call.enqueue(new Callback<ModelResponse>() {
#Override
public void onResponse(Call<ModelResponse> call, Response<ModelResponse> response) {
Log.e("response", new Gson().toJson(response.body())); //This shows null
if (response.isSuccessful()) {
String status = response.body().getData().getStatus();
} else {
Log.e("res fail", response.toString());
}
}
#Override
public void onFailure(Call<ModelResponse> call, Throwable t) {
Log.e("failure",t.getMessage());
}
});

How to loadmore logic in recyclerview android

i already make user interface listview and progressbar in footerview reclerview and now i'm really stuck how to load more my data JSON?
this class get data json for first page :
private void firstPage() {
final ProgressDialog progressDialog = new ProgressDialog(Feed_Activity.this);
progressDialog.setTitle("Mengambil data");
progressDialog.show();
Log.d(Status.TAG, "dam login fungsi goOAuth");
Call<ResponseBody> token_request;
Retrofit retrofit;
retrofit = new Retrofit.Builder()
.baseUrl(Status.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
token_request = apiService.feed();
token_request.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(Status.TAG, "dam error code = " + response.code());
if (response.code() == 200) {
try {
JSONObject responseObject = new JSONObject(response.body().string());
JSONArray arrayDocs =responseObject.getJSONArray("docs");
for (int i = 0; i < arrayDocs.length(); i++) {
//parsing json proccess
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
progressDialog.dismiss();
}
});
}
and now what must i do in nextPage() function for load more?
private void nextPage() {
//what must i do in here for load more my json data
}
and my api using endpoint like this
https://penawaran.8villages.com/activities/filter?challengeId=*********&limit=10&offset=0
page 1: limit=10&offset=0
page 2: limit=10&offset=10
page 3: limit=10&offset=20
please someone help me, im really stuck with my job :(
ArrayList<JSONObject> jsonArrayList=new ArrayList<>();
boolean isLoadMore;
int offset=0;
#Override
public void onBindViewHolder(ContactsAdapter.ViewHolder viewHolder, int position) {
if(isLoadMore && position==jsonArrayList.size()-1)
{
offset+=10;
isLoadMore =false;
nextPage();//your logic here to hit web service
}
}
////////////////////////////
private void firstPage() {
final ProgressDialog progressDialog = new ProgressDialog(Feed_Activity.this);
progressDialog.setTitle("Mengambil data");
progressDialog.show();
Log.d(Status.TAG, "dam login fungsi goOAuth");
Call<ResponseBody> token_request;
Retrofit retrofit;
retrofit = new Retrofit.Builder()
.baseUrl(Status.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
token_request = apiService.feed();
token_request.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(Status.TAG, "dam error code = " + response.code());
if (response.code() == 200) {
try {
JSONObject responseObject = new JSONObject(response.body().string());
JSONArray arrayDocs =responseObject.getJSONArray("docs");
/*here if lenght of arrayDocs will be more then or equal to limit i.e. 10 in your case then isLoadMore will be true*/
isLoadMore=arrayDocs.length()>=10;//same condition you should be check in nextpage() method each time
for (int i = 0; i < arrayDocs.length(); i++) {
//parsing json proccess
/*add jsonObject into your jsonArrayList and notify your adapter with the same list*/
jsonArrayList.add(arrayDocs.get(i));
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
progressDialog.dismiss();
}
});
}

enqueue multiple GET request when using nested retrofit 2.0

I am using Retrofit 2.0 to make api calls with nesting multiple requests. All api's works fine individually.
But when i nested all retrofit, First request execute perfectly but after that when i register second request it's not callback in enqueue method (i.e. it's directly returning null without inserting enqueue's inner methods like onResponse, onFailure)
My Code :-
public class Main2Activity extends AppCompatActivity {
Gson gson;
JSONObject jsonResult=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gson=new GsonBuilder().create();
firstRequest(); //-- First retrofit request
}
private void firstRequest() {
Retrofit retrofit=new Retrofit.Builder().baseUrl(getResources().getString(R.string.Api_Url)).addConverterFactory(GsonConverterFactory.create(gson)).build();
CityRetailsApi service = retrofit.create(CityRetailsApi.class);
Call call_first= service.getMainCatFlag();
call_first.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", "Status Code = " + response.code());
if (response.isSuccessful()){
MainCatFlag result = (MainCatFlag) response.body(); //-- Get First request response
JSONObject json2nd = secondRequest(); //-- Second request
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "Error");
}
});
}
private JSONObject secondRequest() {
try {
Retrofit retrofit=new Retrofit.Builder().baseUrl(getResources().getString(R.string.Api_Url)).addConverterFactory(GsonConverterFactory.create(gson)).build();
CityRetailsApi service = retrofit.create(CityRetailsApi.class);
Call call_second= service.getMainCat();
call_second.enqueue(new Callback() {
#Override
public void onResponse(Call call2, Response response1) {
Log.d("MainActivity", "Status Code = " + response1.code());
if (response1.isSuccessful()) {
MainCat result = (MainCat) response1.body();
if (result.getSuccess()==1)
{
try {
jsonResult= new JSONObject(new Gson().toJson(result));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "Error");
}
});
}catch (Exception e){
Log.d("MainActivity", "Error= " + e);
}
return jsonResult;
}
}
In above code firstRequest() executed correctly and proving response but the secondRequest (inside firstRequest() enqueue method) not working fine. Not showing any error, success message in console. Can any one please help me to override this problem.
If any problem in my code, please let me know.
Thank you in advance.
You made a mistake that when you using retrofit enquene,it's called asynchronously, so you can't get the result outside of the callback method!
So, you should process your result inside the onResponse method like this:
private void secondRequest() {
try {
call_second.enqueue(new Callback() {
#Override
public void onResponse(Call call2, Response response1) {
Log.d("MainActivity", "Status Code = " + response1.code());
if (response1.isSuccessful()) {
MainCat result = (MainCat) response1.body();
if (result.getSuccess()==1)
{
try {
jsonResult= new JSONObject(new Gson().toJson(result));
// process your jsonResult here
...
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "Error");
}
});
}catch (Exception e){
Log.d("MainActivity", "Error= " + e);
}
}

Categories

Resources