How to fix ‘null json data ’ error in Android Studio - java

I'm trying to convert a string array list to a JSONArray then send it to a remote server
I expect it to send my array in a JSONarray format
this is the error "'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference"
My array got 2 elements,
when i try to fetch them in the log.d : list ja [null,null]
This is the code i'm using
public void sendCommande (){
bt_newCommande.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//----------------------------------
StringRequest stringRequest = new StringRequest(Request.Method.POST,url_ProdCommande, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,"element envoie !");
//listProRest.clear();
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
JSONArray ja = new JSONArray(db.afficherTousProduit());
Log.d(TAG,"list ja "+ja.toString());
for(int i =0;i<ja.length();i++){
JSONObject j = ja.optJSONObject(i);
/*
try {
params.put("idProduit",j.getString(db.afficherTousProduit().get(i).getIdProduct()));
params.put("qte",j.getString(String.valueOf(db.afficherTousProduit().get(i).getQtePro())));
params.put("heure",j.getString(db.afficherTousProduit().get(i).gethCollete()));
params.put("date",j.getString(db.afficherTousProduit().get(i).getDateCollete()));
} catch (JSONException e) {
e.printStackTrace();
}
*/
}
//params.put("id",arrayList.get(position).getIdProduct());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
}

It looks like something is going wrong with
db.afficherTousProduit().get(i).getIdProduct()
I would set a breakpoint and check that the db is returning what you expect it to return.
From looking at your code, it seems like you are doing extra work converting to and from JSON several times. I could be wrong, but I think this could be cleaned up like so:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
JSONArray ja = new JSONArray(db.afficherTousProduit());
Log.d(TAG,"list ja "+ja.toString());
// Begin iterating through the JSON Array
for (int i=0; i < arr.length(); i++) {
// Get current JSON Object at index i
JSONObject j = arr.getJSONObject(i)
try {
// Return the specified value associated with the String for the current object
params.put("key",j.getJsonString("key");
} catch (JSONException e) {
e.printStackTrace();
}
}
//params.put("id",arrayList.get(position).getIdProduct());
return params;
}
It shouldn't require more than one db access to get the json array, and then it's a simple matter of iterating through each object and grabbing what you need from it. Check out the Java docs for more info.

Related

How to send Array in Android StringRequest

I want to send Array to server that looks like this :
"Array":["name"="something", "description"="something"]
To perform request i'm using this method :
private void saveNote(final int id, final String name, final String des, final String assing) {
Log.d(TAG, "Saving");
StringRequest stringRequest = new StringRequest(Request.Method.POST, Api.URL_CREATE_NOTE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response.toString());
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> postParams = new HashMap<>();
Map<String, String> tableData= new HashMap<>();
tableDataParam.put("name",name);
tableDataParam.put("description",des);
postParams.put("Array[]", tableDataParam.toString());
return params;
}
};
VolleySingletonNotes.getInstance(context).addToRequestQueue(stringRequest);
}
First issue is that i can pass only String in postParams HashMap, so when i do tableData.toString the tableData have string brackets like this:
"Array":["{name=something, desciption=something}"]
And the second issue is that tableData HashMap for some reason dont put his String parameters in string brackets as you can see in example below first issue.
I already tried make JsonArray that fix the second issue but the first issue still remains, plus it automatically create backslashes(they dont show when i type them here)
Can anyone help me with this issue? Thanks.

JSON Nested Parsing

could anyone help me set up parsing for this JSON data file.
I want to get each train departure. The structure is departures -> all - > 0,1,2,3 etc... Thanks
I am trying to get certain strings such as time, destination and platform and then display it in a list for each departure.
private void jsonParse()
{
String url = key;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REST", response.toString());
try {
JSONArray jsonArray= response.getJSONArray("departures");
Log.d("REST", jsonArray.toString());
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject departure = jsonArray.getJSONObject(i);
JSONObject all = departure.getJSONObject("all");
String Mode = all.getString("Mode");
TextViewResult.append(Mode + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Queue.add(request);
}
If I have understood correctly, you are getting no results, right?
The JSON objects (0, 1, ...) are children of "all", which is a JSONArray, not a JSONObject. And "departures" seems to be a JSONObject and not a JSONArray. You should:
Get "departures" as a JSONObject out of the loop.
Get "all" as a JSONArray from teh previous one, as it is a child of "departures", and do this also out of the loop.
Iterate over the previous JSONArray in the loop, obtaining the JSONObject's which represent one departure each.
So, the block inside the try would look like this:
//logging omitted
JSONObject departuresJSONObj = response.getJSONObject("departures");
JSONArray allJSONArr = departuresJSONObj.getJSONArray("all");
JSONObject departureJSONObj;
String mode;
for (Object departureObj : allJSONArr) {
if (departureObj instanceof JSONObject) {
departureJSONObj = (JSONObject) departureObj;
mode = departureJSONObj.getString("mode"); //mode is lowercase in the JSON
TextViewResult.append(mode + "\n");
}
}
Hope this helps.

How to return response value in Volley function?

Question1: How to get response value in onResponse function.
Question2: I create cauHoiArrayList. when I check and get cauHoiArrayList values in onResponse function => it worked. But if I check and get cauHoiArrayList values in GETDATA function ==> it did not work. How to I get cauHoiArrayList values.
Thanks you,
This is my code details:
public void GetCauHoi(String url) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
cauHoiArrayList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
_id = object.getInt("_ID");
cauhoi = object.getString("CauHoi");
tenmh = object.getString("TenMH");
tenmonhoc = object.getString("TenMonHoc");
dapan_a = object.getString("DapAn_A");
dapan_b = object.getString("DapAn_B");
dapan_c = object.getString("DapAn_C");
dapan_d = object.getString("DapAn_D");
dapandung = object.getString("DapAnDung");
hinhanh = object.getString("HinhAnh");
dokho = object.getInt("DoKho");
cauHoiArrayList.add(new CauHoi(_id, cauhoi, tenmh, tenmonhoc, dapan_a, dapan_b, dapan_c, dapan_d, dapandung, hinhanh, dokho));
}
Log.d("tag",""+cauHoiArrayList.get(0).getCauHoi());
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ScreenSlideActivity.this, ""+error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("laytenmonhocc", "" + laytenmonhoc);
params.put("laydokhoc", "" + laydokho);
return params;
}
};
requestQueue.add(stringRequest);
}
public ArrayList<CauHoi> GETDATA (){
return cauHoiArrayList;
}
Volley requests are asynchronous. You must be calling GETDATA by time when response is not arrived yet. You need to sure call GETGATA when you have response. Only OnResponse method is guarantee that response is present.

How to POST parameters using JSONArrayRequest in Volley - (ERROR string cannot be converted to jsonarray)

This question may look like a duplicate(it is NOT), but I am stuck with this JSONException error:
Value die of type java.lang.String cannot be converted to JSONArray.
I'm using JsonArrayRequest of Volley to get jsonarray from a server. My JsonArrayRequest is throwing the above error, as i want to post a string to the server and receive jsonarray as a response. Below is my code:
JsonArrayRequest jsonReq = new JsonArrayRequest(Request.Method.POST,
URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject JO = response.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setName(JO.getString("name"));
getterSetter.setNumber(JO.getString("number"));
getterSetter.setDate(JO.getString("date"));
myList.add(getterSetter);
} catch (JSONException e) {
e.printStackTrace();
}
}
myAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("myKey", myValue);
return params;
}
};
MySingleton.getInstance().addToRequestQueue(jsonReq);
}
The PHP file is working properly and it is passing json string to android.
The error is happening somewhere within onResponse block. The same block works clean when using StringRequest instead of JsonArrayRequest.
Any idea what exactly is causing this error? Any help or guidance is much appreciated.
* I'm new in Android Volley and the way it works.
EDIT
This is a format/syntax of the url response:
[
{"name":"test",
"number":"123",
"date":"2017-08-22"
},
{"name":"test1",
"number":"1234",
"date":"2017-08-23"
}
]
Try using StringRequest and then create your own JSONArray from the response string:
new JSONArray(response);
You can find example StringRequest from the documentation:
Sending a Simple Request

Returned object from another class method

I feel like this is a very basic concept missunderstanding. In my Android app I make HTTP requests using Volley lib. At first I made the requests through a JsonObjectRequest in the Activity code and worked right, but now I separated the request code in a class apart so I can call it from any Activity. The new class has a method that returns the requested JSONObject but any "json action" I do over the returned object ends in an error.
Here is the new class code, JSONRequests:
public class JSONRequests {
private JSONObject mResponse;
private String mURL = "https://myurl.com/";
public JSONObject getJSONObject(final String credentials, final String path) {
final JsonObjectRequest mRequest = new JsonObjectRequest(mURL.concat(path), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResponse = response;
try {
Log.d("RESPONSE", mResponse.getString("id")); // It works here
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Basic " + credentials);
return headers;
}
};
MyApplication.getInstance().getRequestQueue().add(mRequest);
return mResponse;
}
}
And here is how I call getJSONObject from MyActivity:
JSONRequests mRequest = new JSONRequests();
JSONObject mInfo = mRequest.getJSONObject(mEncodedCredentials, mPath);
try {
Log.d("RESPONSE", mInfo.getString("id")); // This doesn't work
} catch (JSONException e) {
e.printStackTrace();
}
When in the Activity file, I used "response" as a JSONObject and it worked, but now separated it won't. I don't know if is a error with JSONObject or just that I'm not getting the returned object in the correct way. Thanks in advance.

Categories

Resources