Android value of arraylist out of method - android

I have this code created with Volley and JSON:
public List<String> result = new ArrayList<String>();
public List<String> mostraDati(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, DatiNet.MostraDati, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
System.out.println("fin qui ci siamo");
JSONArray utenti = response.getJSONArray("utenti");
List<String> resTemp = new ArrayList<String>();
for (int i = 0; i < utenti.length(); i++) {
JSONObject student = utenti.getJSONObject(i);
String nome = student.getString("nome");
String cognome = student.getString("cognome");
String numero = student.getString("numero");
String email = student.getString("email");
resTemp.add(nome + " " + cognome + " " + email);
}
result = resTemp;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
System.out.println(result.toString());
return result;
}
It works well but the return is always null "[]". How to solve the problem?
I think the problem is to port the value out of the method of jsonObjectRequest.

You have to change your code to add one arrayList value to another arrayList.
Change
result = resTemp;
to
result.addAll(resTemp);

Related

How parse JSON data into ListView

I would like to visualize the Json data on a listview, but I don't know how to do it ... I tried to use a TextView to verify the correct passage of the data and it seems to work, but I would need to display them on the listView ... ideas?
{"Esito":true,"Dati":[{"id":"357","id_utente":"16","nome_prodotto":"cozze"},{"id":"358","id_utente":"16","nome_prodotto":"riso"},{"id":"362","id_utente":"16","nome_prodotto":"patate"},{"id":"366","id_utente":"16","nome_prodotto":"cozze"},{"id":"367","id_utente":"16","nome_prodotto":null}]}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.G[enter image description here][1]ET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
String id = dato.getString("id");
String id_utente = dato.getString("id_utente");
String nome_prodotto = dato.getString("nome_prodotto");
mTextViewResult.append(id + ", " + id_utente + ", " + nome_prodotto + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Just make new object class and collect data to list :
class YourObiekt {
private String id;
private String idUtente;
private String nomeProdotto;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdUtente() {
return idUtente;
}
public void setIdUtente(String idUtente) {
this.idUtente = idUtente;
}
public String getNomeProdotto() {
return nomeProdotto;
}
public void setNomeProdotto(String nomeProdotto) {
this.nomeProdotto = nomeProdotto;
}
}
List<YourObiekt> yourObiektList = new ArrayList<YourObiekt>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
YourObiekt yo = new YourObiekt();
yo.setId(dato.getString("id"));
yo.setIdUtente(dato.getString("id_utente"));
yo.setNomeProdotto(dato.getString("nome_prodotto"));
yourObiektList.add(yo);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And now you get yourObiektList as data for your listView

How to parse multiple Json values in Android?

I tried doing it multiple times using Volley library.
Link for JSON values: here
My android code to parse the values: here
public class GetUSGSjson extends AppCompatActivity
{
GridView jsonGridView;
ListView jsonListView;
Button jsonGetBtn;
RequestQueue USGSrequestqueue;
String USGSurl = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10";
ArrayList<String> mArrayList;
ArrayList<String>FK;
JsonObjectRequest USGSjsonObjectReq;
JSONObject _properties_;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.json_data);
jsonGridView = (GridView) findViewById(R.id.jsonGridView);
jsonGetBtn = (Button) findViewById(R.id.jsonGetBtn);
USGSrequestqueue = Volley.newRequestQueue(this);
mArrayList = new ArrayList<>();
FK = new ArrayList<>();
jsonGridView.setVisibility(View.GONE);
}
OnCllick of the button
public void USGSgetData(View view)
{
jsonGridView.setVisibility(View.VISIBLE);
USGSjsonObjectReq = new JsonObjectRequest(Request.Method.GET,USGSurl,null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try {
JSONObject _features_ = response.getJSONObject("features");
JSONArray _f_ = response.getJSONArray("features");
for (int x = 0; x < _f_.length(); x++)
{
JSONObject currentFeature = _f_.getJSONObject(x);
_properties_ = currentFeature.getJSONObject("properties"); //JsonObject
double mag = _properties_.getDouble("mag");
long time = _properties_.getLong("time");
String place = _properties_.getString("place");
mArrayList.add(String.valueOf(mag));
mArrayList.add(String.valueOf(time));
mArrayList.add(place);
ArrayAdapter VarrayAdapter = new ArrayAdapter<>(GetUSGSjson.this
,android.R.layout.simple_list_item_1, mArrayList);
jsonGridView.setAdapter(VarrayAdapter);
} catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(GetUSGSjson.this, "Exception: "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(GetUSGSjson.this, "onErrorResponse: "+error.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
USGSrequestqueue.add(USGSjsonObjectReq);
}
}
Try this,
try {
JSONArray arr_features=response.getJSONArray("features");
for(int i=0;i<arr_features.length();i++)
{
JSONObject obj=arr_features.getJSONObject(i);
String type=obj.getString("type");
JSONObject obj_properties=obj.getJSONObject("properties");
String mag=obj_properties.getString("mag");
String place=obj_properties.getString("place");
String time=obj_properties.getString("time");
String updated=obj_properties.getString("updated");
}
} catch (JSONException e) {
e.printStackTrace();
}
I found this way to solve my own problem
Remember that the "mag" is in double form "place" & "type" are in String form & "time" is a Unix time it's in long form.
try {
JSONArray _f_ = response.getJSONArray("features");
for (int x = 0; x < _f_.length(); x++)
{
JSONObject currentFeature = _f_.getJSONObject(x);
_properties_ = currentFeature.getJSONObject("properties"); //JsonObject
double mag = _properties_.getDouble("mag");
long time = _properties_.getLong("time");
String place = _properties_.getString("place");
String type = _properties_.getString("type");
// To add this on to ArrayList.
mArrayList.add("Place: "+place+"\n");
mArrayList.add("\nMagnitude: " + String.valueOf(mag)+"\n");
mArrayList.add("\nTime: " + String.valueOf(newTime)+"\n");
mArrayList.add("\nType: " + type+"\n");
}

My app crashes when there is no value in my JSON

I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})

Android - Wait for Volley response to complete and continue executing

I need execute a Volley request and wait for the response to parse it and return it, but have no idea on how to achieve this.
Can someone help?
here is my code :
public void getWord(){
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject lesMots = response.getJSONObject("lesMots");
Iterator<?> keys = lesMots.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (lesMots.get(key) instanceof JSONObject) {
JSONObject obj = (JSONObject) lesMots.get(key);
//Récupération des deux mots, anglais et français
String wordToFind = obj.getString("wordFrench").toUpperCase();
String wordEnglish = obj.getString("wordEnglish").toUpperCase();
//Mots mis dans un array respectif
listOfWordEnglish.add(wordEnglish);
listOfWordFrench.add(wordToFind);
container.removeAllViews();
}
numberOfWord++;
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error + "", Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
There is 7 word in each array but when i'm trying to get acess into my initGame function, it said they are empty, i guess it's because volley request is not this fast !
if someone can explain me how to do that
here is my initGame function
`public void initGame() {
win = false;
found = 0;
typed_word.setText("");
image.setBackgroundResource(R.drawable.first);
listOfLetters = new ArrayList<>();
listOfWordFrench = new ArrayList<>();
listOfWordEnglish = new ArrayList<>();
getWord();
for (int i = 0; i < listOfWordEnglish.size(); i++){
System.out.println(i);
String wordEnglish = listOfWordEnglish.get(i);
wordEnglishPendu.setText(wordEnglish);
word = listOfWordFrench.get(i);
for (int x = 0; x < word.length(); x++) {
TextView oneLetter = (TextView) getLayoutInflater().inflate(R.layout.textview, null);
container.addView(oneLetter);
}
}
}`
Since Volley is asynchronous, so the for loop below getWord() will be called before onResponse of your Volley request.
The solution for your issue is to move that for loop into onResponse, there you can place it after the while loop.
Hope it helps!

Volley Object request Returning 0

I Have a Remote Database that contains 6 rows.
Here's my code, I put it in List so that i can get the size,
But it's always returning 0.
public List<Comments> getComments() {
final List<Comments> commentsData = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
return commentsData;
}
I need the size for some use.
Why is it always returning zero?
I even tried adding a counter++ inside for loop.
But when i get the value of the counter its still zero.
JsonObjectRequest run on a background thread. That's why you getting the list size 0. you must work into the public void onResponse(JSONObject response) {} function .
Exmp.
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
// **you may call function and pass the list value to update your ui component. you will get the real size of list here.**
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories

Resources