Marky B Marky B - 2 months ago 17
Java Question

JSONArray to a ListView array data not shown

data receipt of a JsonArrayRequest not displayed in my ListView , the php works perfect as 've tried it with my browser but when passing the data to my Android Studio by a JsonArrayRequest a arrayList the application does not stop but not sample data array.
I have 4 classes: MainActivity with a button that launches the request, Contact.class where getters and setters are , BackgroundTask.class where JsonArrayRequest is set , and MySingleton.class .
I've seen other responses to similar problems here but I have not managed to deploy the array. Here I leave my classes and php code.

the jsonArray to display:

[
{"delegacion":"Benito Juarez"},
{"delegacion":"Azcapotzalco"},
{"delegacion":"Coyoacan"},
{"delegacion":"Magdalena Contreras"},
{"delegacion":"Miguel Hidalgo"}
]


error:
BackgroundTask.java:47 is:
Contact contact = new Contact(jsonObject.getString("Delegacion");

BackgroundTask.java:35 is:
new Response.Listener() { ...

09-08 23:44:06.620 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: org.json.JSONException: No value for Delegacion
09-08 23:44:06.628 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at org.json.JSONObject.get(JSONObject.java:354)
09-08 23:44:06.632 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at org.json.JSONObject.getString(JSONObject.java:510)
09-08 23:44:06.636 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at com.example.compushop.jsonarraypeticion.BackgroundTask$1.onResponse(BackgroundTask.java:47)
09-08 23:44:06.640 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at com.example.compushop.jsonarraypeticion.BackgroundTask$1.onResponse(BackgroundTask.java:35)
09-08 23:44:06.640 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72)
09-08 23:44:06.640 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
09-08 23:44:06.644 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at android.os.Handler.handleCallback(Handler.java:725)
09-08 23:44:06.644 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
09-08 23:44:06.644 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at android.os.Looper.loop(Looper.java:137)
09-08 23:44:06.648 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5041)
09-08 23:44:06.648 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
09-08 23:44:06.648 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
09-08 23:44:06.648 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-08 23:44:06.648 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-08 23:44:06.648 16996-16996/com.example.compushop.jsonarraypeticion W/System.err: at dalvik.system.NativeStart.main(Native Method)


Php code:

<?php

$user_name = 'root';
$password = '';
$host = 'localhost';
$db_name = 'delegaciones';

$conexion = mysqli_connect($host, $user_name, $password, $db_name);

if(mysqli_connect_errno($conexion)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "select * from tabla_delegaciones";
$result = mysqli_query($conexion, $sql);
$response = array();

while($row = mysqli_fetch_array($result)){

array_push($response, array("Delegacion"=>$row["delegacion"]));
}

msqli_stop($conexion);

echo json_encode($response);


MainActivity.class

public class MainActivity extends AppCompatActivity {

TextView txdeleg_lista;
Button btnObtener;
ArrayList<Contact> arrayList = new ArrayList<>();
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnObtener = (Button)findViewById(R.id.btnObtener);
txdeleg_lista = (TextView) findViewById(R.id.txdeleg_lista);
listView = (ListView) findViewById(R.id.lvDelegacion);

btnObtener.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity(new Intent(MainActivity.this, DesplegarLista.class));

BackgroundTask backgroundTask = new BackgroundTask(MainActivity.this);
arrayList = backgroundTask.getList();
listView.setAdapter(new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList));

}
});
}
}


My table of my data base contains just one row = "delegaciones" and i want to put all de data of this row in may array.

Contact.class

public class Contact {

private String Delegacion;

public Contact(String Delegacion){

this.setDelegacion(Delegacion);

}
public String getDelegacion() {
return Delegacion;
}

public void setDelegacion(String delegacion) {
Delegacion = delegacion;
}
}


My BackgroundTask.class

public class BackgroundTask {

Context context;
ArrayList<Contact> arrayList = new ArrayList<>();
String json_url = "http://192.168.56.1/VolleyTutorial/JsonArrayRequest2.php";

public BackgroundTask(Context context){

this.context = context;

}

public ArrayList<Contact> getList(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
if(jsonArray == null){
Toast.makeText(context,"EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
}
else {

for (int i = 0; i < jsonArray.length(); i++) {

try {
JSONObject jsonObject = (JSONObject) jsonArray.getJSONObject(i);
Contact contact = new Contact(jsonObject.getString("delegacion"));
arrayList.add(contact);


} catch (JSONException e) {
e.printStackTrace();
}
}
}

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

Toast.makeText(context,"ERROR...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestque(jsonArrayRequest);

return arrayList;
}
}


and MySingleton.class

public class MySingleton {

private static MySingleton mInstance;
private RequestQueue requestQueue;
private static Context mCntx;

private MySingleton(Context context){

mCntx = context;
requestQueue = getRequestQueue();
}

public RequestQueue getRequestQueue(){

if(requestQueue == null){
requestQueue = Volley.newRequestQueue(mCntx.getApplicationContext());

}
return requestQueue;
}

public static synchronized MySingleton getInstance(Context context){

if(mInstance == null){

mInstance = new MySingleton(context);
}
return mInstance;
}

public<T> void addToRequestque(Request<T> request){

requestQueue.add(request);

}
}

Answer

Since you are using only one string in contact class. instead of arrayList<Contact> I will use ArrayList<String>

here I have removed singleTone class. and added jsonArrayRequest code inside in same class. and after adding item in arraylist I have called adapter.notifyDataSetChanged();

MainActivity.class

public class MainActivity extends AppCompatActivity {

    TextView txdeleg_lista;
    Button btnObtener;
    ArrayList<String> arrayList = new ArrayList<String>();
    ListView listView;
    String json_url = "your url";
    ArrayAdapter<String> adapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnObtener = (Button) findViewById(R.id.btnObtener);
    txdeleg_lista = (TextView) findViewById(R.id.txdeleg_lista);
    listView = (ListView) findViewById(R.id.lvDelegacion);

    adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);

    btnObtener.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //startActivity(new Intent(MainActivity.this, DesplegarLista.class));

            listView.setAdapter(adapter);


            request();

        }
    });
  }

  public void request() {
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray jsonArray) {
                    Log.e("jsonArray",""+jsonArray);
                    if(jsonArray == null){
                        Toast.makeText(MainActivity.this,"EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
                    }
                    else {

                        for (int i = 0; i < jsonArray.length(); i++) {

                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String contact = jsonObject.getString("UFULLNAME");
                                arrayList.add(contact);


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        adapter.notifyDataSetChanged();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Toast.makeText(MainActivity.this,"ERROR...", Toast.LENGTH_SHORT).show();
            error.printStackTrace();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
    requestQueue.add(jsonArrayRequest);
    }
}

check and if you have any query comment.

Comments