Post data request using Volley - android

i am trying to post data on server using volley but it just give me Volley.ServerError when i click on submit button.But also When i debug my app then all parameters get value but instead of that their is error.
public class ConnectWithSpeaker extends AppCompatActivity implements
View.OnClickListener {
LinearLayout linear_layoutcontainer;
Toolbar toolbar;
String url = Constants.SUBMIT_API;
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_MOBILE = "mobile";
public static final String KEY_COMPANY = "company";
public static final String KEY_SPEAKERID = "speaker_id";
String s_id;
private EditText u_name;
private EditText u_email;
private EditText u_mobile;
private EditText u_company;
private Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect_with_speaker);
linear_layoutcontainer = (LinearLayout) findViewById(R.id.linear_layoutcontainer);
toolbar = (Toolbar) findViewById(R.id.customtoolbar);
TextView title = (TextView) toolbar.findViewById(R.id.title);
title.setText("Connect with Speakers");
toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
u_name = (EditText) findViewById(R.id.name);
u_email = (EditText) findViewById(R.id.email);
u_mobile = (EditText) findViewById(R.id.mobile);
u_company = (EditText) findViewById(R.id.compny_name);
submit = (Button) findViewById(R.id.connect);
submit.setOnClickListener(this);
s_id = getIntent().getStringExtra("speakerid");
}
private void submitdetails() {
final String name = u_name.getText().toString().trim(); //trim() remove spaces after&before string
final String email = u_email.getText().toString().trim();
final String mobile = u_mobile.getText().toString().trim();
final String company = u_company.getText().toString().trim();
final String speaker_id = s_id;
Toast.makeText(ConnectWithSpeaker.this, "submit details", Toast.LENGTH_SHORT).show();
CustomJSONObjectRequest request2 = new CustomJSONObjectRequest(Request.Method.POST, url, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response........"+response);
if (response.trim().equals("success")) {
Toast.makeText(getApplicationContext(), "Your request is proceed, we will update you with further updates.",
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(ConnectWithSpeaker.this, volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_NAME, name);
params.put(KEY_EMAIL, email);
params.put(KEY_MOBILE, mobile);
params.put(KEY_COMPANY, company);
params.put(KEY_SPEAKERID, speaker_id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request2);
}
#Override
public void onClick(View v) {
if (v == submit) {
if (TextUtils.isEmpty(u_name.getText().toString())) {
u_name.setError("Enter Name");
u_name.requestFocus();
}
if (TextUtils.isEmpty(u_email.getText().toString())) {
u_email.setError("Enter Email");
u_email.requestFocus();
}
if ((TextUtils.isEmpty(u_mobile.getText().toString())) || (u_mobile.length() < 10 || u_mobile.length() > 15)) {
u_mobile.setError("Enter valid Mobile No");
u_mobile.requestFocus();
}
if (TextUtils.isEmpty(u_company.getText().toString())) {
u_company.setError("Enter Company Name");
u_company.requestFocus();
} else {
submitdetails();
}
}
}
This is the error in logcat.
E/Volley: [1515] BasicNetwork.performRequest: Unexpected response code 400 for http://

I am using this.
public class AEJsonRequest extends JsonObjectRequest {
private static int mStatusCode;
public AEJsonRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
ServerHandler.bwLog("sending params", jsonRequest.toString());
}
public AEJsonRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
public static int getStatusCode() {
return mStatusCode;
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if (volleyError.networkResponse != null && volleyError.networkResponse.data != null) {
mStatusCode = volleyError.networkResponse.statusCode;
ServerHandler.bwLog("Error Status code", "" + mStatusCode);
VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
volleyError = error;
}
return volleyError;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Accept", "application/json");
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
}
and call it to
public void submitDetail(HashMap<String, String> hashMap) throws JSONException {
//param is the JSONobject
final AEJsonRequest jsonRequest = new AEJsonRequest(Request.Method.POST, "url", new JSONObject(hashMap),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// if status is true, it will return the json data to its calling activity
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
MAX_TIMEOUT_MS,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsonRequest);
}
Hope this'd help

Related

Send Object as Data with POST Method in Android Volley?

I am using POST method and trying to Send Object as data using Android Volley Library to change the Current Password to New One but I am not Able to do it.
SettingFragment
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
/*
// JSONObject js = new JSONObject();
try {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = 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());
// error.getMessage();
}
}) {
#Override
public String getBodyContentType() {
return "Content-Type;application/x-www-form-urlencoded";
}
#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;
}
}
#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));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
*/
// JSONObject params = new JSONObject();
// params.put(KEY_Name, Name);
// params.put(KEY_MasterID, master_id);
// params.put(KEY_USERNAME, username);
// params.put(KEY_OldPASSWORD, oldpassword);
// params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
// headers.put(KEY_Name, Name);
// headers.put(KEY_MasterID, master_id);
// headers.put(KEY_USERNAME, username);
// headers.put(KEY_OldPASSWORD, oldpassword);
// headers.put(KEY_UserPassword, newpassword);
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Backend object looks like
Users = {
NAME: vm.name,
UserName: vm.currentUserName,
oldPassword:vm.oldPassword,
UserPassword: vm.UserPassword
Users.MasterID = vm.masterID;
}
I am able to send through the POSTMan but through Code i am not able to do it.
logcat
05-29 16:16:49.764 1114-2077/com.example.user.mis E/Volley: [651] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.100.5:84/api/usersApi/updateByMasterID
How can this issue be Solved?
You may try this code, I have implemented the same thing as you do ... it might work for you
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put(KEY_Name, Name);
headers.put(KEY_MasterID, master_id);
headers.put(KEY_USERNAME, username);
headers.put(KEY_OldPASSWORD, oldpassword);
headers.put(KEY_UserPassword, newpassword);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
You can try this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = 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 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(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
You should change the StringRequest to JSONObjectRequest as you are working with a JSON object in the backend. So you should pass the strings as a JSON object and then it might work.
private void makeJsonObjectRequest() throws JSONException {
JSONObject cred = new JSONObject();
cred.put("username", username.getText().toString());
cred.put("password", password.getText().toString());
JsonObjectRequest jsonObjReq = new
JsonObjectRequest(Request.Method.POST,
urlJsonPost, cred, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
//aftererror:
try {
// Parsing json object response
// response will be a json object
token = response.getString("token");
adminName = response.getString("adminName");
jsonResponse = "";
jsonResponse += "token:" + token ;
jsonResponse += "adminName:" + adminName;
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}});AppController.getInstance().addToRequestQueue(jsonObjReq);
You would also need to create a class named AppController.java and punch in the below code
import android.app.Application;
import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
You can also send POST parameters as JSONObject with the StringRequest.
Try this one:
private static final String KEY_Name = "NAME"
private static final String KEY_MasterID = "MasterID"
private static final String KEY_USERNAME = "UserName"
private static final String KEY_OldPASSWORD = "oldPassword"
private static final String KEY_UserPassword= "UserPassword"
..........
..................
JSONObject params = new JSONObject();
params.put(KEY_Name, Name);
params.put(KEY_MasterID, master_id);
params.put(KEY_USERNAME, username);
params.put(KEY_OldPASSWORD, oldpassword);
params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Navigation_URL_SettingRequest, params,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
..............
...................
I have broken masterID and Send only the integer for the login, but in the changing password i want all the masterID without broken.Which is not added by me,thats the error and has to sent through the parameter section.
working code is shown below
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, "s" + master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
Toast.makeText(getContext(), "", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}

How to put Cookie session id into volley request?

So, i have this code to make a POST request with volley:
public class MainActivity extends AppCompatActivity {
Button btnSearch;
ProgressDialog loadingDialog;
ListView lvResult;
String session_id;
RequestQueue queue;
MyCookieManager myCookieManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch = (Button) findViewById(R.id.btnSearch);
lvResult = (ListView) findViewById(R.id.lvResult);
loadingDialog = new ProgressDialog(MainActivity.this);
loadingDialog.setMessage("Wait.\nLoading...");
loadingDialog.setCancelable(false);
myCookieManager = new MyCookieManager();
requestCookie(); //FIRST CALL TO GET SESSION ID
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showLoading();
requestWithSomeHttpHeaders(); //CALL TO MAKE THE REQUEST WITH VALID SESSION ID
}
});
}
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
//
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO&param2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map < String, String > getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap < String, String > ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//params.put("Set-Cookie", session_id);// + " _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
//"PHPSESSID=ra0nbm0l22gsnl6s4jo0qkqci1");
return params;
}
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(postRequest);
}
public void requestWithSomeHttpHeaders() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
Log.d("Response", response);
String x = myCookieManager.getCookieValue();
String status = "";
try {
JSONObject resultObject = new JSONObject(response);
Log.d("JSON RESULT =>", resultObject.toString());
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
hideLoading();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO&param2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map <String, String> getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap <String, String> ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
params.put("Cookie", /*myCookieManager.getCookieValue()*/ session_id + "; _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
return params;
}
};
queue.add(postRequest);
}
private void showLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!loadingDialog.isShowing())
loadingDialog.show();
}
});
}
private void hideLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loadingDialog.isShowing())
loadingDialog.dismiss();
}
});
}
}
If I send a valid cookie ID this return a valid JSON object else a empty object.
I tried (unsuccessfully) to set default cookie handles like
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
but I get a empty object.
How to put a valid cookie session ID to post request?
So the problem was getting a valid cookie. My mistake was to get it from the POST request itself. I kept the same working principle, getting the cookie when I started the application but using GET instead of POST and calling the root of the URL instead of the address where I get the JSON.
My solution looked like this:
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(getRequest);
}
Using cookies with Android volley library
Request class:
public class StringRequest extends com.android.volley.toolbox.StringRequest {
private final Map<String, String> _params;
/**
* #param method
* #param url
* #param params
* A {#link HashMap} to post with the request. Null is allowed
* and indicates no parameters will be posted along with request.
* #param listener
* #param errorListener
*/
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
ErrorListener errorListener) {
super(method, url, listener, errorListener);
_params = params;
}
#Override
protected Map<String, String> getParams() {
return _params;
}
/* (non-Javadoc)
* #see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
*/
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
MyApp.get().checkSessionCookie(response.headers);
return super.parseNetworkResponse(response);
}
/* (non-Javadoc)
* #see com.android.volley.Request#getHeaders()
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
}
MyApp:
public class MyApp extends Application {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
private static MyApp _instance;
private RequestQueue _requestQueue;
private SharedPreferences _preferences;
public static MyApp get() {
return _instance;
}
#Override
public void onCreate() {
super.onCreate();
_instance = this;
_preferences = PreferenceManager.getDefaultSharedPreferences(this);
_requestQueue = Volley.newRequestQueue(this);
}
public RequestQueue getRequestQueue() {
return _requestQueue;
}
/**
* Checks the response headers for session cookie and saves it
* if it finds it.
* #param headers Response Headers.
*/
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* #param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}
}
You getting cookie (Session id) in Login response, Save cookie in sharedpreference or other db, and use that to send in request.
for getting cookie from login request
CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.POST, SIGN_IN_URL,
new Response.Listener<CustomStringRequest.ResponseM>() {
#Override
public void onResponse(CustomStringRequest.ResponseM result) {
CookieManager cookieManage = new CookieManager();
CookieHandler.setDefault(cookieManage);
progressDialog.hide();
try {
//From here you will get headers
String sessionId = result.headers.get("Set-Cookie");
String responseString = result.response;
Log.e("session", sessionId);
Log.e("responseString", responseString);
JSONObject object = new JSONObject(responseString);
CustomStringRequest class
public class CustomStringRequest extends Request<CustomStringRequest.ResponseM> {
private Response.Listener<CustomStringRequest.ResponseM> mListener;
public CustomStringRequest(int method, String url, Response.Listener<CustomStringRequest.ResponseM> responseListener, Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = responseListener;
}
#Override
protected void deliverResponse(ResponseM response) {
this.mListener.onResponse(response);
}
#Override
protected Response<ResponseM> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
ResponseM responseM = new ResponseM();
responseM.headers = response.headers;
responseM.response = parsed;
return Response.success(responseM, HttpHeaderParser.parseCacheHeaders(response));
}
public static class ResponseM {
public Map<String, String> headers;
public String response;
}
}
set cookie when add request to server..
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String session=sharedPreferences.getString("sessionId","");
headers.put("Cookie",session);
return headers;
}

getting error org.json.JSONException: Value <pre of type java.lang.String cannot be converted to JSONObject

I want to access my Android apps through Web-Service.
but getting error in my android app ,
i am using volley & POST method for login.. `public class Main extends AppCompatActivity implements View.OnClickListener
{
public static final String LOGIN_URL = "http://10.54.103.8:4067/evivaservices/Webservices/login";
public static final String KEY_USERNAME="username";
public static final String KEY_PASSWORD="password";
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonLogin;
private String username;
private String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
editTextUsername = (EditText) findViewById(R.id.username1);
editTextPassword = (EditText) findViewById(R.id.password1);
buttonLogin = (Button) findViewById(R.id.login_button);
buttonLogin.setOnClickListener(this);
}
private void userLogin() {
username = editTextUsername.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try
{
JSONObject jsonObject = new JSONObject(response);
Next();
}
catch(JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.toString(), Toast.LENGTH_LONG ).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put(KEY_USERNAME,username);
map.put(KEY_PASSWORD,password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void Next(){
Intent intent = new Intent(this, HomeScreen.class);
intent.putExtra(KEY_USERNAME, username);
startActivity(intent);
}
#Override
public void onClick(View v)
{
userLogin();
}
}
`
JSON DATA
{
"id": 31,
"username": "andrew.cope#services.co.in",
"user_image": "http:\/\/103.54.103.8:4067\/evivaservices\/img\/profile_31.png",
"err-code": 0
}
`
Please change your StringRequest to JsonRequest as below:
JsonRequest jsonRequest = new JsonRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<>() {
#Override
public void onResponse(Object response) {
try {
Next();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
return map;
}
#Override
protected Response parseNetworkResponse(NetworkResponse response) {
return null;
}
#Override
public int compareTo(Object another) {
return 0;
}
};
Thank You.
Hello dear you made a mistake while you parsing the response
JSONArray jsonArray=jsonObject.getJSONArray("err-code")
remove above the line and then parse again.
In you JSON DATA, I not find array, so you shouldn't use JsonArray, you can delete this line in your code :JSONArray jsonArray=jsonObject.getJSONArray("err-code").

Android volley how to receive and send a json

I making an app and in a specific part I send a string and receive a json. I USE VOLLEY
It works good, but now i need to send a json.
HERE IS MY CODE:
public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id="; // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
HERE:
public class Config {
public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id="; // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
public static final String KEY_NAME = "COD_ALUMNO";
public static final String KEY_ADDRESS = "COD_ASIGNATURA";
public static final String KEY_VC = "GRUPO_SECCION";
public static final String KEY_AULA = "AULA";
public static final String KEY_DIA = "DIA";
public static final String KEY_INICIO = "INICIO";
public static final String KEY_FIN = "FIN";
public static final String JSON_ARRAY = "result";
}
AND HERE IS THE PART OF VOLLEY CODE
public class TabsActivity extends AppCompatActivity implements
View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
int cont=1;
String[ ] contenido = new String[7];
String f="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainint);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
Toast.makeText(getBaseContext(), "si", Toast.LENGTH_LONG).show();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TabsActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
// Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
String name="";
String address="";
String grupo = "";
String aula = "";
String dia = "";
String inicio = "";
String fin = "";
try {
Toast.makeText(getBaseContext(), "LOGIN... ", Toast.LENGTH_LONG).show();
JSONObject jsonObject = new JSONObject(response);
JSONArray ja = jsonObject.getJSONArray("orders");
// JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
for (int i = 0; i < ja.length(); i++) {
JSONObject collegeData = ja.getJSONObject(i);
name = collegeData.getString("id");
address = collegeData.getString("item");
grupo = collegeData.getString("GRUPO_SECCION");
aula = collegeData.getString("AULA");
dia = collegeData.getString("DIA");
inicio = collegeData.getString("INICIO");
fin = collegeData.getString("FIN");
///database
DBAdapter db= new DBAdapter(this);
db.open();
long id = db.insertContact(address, aula,dia,inicio,fin );
db.close();
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{ do{
contenido=getcontenido(c);
}while (c.moveToNext());
}
db.close();
cont= Integer.parseInt( contenido[0]);
/// database
/// alarms
int [] time;
time = parsetime(inicio);
int horai = time[0];
int minutoi = time[1];
int diaa = getDay(dia);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, horai);
cal.set(Calendar.MINUTE, minutoi);
cal.set(Calendar.DAY_OF_WEEK, diaa);
cal.add(Calendar.SECOND, 2);
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.putExtra("name", address);
//intent.putExtra("curos bn",1);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(getBaseContext(),
cont+1, intent, PendingIntent.FLAG_UPDATE_CURRENT );
AlarmManager alarmManager =
(AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);
////alarms
f=f+"codigo alumno:\t"+name+"\ncodigo/nombre curso:\t" +address+ "\ngrupo:\t"+grupo+"\naula:\t"
+aula+"\ndia:\t"+dia+"\ninicio:\t"+inicio+"\nfin:\t"+fin+"\n:\t";
}
// Toast.makeText(getBaseContext(), collegeData.length(), Toast.LENGTH_LONG).show();
//collegeData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText(f);
}
I JUS SENT THE STRING editTextId.getText() . That is a code for each user , but now i need to send a json with that string .
'CCODUSU' '45875621'
CCODUSU is the identifier
I would take a look at StringRequests. Here is an example of how to send things to a PHP file, which updates a database, or can do whatever:
SetMyStuff.java:
package com.example.your_app.database_requests;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class SetMyStuff extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://example.com/SetMyStuff.php";
private Map<String, String> params;
public SetMyStuff(String username, String password, Response.Listener<String> listener) {
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
To call this StringRequest:
Response.Listener<String> listener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (!success) {
Log.e(TAG, "Could not update stuff.");
} else {
Log.e(TAG, "Updated stuff.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
SetMyStuff setMyStuffRequest = new SetMyStuff(username, password, listener);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(setMyStuffRequest);
The PHP file that recieves this:
<?php
$password = $_POST["password"];
$username = $_POST["username"];
$con = mysqli_connect("website.com", "dbusername", "dbpassword", "dbtable");
$response = array();
$response["success"] = false;
/* Do something */
$response["success"] = true;
echo json_encode($response);
?>
Do you mean you need send a JSON which contains the editTextId.getText().toString().trim(), if you want to do this, you must spell out a complete and correct JSON.
'CCODUSU' '45875621'
The string you post is not a json, you need to modify it into this:
{"CCODUSU": "45875621"}
Once you give this string after your Config.DATA_URL, the server will receive the id parameter and it is the JSON.
I also came up with this same issue.On the course of finding way I have developed a way that might help you.
If you want to post json to the server then you can create JsonObjectRequest as:
public class AppJSONObjectRequest extends JsonObjectRequest{
private Response.Listener<JSONObject> listener;
private Map<String, String> headers;
public AppJSONObjectRequest(int method, String url, JSONObject jsonObject, Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener, Map<String, String> headers) {
super(method, url, jsonObject, reponseListener, errorListener);
this.headers = headers;
this.listener = reponseListener;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
}
And then you can use this jave file in your activity or fragment to send json and recieve response like this below:
JSONObject parameters = new JSONObject();
try {
parameters.put("f_name", "name1");
parameters.put("l_name", "name2");
.......
}catch (Exception e){
e.printStackTrace();
}
AppJSONObjectRequest objectRequest = new AppJSONObjectRequest(Request.Method.PUT, url, parameters, RequestSuccessListener, RequestErrorListener, getHeaders); //headers if u have
//url: your request base url
VolleySingleton volleySingleton = VolleySingleton.getInstance(this);
volleySingleton.addToRequestQueue(objectRequest);
And you can receive json as :
Response.Listener<JSONObject> RequestSuccessListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Response" + " " + response);
}
};
Response.ErrorListener RequestErrorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
you can get headers as:
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("x-auth-token", Constant.API_KEY_X_AUTH_TOKEN);
return headers;
}
VolleySingleton class
public class VolleySingleton {
private static VolleySingleton mInstance;
private Context mContext;
private RequestQueue mRequestQueue;
private VolleySingleton(Context context){
this.mContext = context;
mRequestQueue = getRequestQueue() ;
}
public static synchronized VolleySingleton getInstance(Context context){
if(mInstance == null){
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req){
getRequestQueue().add(req);
}
}
Just you can implement above sample... then hope you will get what you want.it may be copy paste code but it covers overall enough to solve your problem.

parsing Json data from server using parameters

i am new in android. i am making an application in which i am getting the data from server using volley library. but i dont know how to fetch data from server when we use id or parameters. please help.
public class MainActivity extends AppCompatActivity {
Button btn_next,btn_search,cross;
TextView title;
EditText et;
private ProgressDialog pDialog;
public static final String JSON_URL = "http://bcshymns.com/heading.php";
private Button buttonGet;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cross=(Button)findViewById(R.id.cross);
et=(EditText)findViewById(R.id.search);
btn_next=(Button)findViewById(R.id.btnnext);
btn_search=(Button)findViewById(R.id.btnsearch);
title=(TextView)findViewById(R.id.tv_title);
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cross.setVisibility(View.VISIBLE);
title.setVisibility(View.INVISIBLE);
et.setVisibility(View.VISIBLE);
}
});
cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
title.setVisibility(View.INVISIBLE);
btn_search.setVisibility(View.VISIBLE);
}
});
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Subheading.class);
startActivity(i);
}
});
listView = (ListView) findViewById(R.id.listView);
sendRequest();
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// String product = ((TextView) view).getText().toString();
Intent i=new Intent(getApplicationContext(),Subcontent_main.class);
startActivity(i);
}
});
}
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON_Heading pj = new ParseJSON_Heading(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON_Heading.heading,ParseJSON_Heading.from,ParseJSON_Heading.to);
listView.setAdapter(cl);
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}`
public class ParseJSON_Heading {
public static String[] heading;
public static String[] from;
public static String[] to;
public static String[] id;
public static final String JSON_ARRAY_SUBHEADING = "tbl_heading";
public static final String JSON_ARRAY_HEADING = "tbl_heading";
public static final String KEY__HEADING_ID = "intheadingId";
public static final String KEY_TEXT_HEADING = "vchheading";
public static final String KEY_TEXT_FROM = "vchfrom";
public static final String KEY_TEXT_TO = "vchto";
private JSONArray users = null;
private String json;
public ParseJSON_Heading(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY_HEADING);
id=new String[users.length()];
heading = new String[users.length()];
from = new String[users.length()];
to = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
id[i]=jo.getString(KEY__HEADING_ID);
heading[i] = jo.getString(KEY_TEXT_HEADING);
from[i] = jo.getString(KEY_TEXT_FROM);
to[i] = jo.getString(KEY_TEXT_TO);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
If you need to submit request parameters, then you have to override the getParams() method which should return list of parameters to be sent in a key value format.
In the code below we submit name, email and password as request parameters.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "foo");
params.put("email", "abc#gmail.com");
params.put("password", "foobar");
return params;
}
};

Categories

Resources