POST data to server from android using session - android

I want to ask, I have session data and I want to post the session data to server.. I am using JsonArrayRequest..
Below is my code:
// untuk menampilkan semua data pada listview
private void callVolley(){
itemList.clear();
adapter.notifyDataSetChanged();
swipe.setRefreshing(true);
session.getLocalSession(LocalSession.KEY_USERNAME);
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setId(obj.getString(TAG_ID));
item.setNama(obj.getString(TAG_NAMA));
item.setAlamat(obj.getString(TAG_ALAMAT));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
Please somebody help me, where I can post the data....
this session in android:
session.getLocalSession(LocalSession.KEY_USERNAME);
I am using this code and showing all the data, I mean I just want to show some data with parameter session
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener()
Any help will be appreciated, Thanks.

As i can see you are using volley and creating instance of JsonArrayRequest, so you direct pass your array with JsonArrayReuest constructor please see the below code snippet.
public JsonArrayRequest(int method, String url, JSONArray yourArray,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}

Related

Not able to fetch JSON data [using volley Library] in Android

The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive

Do something after volley request is processed

I was working on parsing the nested JSON objects using Volley and I got the answer from the stackoverflow itself.
Parsing Nested JSON Objects using Volley
But I think the code can be optimized without the if else and also I have to display a text "No Data" if the volley request is null or no data received. I tried to check using adapter.isEmpty, adapter.getCount()
None of it worked.
This is my code
datalist=false;
progressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
schemeslist=false;
progressBar.setVisibility(View.INVISIBLE);
try {
JSONObject obj = new JSONObject(response);
JSONObject one = obj.getJSONObject("getProjectDetailsResult");
JSONObject two = one.getJSONObject("NewDataSet");
if(two.get("Rec") instanceof JSONArray) {
datalist=true;
JSONArray heroArray = two.getJSONArray("Rec");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
APIModel hero = new APIModel(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
} else {
datalist=true;
JSONObject heroObject = two.getJSONObject("Rec");
APIModel hero = new APIModel(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
// Toast.makeText(getApplicationContext(), " " + listView.getAdapter().getCount(),Toast.LENGTH_SHORT).show();
if(!datalist){
txtNoData.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
Can anyone tell me where should I put the if condition to work?
I checked with a toast for getting item count, but if there is no data, it is displaying blank and not 0. So I am not able to check
You can check size() of data list(heroList), size() is zero means you have no data.
try this
if(heroList.size() == 0){
txtNoData.setVisibility(View.VISIBLE);
}

Extract JSON from multiple URLs in Android Volley

I am currently using Volley to extract JSON contents using the following code.
JsonArrayRequest servicesStatus = new JsonArrayRequest(url1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
// Having obj to process further
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Now, I want one more JSON handler for the new URL and the dialog to be closed once it has successfully downloaded from both the URLs.
I tried to copy paste the above thing with url1 replaced by url2 and different jsonarrayrequest name. And added the hideDialog() in the second one. But the second one is not being called at all.
If you want make multiple request then you will have to add your Request to Queue. You can do it like this:
RequestQueue request = Volley.newRequestQueue(Context);
request.add(FirstRequest);
request.add(SecondRequest);
This should help you to add multiple request in Volley.

How to stop for loop execution until responce come in android

I want to add each user response to my list listItem, inserting the response's specific key and value pair. However, in this code, the first loop of getCat() executes 4 times ... then all responses get added to the last key those are 4.
public void getCat(){
String url = "http://******/*****/*****.json";
HashMap<String, List<CatType> hmap=new HashMap<String, ArrayList<CatType>>();
private List<ListItem> listItems;
for(int i=1;i<5;i++)
{
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Response: " + response.toString());
parseJsonFeed(response);
listItems = new ArrayList<ListItem>();
listItem.addAll(O_listItems);
hmap.put("["+i+"]",listItem);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("food");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
OrderListItem item=new OrderListItem();
item.setId(feedObj.getInt("id"));
item.setImage(feedObj.getString("image"));
item.setItem_name(feedObj.getString("name"));
O_listItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is happening because each time you make a request a new thread is created, so before the response comes back from the first hit, a new hit is made and this goes on. For such kind of situation it is better to use AsyncTask or make synchronous hits. See this answer for making synchronous hits.

com.android.volley.ParseError: org.json.JSONException

I got this error from volley library
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
the error
com.android.volley.ParseError: org.json.JSONException: Value [{"id":"admin","name":"Admin"}] of type org.json.JSONArray cannot be converted to JSONObject
How can I receive the result as string and then I will process it using jackson ?
If you want to receive the result as a string don't use the JSONRequest. Go with the simple Request class.
Your problem is pretty simple the server is giving back a JSONArray with just one element inside.
A JSONArray is not a JSONObject. That's why the parsing is failing.
We Have to use JsonArrayRequest instead of JsonObjectRequest. The code as:
RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://192.168.88.253/mybazar/get_product_list.php";
// prepare the Request
JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
// add it to the RequestQueue
queue.add(getRequest);
Hope, it's solve the problem.
I noticed that there is class JsonArrayRequest supported by volley so I use this class and the problem solved, I was using JsonObjectRequest
https://android.googlesource.com/platform/frameworks/volley/+/43950676303ff68b23a8b469d6a534ccd1e08cfc/src/com/android/volley/toolbox
Probably the below logic will work for you:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject1 = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject1.getJSONArray("statewise");
Log.d("Json response", "onResponse: "+jsonObject1.toString());
for (int i = 0; i < jsonArray.length; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Here you will get your result so can use textview
//to populate the result
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: "+error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}

Categories

Resources