Volley POST request Android token - android

I am new to new android programming and currently working with the Volley POST request library for a login page. I already have a working API which gives a String token when you make a post request. For now I have hard coded the username and password just to see if the post request works by creating a Toast. However, when I click on the submit button it prints out 200 in toast which doesnt make sense because the token is very big. It takes a few seconds for the toast to appear. This is what the API gives(I need the token):
{
"status": true,
"result": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjI4OTkiLCJvdGhlciI6eyJ1c2VyX2lkIjoiMjg5OSIsImRvbWFpbl9saXN0X2ZrIjoiMSIsInV1aWQiOiIxNTY4NzA2Mjg4ODk5IiwidXNlcl90eXBlIjoiNCIsInJlZ190eXBlIjoiMSIsImVtYWlsIjoiZmFpc2FsY2t5ZkBnbWFpbC5jb20iLCJwYXNzd29yZCI6ImY0NjY4Mjg4ZmRiZjk3NzNkZDk3NzlkNDEyOTQyOTA1Iiwic3RhdHVzIjoiMSIsImRhdGVfb2ZfYmlydGgiOm51bGwsImltYWdlIjpudWxsLCJ0aXRsZSI6bnVsbCwiYWdlbmN5X25hbWUiOm51bGwsImFnZW50X25hbWUiOm51bGwsImFnZW5jeV9lbWFpbCI6IiIsImZpcnN0X25hbWUiOiJGYWlzYWwiLCJtaWRkbGVfbmFtZSI6IiIsImxhc3RfbmFtZSI6bnVsbCwiYWRkcmVzcyI6IjMxIEQiLCJjaXR5IjoiUmFzaGlkaXlhIiwic3RhdGUiOiJEdWJhaSIsImNvdW50cnlfY29kZSI6IjIxMiIsImNvdW50cnlfbmFtZSI6IlVuaXRlZCBBcmFiIEVtaXJhdGVzIiwicGhvbmUiOiIwNTY2OTkzNzA5IiwicGhvbmVfY29kZSI6Iis5NzEiLCJvZmZpY2VfcGhvbmUiOm51bGwsInBpbl9jb2RlIjoiMTE0MTYwIiwicGFuX251bWJlciI6bnVsbCwicGFzc3BvcnRfbnVtYmVyIjoiIiwiY291bnRyeV9pc3N1ZSI6IjAiLCJwYXNzX2V4cGlyZV9kYXRlIjoiMDAwMC0wMC0wMCIsImNyZWF0aW9uX3NvdXJjZSI6InBvcnRhbCIsImNyZWF0ZWRfZGF0ZXRpbWUiOiIyMDE5LTA5LTE3IDA3OjQ0OjQ4IiwiY3JlYXRlZF9ieV9pZCI6IjAiLCJsYW5ndWFnZV9wcmVmZXJlbmNlIjoiZW5nbGlzaCIsInNpZ25hdHVyZSI6bnVsbCwic3ViX2FkbWluX3ByZXZpbGFnZSI6bnVsbCwicHJvbW9fY29kZSI6bnVsbCwiaG90ZWxfcHJvbW9fY29kZSI6bnVsbCwiY2FyX3Byb21vX2NvZGUiOm51bGwsImdyb3VwIjoiMCJ9LCJBUElfVElNRSI6MTU3MjQwMzU2Nn0.rU3NIqiHxsgOS7zeeuSCmPZP9Sc7RMXVGKWXni4JBLM"
}
}
Here is the current code that I have :
public class Login extends AppCompatActivity {
EditText username, password;
Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.username = findViewById(R.id.editTextUsername);
this.password = findViewById(R.id.editTextPassword);
this.loginButton = findViewById(R.id.buttonLogin);
this.loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(Login.this, "I just clicked the button",
Toast.LENGTH_LONG).show();
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
String URL =
"http://apidev.travelhouse.world/api/v1/user/login?
username=faisalckyf#gmail.com&password=faisal";
final JSONObject jsonBody = new JSONObject();
// jsonBody.put("username", "faisalckyf#gmail.com");
// jsonBody.put("password", "faisal");
final String requestBody = jsonBody.toString();
JsonArrayRequest jsonObjectRequest = new
JsonArrayRequest(Request.Method.POST, URL, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String token = "";
for (int i = 0; i < response.length(); i++)
{
try {
JSONObject hit =
response.getJSONObject(i);
token = hit.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(Login.this, token,
Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.toString(),
Toast.LENGTH_LONG).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
public byte[] getBody() {
try {
return requestBody == null ? null :
requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while
trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String>
parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString =
String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(response,
HttpHeaderParser.parseCacheHeaders(response));
}
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-API-KEY", "CODEX#123");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
//
});
//
}
}

You are parsing status code instead of result token in your parseNetworkResponse() function:
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
You need to change the return statement to this:
return Response.success(response, HttpHeaderParser.parseCacheHeaders(response));
As you can see, in your function you are taking the response but you are only passing the status code(responseString) to result.
Secondly your response is actually JSON object. You need to parse it to JsonObject (or use JsonObjectRequest) and then read value token nested in result.

Related

Best way to call Volley network call multiple times

I have one requirement, where I have to call Volley POST method near about 300-500 times. In post I am sending JSONObject and in response I am getting String as output. But my problem is when I call volley on some devices I am getting java.lang.OutOfMemoryError because calling service more than 300 times. Following is my code:
for (int i=0;i<myJsonArr.length();i++) // here myJsonArr may contains 300-500 json object
{
customRequestTest(allAppJson.getJSONObject(i));
}
public void customRequestTest(JSONObject jsonObject)
{
try {
String myURL = "My URL";
RequestQueue requestQueue = Volley.newRequestQueue(this);
final String mRequestBody = jsonObject.toString();
System.out.println (">>>>>>>>>>mRequestBody"+mRequestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, myURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_RESPONSE", response);
System.out.println (">>>>>>>>onResponse"+response +" for request "+mRequestBody);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_RESPONSE", error.toString());
System.out.println (">>>>>>>>onErrorResponse"+error.toString()+" for request "+mRequestBody);
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
String str = new String(response.data);
responseString = str;
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (Exception e) {
System.out.println (">>>>>>>>Inside catch of customRequestTest");
e.printStackTrace();
}
}
getting Out of memory erorr at : RequestQueue requestQueue = Volley.newRequestQueue(this);

Server responce is in json form

I want to send and receive data from server. For this I've used Volley. The code is in below. Volley can receive the data in Json format. The Server can send and receive data in Json format. How do I convert this Json data into a user readable JAVA format ?? There are about 10 methods in other class. The below class contains the methods for network calls and also interacts with the MainActivity.
public class Api_Volley {
String data;
String flag;
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(Object response) {
String flag = response.toString();
Toast.makeText( context , flag , Toast.LENGTH_LONG ).show();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
}
Methods in another class:
public void showAllOrderByUserId() {
try {
data_args.put("userId", 2);
} catch (JSONException e) {
e.printStackTrace();
}
try {
data_action.put("action", "showAllOrderByUserId");
data_action.put("args", data_args);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
route = "/order";
new Api_Volley().my_volley_post(addUserUrl + route, data_action, context);
}
Your can use json data like
{"userNodes":[{"id":"1","name":"Enamul Haque"}]}
You can use volley like bellow
private void doLoginAction() {
String url_login = "http://www.lineitopkal.com/android/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("userNodes");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String id = jo.getString("id");
Log.e("id ::",id);
String name = jo.getString("name");
Log.e("name ::",name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Post parameter like bellow
params.put("uname", "era#gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Create your Response format like this
public class Post {
long id;
Date dateCreated;
String title;
String author;
String url;
String body;
}
After making request like below
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
// This will be your Entity
Post post = gson.fromJson(response, Post.class));
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
You have to parse JSON and have to show according to need:
By this you can use GSON (Its easy)
Use this Site to convert JSON to pojo classes.
Click here
These are the References site you can use and implement :
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
https://kylewbanks.com/blog/tutorial-parsing-json-on-android-using-gson-and-volley

Android Json Arraylist to Server with Restful Web service

This is my Arraylist which I get from the previous fragment,
listoftags = getArguments().getParcelableArrayList("data");
It works well. Now I have to send this with some parameters like below:
public void volleyJsonObjectRequest(final String SessionID , final String CustomerID, final String ServiceState , final String ServiceID, final String Address, final String PaymentMode, final String CustomerComments , final ArrayList Items){
String REQUEST_TAG = "volleyJsonObjectRequest";
// POST parameters
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
/* String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(getActivity(), ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
// Intent i = new Intent(SignActivity.this, LoginActivity.class);
// startActivity(i);
// finish();
}*/
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
/* #Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}*/
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
JSONArray jsArray = new JSONArray(listoftags);
params.put("SessionID", SessionID);
params.put("CustomerID", CustomerID);
params.put("ServiceState", ServiceState);
params.put("ServiceID", ServiceID);
params.put("Address", Address);
params.put("PaymentMode",PaymentMode);
params.put("CustomerComments",CustomerComments);
params.put("Items",jsArray.toString());
return params;
}
};
AppSingleton.getInstance(getActivity().getApplicationContext())
.addToRequestQueue(request, REQUEST_TAG);
}
but it getting error to me I want to send it like
// server side //
{
"SessionID":"9lm5255sg0ti9",
"CustomerID":"9",
"ServiceState":"Karnataka",
"ServiceID":"3",
"Address":"sfaff",
"PaymentMode":"cash",
"CustomerComments":"this is fine",
"Items":[
{
"ItemId":1,
"Cost":6777,
"Quantity":33333
}
]
}
How can send arraylist, with other strings, as raw data using volley on server.
JsonObjectRequest can be used to execute rest api using json as input.
JsonObject jobj = new JsonObject();
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
JsonObjectRequest request = new JsonObjectRequest(requestURL, jobj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
}
});
*Now add this request in request queue of volley.*
Here jobj is containing input parameters. It can contain even json array inside a JsonObject. Let me know in case of any query.
Rather then volley try retrofit. Make pojo model of your object you want to send, you can make that from pojo classes from https://www.jsonschema2pojo.org the send the whole object on restapi
// try the request //
try {
REQUEST QUEUE
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = url;
JSONObject jsonBody = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Iterator itr = listoftags.iterator();
while(itr.hasNext()){
AddRowItem ad=(AddRowItem)itr.next();
jsonObject.put("ItemId:",1);
jsonObject.put("Cost:",ad.getPrices());
jsonObject.put("Quantity:",ad.getQty());
// Log.d("ItemId:",""+1+" "+"Cost:"+ad.getPrices()+" "+"Quantity:"+ad.getQty());
}
jsonArray.put(jsonObject);
JSON VALUES PUT
jsonBody.put("SessionID", "9kp0851kh6mk3");
jsonBody.put("CustomerID", "9");
jsonBody.put("ServiceState", "Karnataka");
jsonBody.put("ServiceID", "3");
jsonBody.put("Address", "Address Demo");
jsonBody.put("PaymentMode", "cost");
jsonBody.put("CustomerComments", "Android Volley Demo");
jsonBody.put("Items", jsonArray);
final String requestBody = jsonBody.toString();
Log.d("string ---- >",""+requestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
showToast("get value"+response.toString());
try {
JSONObject jObj = new JSONObject(response);
String action = jObj.get("ActionStatus").toString();
String status = jObj.getString("StatusMessage");
{"ActionStatus":"Success","StatusMessage":"Order Created","RefIDName":"OrderID","RefIDValue":19}
showToast("get value"+action);
}
catch (JSONException e)
{
showToast("get error"+e.toString());
Log.d("errorissue",""+e.toString());
}
dismissProgress();
}
}, new Response.ErrorListener() {
// error response //
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
showToast("get error"+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
dismissProgress();
}
}
}
// THIS IS THE WAY ISSUE RESLOVED //
THANKS EVERYONE ...

Volley delete request with body data not working

hello everyone im facing a problem with volley delete request .
i working on task in user add or remove some contacts by it's id .
im using volley library for it.
API is tested with postman and working fine.
private void AddContactInList(final Contacts contacts,int RequestMethod) {
JSONArray ContactArray = new JSONArray();
ContactArray.put(StoredContactid);
final String jsonStr = ContactArray.toString();
String URl = OrganizationModel.getApiBaseUrl() + getOrgId() + "/lists/" + contacts.getId()+"/contacts";
Log.i(TAG,URl);
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(RequestMethod,URl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
try {
JSONArray mJSONArray = response.getJSONArray("contactIds");
contacts.setCode(String.valueOf(mJSONArray.length()));
long time = System.currentTimeMillis();
sqliteDataBaseHelper.changeContactUpdatedON(StoredContactid, String.valueOf(time));
sqliteDataBaseHelper.updateListContactsAndLength(contacts.getId(), mJSONArray.toString(), (mJSONArray.length()));
dataAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.toString());
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
case 405:
json = new String(response.data);
json = dataHelper.trimMessage(json, "message");
if (json != null) dataHelper.displayMessage(json);
break;
}
}
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
try {
return jsonStr == null ? null : jsonStr.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
jsonStr, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Basic " + GetApiAccess());
return headers;
}
};
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
9000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonArrayRequest);
}
In my SQLite Database , the below code is working. Hope it may help you..
public void DeleteData(){
btnDltData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deleteRows = myDB.deleteData(editId.getText().toString());
if(deleteRows > 0)
Toast.makeText(MainActivity.this, "Task Clear..", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Task not Clear..", Toast.LENGTH_SHORT).show();
editId.setText("");
}
}
);
}
http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
try this, if problem didnt solve yet

Android Volley onResponse get data

In a string post request for logging in. in onResponse all i am returned is the status code of 200. I would like to get the data returned as well. I am not sure where to go from this point forward? Any ideas on how to get the data returned, and not just the status code?
public void requestWithSomeHttpHeaders() {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://......";
JSONObject jsonBody = new JSONObject();
jsonBody.put("username", "yourusername");
jsonBody.put("password", "yourpassword");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
System.out.println(responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Preferably, define a method.
private void doLogin() {
// TODO: startActivity?
}
Then call that
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
doLogin();
}
If you want the data from the server, that is what String response is. Check your Logcat.
As mentioned in the comments, using StringRequest without implementing getBody, parseNetworkResponse, and getBodyContentType might work better.
If you want to parse JSON add method like this
public Profile getUserProfile(String response){
Profile profile = null;
try {
profile = new Profile();
JSONObject jsonObject = new JSONObject(response);
profile.setId(jsonObject.getInt(context.getString(R.string.profile_id)));
profile.setLastName(jsonObject.getString(context.getString(R.string.profile_lastName)));
profile.setName(jsonObject.getString(context.getString(R.string.profile_name)));
profile.setEmail(jsonObject.getString(context.getString(R.string.profile_email)));
} catch (JSONException | NullPointerException e) {
e.printStackTrace();
return null;
}
return profile;
}
In your onResponse method
#Override
public void onResponse(String response) {
//If you have son object
Profile profile = getUserProfile(response)
}

Categories

Resources