how to fetch response from retrofit JSON without key - android

In my retrofit JSON response there is a single value without any key and type.In my JSON i have passed three-element as per need and now i get a response as shown below. so how can I fetch that response?
My JSON of Response looks like -
successful
This is my JSON code-
private void ASSIGN_DATA() {
ApiInterface apiInterface=ApiClient.getClient().create(ApiInterface.class);
Call<ArrayList<price_get_set>> call=apiInterface.assignItemToJson(select_date.getText().toString(),
id,item_list);
call.enqueue(new Callback<ArrayList<price_get_set>>() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onResponse(Call<ArrayList<price_get_set>> call, Response<ArrayList<price_get_set>> response) {
progress.dismiss();
Log.d("URL::",response.toString());
Log.d("new URL::",response.body().toString());
try {
if (response.isSuccessful()) {
Toast.makeText(Items_List.this, "Successs", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Items_List.this, Item_Accept_Reject_List.class);
startActivity(intent);
}
else
Toast.makeText(Items_List.this, "Something went Wrong", Toast.LENGTH_SHORT).show();
}
catch (Exception ex){
Log.e("ERROR::",ex.getMessage());
}
}
#Override
public void onFailure(Call<ArrayList<price_get_set>> call, Throwable t) {
progress.dismiss();
Log.i("FAILURE ERROR::",t.getMessage());
}
});
}

You can use response.body().string().
It will convert your response in String.
Example On Your onResponse method of API you have to use this code.
#Override
public void onResponse(Response<ResponseBody> response) {
try {
String responseString = response.body().toString();//This a response as string
Log.d("Response : " + responseString);
} catch (IOException e) {
e.printStackTrace();
}
}

Related

in arraylist data.size() showing 0 which i want to return

please help me how to return data added which i'm using to set data to
cardview in recyclerview.
i didn't understand why arraylist size returning zero.anyone please explain.
private List<NotificationData> prepareData() {
data = new ArrayList<>();
data.clear();
SharedPreferences prfs = getSharedPreferences("userdetails", Context.MODE_PRIVATE);
String outletid = prfs.getString("outletid", "");
String authkey = prfs.getString("authkey", "");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://xxxxxx-yyyyy.zzzz.com/api/v1/outlet/cpf-ghh/" + outletid + "/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
FuelwareInterface fuelwareInterface = retrofit.create(FuelwareInterface.class);
Call<ResponseBody> responce_outlets;
Log.d("authkeyssss", "onClick: "+authkey);
responce_outlets = fuelwareInterface.getallindents(authkey);
responce_outlets.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String result = response.body().string();
Log.d("like", "*** " + result);
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonObject1=jsonObject.getJSONArray("data");
Log.d("ghllwnmm", "________"+jsonObject1.length());
int i=jsonObject1.length();
data.clear();
for (int j=0;j<i;j++){
JSONObject jsonObject2=jsonObject1.getJSONObject(j);
NotificationData notificationData = new NotificationData(jsonObject2.getString("vehicle_number"),
jsonObject2.getString("indent_number"),jsonObject2.getString("id"),
jsonObject2.getString("fill_type"),jsonObject2.getString("product"),
jsonObject2.getString("fill_date"),jsonObject2.getString("status"),
jsonObject2.getString("litre"),jsonObject2.getString("amount"));
data.add(notificationData);
}
Log.d("lk000jhgfs", "prepareMovieData: "+data.size());
adapter.notifyDataSetChanged();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getApplicationContext(),"Something Went Wrong",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failuremethods", "content " + call.toString());
}
});
Log.d("lkjhgfs", "prepareMovieData: "+data.size());
return data;
}
data which i want to return showing size zero which i don't want.
The problem is return statement won't wait till onResponse method is called , so it will return 0 immediately, if you want to get the data, pass an interface to method and use callback to post as in
interface
public interface ResultCallback{
void onResult(List<NotificationData> data);
}
Method
private void prepareData(ResultCallback callback) { //< make it void
// some code
responce_outlets.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String result = response.body().string();
Log.d("like", "*** " + result);
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonObject1=jsonObject.getJSONArray("data");
Log.d("ghllwnmm", "________"+jsonObject1.length());
int i=jsonObject1.length();
data.clear();
for (int j=0;j<i;j++){
JSONObject jsonObject2=jsonObject1.getJSONObject(j);
NotificationData notificationData = new NotificationData(jsonObject2.getString("vehicle_number"),
jsonObject2.getString("indent_number"),jsonObject2.getString("id"),
jsonObject2.getString("fill_type"),jsonObject2.getString("product"),
jsonObject2.getString("fill_date"),jsonObject2.getString("status"),
jsonObject2.getString("litre"),jsonObject2.getString("amount"));
data.add(notificationData);
}
callback.onResult(data); //<this will push data back to caller
Log.d("lk000jhgfs", "prepareMovieData: "+data.size());
adapter.notifyDataSetChanged();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getApplicationContext(),"Something Went Wrong",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failuremethods", "content " + call.toString());
}
});
//some code
}
Calling method to get data
prepareData(new ResultCallback(){
#Override
public void onResult(List<NotificationData> data){
// log data.size you will get everything
}
});

how to Passing headers and body at a time in retrofit

Im sending 2 headers and a body of class type here
#POST("/api/access/change-password")
Call<JsonElement> changePassword(#Header("Content-Type") String content_type,
#Header("Authorization") String AuthToken,
#Body PostChangePassword postChangePassword);
here i am posting the data to server. but it returns some error. It is working fine in postman. but not in here.
public void postData(String old_password, String new_password) {
Log.v("im here in retro0", "");
PostChangePassword postChangePassword = new PostChangePassword(sharedPrefUserData.getUserData().getUserId(), sharedPrefUserData.getUserData().getAuthToken(), old_password, new_password);
mAPIService.changePassword("application/json", "Bearer " + sharedPrefUserData.getUserData().getAuthToken(), postChangePassword).enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
Log.v("im here in retro1", response + "");
Gson gson = new Gson();
if (response.code() == 200) {
JsonElement jsonElement = response.body();
if (jsonElement.isJsonObject()) {
JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();
ResponseChangePassword object = gson.fromJson(objectWhichYouNeed, ResponseChangePassword.class);
}
} else {
Log.v("im here in retro2", response + "");
ResponseChangePassword responseChangePassword = null;
try {
responseChangePassword = gson.fromJson(response.errorBody().string(), ResponseChangePassword.class);
Toast.makeText(ProfileActivity.this, responseChangePassword.getMessage(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
// progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
// progressBar.setVisibility(View.GONE);
internetConnectionChecker.serverErrorAlert();
Log.v("im here in retro3", "");
}
});
}

How to return volley jsonobject from class to activity in android

I am trying volley library response, here i am getting response as per my expectation but am not am able to return the jsonobject to my activity, i am planning to write a single method that will give response all over the application in android, ok i am coming to the point now,
I have a class called Util.java, in this class i have return jsonobject like below
public JSONObject fetchResponse() {
try {
JSONObject json = new JSONObject();
json = createStuff();
URL = "my url here" + json.toString();
final JsonObjectRequest volleyRes = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//fetchRes = result(response);
//fetchRes = new JSONObject();
//fetchRes = new JSONObject(response.toString());
Log.w("UTIL res 61 ", fetchRes.toString());
// result(fetchRes);
} catch (Exception e) {
Log.w("UTILrespon error ", "" + e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
Log.w("UTIL res error ", "" + e);
}
});
volleyRes.setRetryPolicy(new DefaultRetryPolicy(10000, 2, 2));
AppController.getInstance().addToRequestQueue(volleyRes);
Log.w("UTIL res 83 ", fetchRes.toString());
} catch (Exception e) {
Log.e("UTIL Error ", "" + e);
}
return fetchRes;
}
Here fetchRes is an jsonobject which i declared outside of this method
now my problem is, when i am running my app, i can get the response from this method
#Override
public void onResponse(JSONObject response) {
try {
// fetchRes = result(response);
// fetchRes = new JSONObject();
fetchRes = new JSONObject(response.toString());
Log.w("UTIL res 61 ", response.toString());
// result(fetchRes);
} catch (Exception e) {
Log.w("UTILrespon error ", "" + e);
}
}
once i get the response i can't store in another jsonobject and can't return to my MainActivity.java in android.. so please anyone help me to come out of this problem
Thanks in advance
create classes of json object and use Gson library. It directly converts json string to objects.
Example :-
Gson gson = new Gson();
MyBean myBean;
myBean = gson.fromJson(response.toString,MyBeans.class);
Define an interface
interface FetResponseListener {
void onFetchResponse(JSONObject response);
}
Pass this interface as parameter to fetchResponse
public void fetchResponse(FetResponseListener listener) {
....
#Override
public void onResponse(JSONObject response) {
try {
listener.onFetchResponse(response);
} catch (Exception e) {
Log.w("UTILrespon error ", "" + e);
}
}
}
Implement FetResponseListener where you call fetchResponse
fetchResponse(new FetResponseListener() {
#Override
public void onFetchResponse(JSONObject response) {
// use json response
}
});
Or just use EventBus

getjson as response in retrofit 2.0

iam trying to get json resopse like this but it come with improper json format how can get the string in proper format
Call<HashMap<Object,Object>> call = RestClient.getClient().aladata(AppUtil.getAuthKey(DashboardActivity.this),String.valueOf(mSelectedCategory.getId()), String.valueOf(mLat), String.valueOf(mLng), String.valueOf(50), String.valueOf(offset * 50));
call.enqueue(new Callback<HashMap<Object,Object>>() {
#Override
public void onResponse(Call<HashMap<Object,Object>> call, Response<HashMap<Object,Object>> response) {
String hashMapString=response.body().toString();
try {
JSONObject jsonObject=new JSONObject(hashMapString);
String jsonstr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
HashMap<Object,Object> hashMap2=response.body();
}
#Override
public void onFailure(Call<HashMap<Object,Object>> call, Throwable t) {
}
});
}
When you work with Retrofit should to use JsonObject instead of JSONObject.
Hope it helps!

Retrofit - POST request with #Path and without parameters

The request to API as follows:
POST /verify/phone/{userid}/
Mandatory parameters: userid (integer)
Return: nothing
I receive Bad Request error all the time if I want to verify user with id 1 (for example):
Response{protocol=http/1.1, code=400, message=Bad Request, url=http://dummyapi.com/verify/phone/1/}
Posting the same request using Postman works well.
Code:
#POST("/verify/phone/{userid}/")
Call<String> postVerifyPhone(#Path("userid") int userId);
public void postVerifyPhone(int userID){
showProgressBar();
RestClient.GitApiInterface service = RestClient.getClient();
Call<String> call = service.postVerifyPhone(userID);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Response<String> response) {
hideProgressBar();
if (response.isSuccess()) {
String result = response.body();
} else {
Log.d("Fail: ", response.body()); //everytime here with Bad Request
}
}
#Override
public void onFailure(Throwable t) {
hideProgressBar();
}
});
}
I'm using String as the return type since there's message returned when there're no user with requested ID in db.
What could be a cause?
I am calling below code for reading response data.
public void postVerifyPhone(int userID){
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.URL).build();
RetrofitApi retrofitApi = restAdapter.create(RetrofitApi.class);
retrofitApi.postVerifyPhone(userID, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
// System.out.println("res:" + result.toString());
}
#Override
public void failure(RetrofitError error) {
hidePDialog();
}
});
}
below is postVerifyPhone() code
#FormUrlEncoded
#POST("/verify/phone/")
public void postVerifyPhone(#Field("userID") String userID, Callback<Response> resonse);
It is working fine for me.please check it once.
I think the right annotation is #PathParam, not #Path

Categories

Resources