Index 0 out of range [0...0] - android

I am getting this in my Json method.
I am trying to get information from my server and mysql database and then display it in my username text view.
This is my Json Method. It throws the index out of range error.
private void showJSON(String response) {
String username = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Constantss.JSON_ARRAY);
JSONObject profileData = result.getJSONObject(0);
username = profileData.getString(Constantss.USERNAME);
System.out.println("first" + username);
} catch (JSONException e) {
e.printStackTrace();
}
usernameView.setText(username);
System.out.println("second" + username);
}
Probably not needed but this is how I am getting my data, It works fine I am able to retrieve the Id and also run the php code to give me the username.
private void getData() {
class lata extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), //Context
"us-east--------------", //Identity Pool ID
Regions.US_EAST_1 // Region
//Now we retrieve
);
// return null;
String identityID = credentialsProvider.getIdentityId();
Log.d("LogTag", "my ID is" + identityID);
String id = identityID;
String userid = identityID;
System.out.println("Id is" + identityID);
System.out.println("Id tis" + id);
String url = Constantss.PROFILE_URL + identityID;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Profile.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(Profile.this);
requestQueue.add(stringRequest);
return identityID;
}
}
lata pasta = new lata();
pasta.execute();
}

Probably the length of your array is 0. Please check it.

You can try verifying the response var in
private void showJSON(String response) {
Is not empty

Use Gson to decode the json will be much more convenient than the way you did , and obviously the JSONArray result's length is 0

Related

Adding volley response to global variables

I have using volley library for fetching data. I used a HashMap to store response data. When I fetch the data out of the volley request it is showing empty. I knew I should use this Hashmap inside the response method. But I need to get that in a global variable. Any suggestions?
String liveURL = BASE_URL + "livescores?api_token=" + API_KEY;
HashMap<String, String> hashMap = new HashMap<>();
JsonObjectRequest livescoresRequest = new JsonObjectRequest(Request.Method.GET,
liveURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
final JSONArray liveArray = response.getJSONArray("data");
for (int i = 0; i < liveArray.length(); i++) {
JSONObject data = liveArray.getJSONObject(i);
String liveID = data.getString("id");
final String league_id = data.getString("league_id");
hashMap.put(league_id, liveID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
}
});
Volley.newRequestQueue(getContext()).add(livescoresRequest);
Log.i("HASHMAP", hashMap.toString());

Volley onResponse method not triggered

I am trying to parse a JSON file and fetch certain info from every person in the JSON file. I have created a parseJSON() function to do this for me, but I have run into a problem. The application works but it does not receive the information from the JSON file. After placing a breakpoint in the function, I realised that the application does not even acess the onResponse() function.
I have read the answers of some similar questions like this, but they did not seem to be of help.
What seems to be the cause of this?
parseJson() function:
private void parseJson() {
JsonArrayRequest request = new JsonArrayRequest(jsonUrl, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
JSONObject nameObject = jsonObject.getJSONObject("name");
String title = nameObject.getString("title");
String firstName = nameObject.getString("first");
String lastName = nameObject.getString("last");
String email = jsonObject.getString("emial");
JSONObject prictureObject = jsonObject.getJSONObject("picture");
String imageUrl = prictureObject.getString("medium");
String fullName = title + " " + firstName + " " + lastName;
Log.e("FULL NAME", fullName);
// Ignore this part
/*Book jsonBook = new Book(imageUrl, fullName, email, 50.0, 100, 3);
Books.add(jsonBook);*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(HomeActivity.this);
}
}
link to my json file: https://api.myjson.com/bins/ldql7
You are doing a JsonArrayRequest when it needs to be a JsonObjectRequest. The body of your JSON file is contained within a Json Object:
{
"results": [...]
}
Once you have changed the request type, modify your parseJson method like so:
private void parseJson() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, "https://api.myjson.com/bins/ldql7", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
try {
JSONArray array = response.getJSONArray("results");
JSONObject jsonObject = null;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
JSONObject nameObject = jsonObject.getJSONObject("name");
String title = nameObject.getString("title");
String firstName = nameObject.getString("first");
String lastName = nameObject.getString("last");
String email = jsonObject.getString("email");
JSONObject prictureObject = jsonObject.getJSONObject("picture");
String imageUrl = prictureObject.getString("medium");
String fullName = title + " " + firstName + " " + lastName;
Log.e("FULL NAME", fullName);
// Ignore this part
/*Book jsonBook = new Book(imageUrl, fullName, email, 50.0, 100, 3);
Books.add(jsonBook);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}

Value of parameter does not change when returned from volley request

I have two volley requests values returned from second request goes to first request where the values are used to make the recycle view . to return the value i made the parameter as field, but its value does not change from 0 which was default .
My first volley request:
private void callplcaedetails(String id) {
RequestQueue queue = Volley.newRequestQueue(this);
System.out.println("id" + id);
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + id + "&key=AIzaSyDi9vrZ0F3TX***********Q";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
// Log.i("Response is: ", response);
JSONObject m = null;
try {
m = new JSONObject(response);
reader1 = m.getJSONObject("result");
String nameofplace = reader1.getString("name");
JSONObject geometry = reader1.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
String lat = location.getString("lat");
String lng = location.getString("lng");
Log.i("lat" + lat, "lng" + lng);
Addressname = reader1.getString("formatted_address");
float x1=getdistance(lat,lng);
Log.i("disatancccccccc",x1+"");
placelist.add(new Place(nameofplace, Addressname, x1));
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Not worked", "That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
My second volley request:
private Float getdistance(String lat, String lng) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins="+latitude+","+longitude+"&destinations="+lat+","+lng+"&key=AIzaSyDi9vrZ0F3T******Y3GlQ";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.i("Response is: ", response);
JSONObject m = null;
try {
m = new JSONObject(response);
JSONArray reader1 = m.getJSONArray("rows");
JSONObject e = reader1.getJSONObject(0);
JSONArray f = e.getJSONArray("elements");
JSONObject g =f.getJSONObject(0);
JSONObject h= g.getJSONObject("distance");
String dist = h.getString("value");
x = Float.parseFloat(dist);
Log.i("distance",x+"");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Not worked", "That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
System.out.println("Distance Value"+x);
return x;
}
The log response
I/disatancccccccc: 0.0
I/lat22.9575252: lng76.04197789999999
I/System.out: dkkvnjnvfnvjnvdfjvndfvjn0.0
I/disatancccccccc: 0.0
I/ResponseĀ is:: "Response works right"
I/distance: 3595.0
distance comes right, What is wrong in this , and which is better way to do it.
Note: i made the parameter as final, but its value does not change from 0 which was default. Mention in your question dear when declare a variable final that means you cant change its values after declaring it as a final you can understand from its name final.
Solution:
You have to declare variable as class level and and dont make it final and assign your value to it and then use it.
public class AboutUsActivity extends Activity {
int x=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
//your response callback value
void XYZResponce(int result){
x = result;
}
}

How to Get String from JSON Array [duplicate]

This question already has answers here:
JSON Array of strings (no objects), extracting data
(4 answers)
Closed 6 years ago.
its actually a simple code, cuz of lack of basic I still cant manage to handle this.
After I made a Post JSON Method on my own Api, I get the following response
[{"id":"2"}]
What I'm trying to achieve is that I would like to get the value of this "id" which is "2".
I've tried the following code in my private void method
private void getUserID() {
StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String idUser = jsonObject.optString("id").toString();
}
output.setText(idUser);
} catch (JSONException e) {e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put(Constants.KEY_A, username);
map.put(Constants.KEY_B, password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I get it from here.
It's a bit of waste, because I only have one list object in my array, and I thinks for loop is not really important in here.
replace your try block with following
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String idUser = jsonObject.getString("id");
Log.e("id is: ", idUser);
}
Try this way you will get
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( delprourl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
// Parsing json
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println("person" + person);
//get your id here
String id = person.getString("id");
Log.e("id: ", id);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
// 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("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}

How to convert String to JSONObject?

I have an obstacle by changing the data string into a jsonobject, is his org.json.JSONException script error: Value
This coding I am trying
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = inputUser.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (username.trim().length() > 0 && password.trim().length() > 0) {
Map<String,String> params = new HashMap<>();
params.put("username", inputUser.getText().toString());
params.put("password", inputPassword.getText().toString());
sendPostRequest(params);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Silahkan Masukan Username dan Password!", Toast.LENGTH_LONG)
.show();
}
}
});
public void sendPostRequest(Map<String, String> params) {
showDialog();
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.chris-chris.webege.com/login.php";
mCustomRequest = new CustomRequest(Request.Method.POST,
url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Intent intent = new Intent(Login.this,
Coba.class);
startActivity(intent);
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
hidepDialog();
Toast.makeText(Login.this, "Belum Terhubung Internet! ", Toast.LENGTH_SHORT).show();
}
});
mCustomRequest.setRetryPolicy(new DefaultRetryPolicy(Template.VolleyRetryPolicy.SOCKET_TIMEOUT,
Template.VolleyRetryPolicy.RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(mCustomRequest);
}
There are two conditions to convert a string to JSONObject :
1 . The string should be in proper Json format .
2 . Put code in try catch block .
Example:
String jsonString = "{"status":"1","message":"Login successfully","data":{"uid":"1","email":"baleshwar#gmail.com","password":"202cb962ac59075b964b07152d234b70","name":"","role":"1","gender":"","address":"","image":"","is_active":"0","last_login":"0000-00-00 00:00:00","device_id":"0","created_at":"2015-06-03 06:01:02","updated_at":"2015-06-03 11:01:02","location":"","dob":"0000-00-00","descriptions":""}}"
Now convert this string to JSONObject
try{
JSONObject jsonResponse = new JSONObject(result);
}catch(Exception e){
e.printStackTrace();
}
Try this,
If you call your service and try to paste that code inside your isSucsess part
JSONObject jObject = jsonObject.getJSONObject("jsonobjectname");
tvTitle.setText(jObject.getString("your string name"));

Categories

Resources