Poeja Network Poeja Network - 8 months ago 74
PHP Question

jsonobject cannot be converted to jsonarray android studio

i want to show images that already i upload to my database SQL using JSON

i already make this code for my android and my server side

getImages.php

<?php

//Importing dbdetails file
require_once 'dbDetails.php';

//connection to database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');

//sql query to fetch all images
$sql = "SELECT * FROM images";

//getting images
$result = mysqli_query($con,$sql);

//response array
$response = array();
$response['error'] = false;
$response['images'] = array();

//traversing through all the rows
while($row = mysqli_fetch_array($result)){
$temp = array();
$temp['id']=$row['id'];
$temp['name']=$row['name'];
$temp['url']=$row['url'];
array_push($response['images'],$temp);
}
//displaying the response
echo json_encode($response);


and then for android code, i make MainActivity class

public class MainActivity extends AppCompatActivity {

//Web api url
public static final String DATA_URL = "http://10.0.2.2/phpcode/getImages.php";

//Tag values to read from json
public static final String TAG_IMAGE_URL = "image";
public static final String TAG_NAME = "name";

//GridView Object
private GridView gridView;

//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private ArrayList<String> names;

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

gridView = (GridView) findViewById(R.id.gridView);

images = new ArrayList<>();
names = new ArrayList<>();

//Calling the getData method
getData();
}

private void getData(){
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...","Fetching data...",false,false);

//Creating a json array request to get the json from our api
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Dismissing the progressdialog on response
loading.dismiss();

//Displaying our grid
showGrid(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage() + ".", Toast.LENGTH_LONG).show();
}
}
);

//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding our request to the queue
requestQueue.add(jsonArrayRequest);
}


private void showGrid(JSONArray jsonArray){
//Looping through all the elements of json array
for(int i = 0; i<jsonArray.length(); i++){
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = jsonArray.getJSONObject(i);

//getting image url and title from json object
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Creating GridViewAdapter Object
GridViewAdapter gridViewAdapter = new GridViewAdapter(this,images,names);

//Adding adapter to gridview
gridView.setAdapter(gridViewAdapter);
}

}


but the result is error JSONObject cannot be converted to JSONarray?

please help me to fix the code
i need this code in my work, and i'm to confuse to understand the code

===============================
here my gridView class

public class GridViewAdapter extends BaseAdapter {

//Imageloader to load images
private ImageLoader imageLoader;

//Context
private Context context;

//Array List that would contain the urls and the titles for the images
private ArrayList<String> images;
private ArrayList<String> names;

public GridViewAdapter (Context context, ArrayList<String> images, ArrayList<String> names){
//Getting all the values
this.context = context;
this.images = images;
this.names = names;
}

@Override
public int getCount() {
return images.size();
}

@Override
public Object getItem(int position) {
return images.get(position);
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
//Creating a linear layout
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);

//NetworkImageView
NetworkImageView networkImageView = new NetworkImageView(context);

//Initializing ImageLoader
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(images.get(position), ImageLoader.getImageListener(networkImageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));

//Setting the image url to load
networkImageView.setImageUrl(images.get(position),imageLoader);

//Creating a textview to show the title
TextView textView = new TextView(context);
textView.setText(names.get(position));

//Scaling the imageview
networkImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
networkImageView.setLayoutParams(new GridView.LayoutParams(200,200));

//Adding views to the layout
linearLayout.addView(textView);
linearLayout.addView(networkImageView);

//Returnint the layout
return linearLayout;
}
}


================================================
android monitor



10-03 12:20:41.285 24381-24381/? I/art: Not late-enabling -Xcheck:jni (already on) 10-03 12:20:41.285 24381-24381/? W/art: Unexpected CPU variant for X86 using defaults: x86 10-03 12:20:41.461
24381-24388/? I/art: Debugger is no longer active 10-03 12:20:41.461
24381-24388/? I/art: Starting a blocking GC Instrumentation 10-03
12:20:41.543 24381-24381/? W/System: ClassLoader referenced unknown
path: /data/app/net.simplifiedcoding.androidcustomgridview-1/lib/x86
10-03 12:20:41.560 24381-24381/? I/InstantRun: starting instant run
server: is main process 10-03 12:20:41.935 24381-24410/?
D/NetworkSecurityConfig: No Network Security Config specified, using
platform default


[ 10-03 12:20:41.965 24381:24405 D/ ]
HostConnection::get() New Host Connection established 0x9dfa0b80, tid


24405

[ 10-03 12:20:41.966 24381:24405 W/ ]
Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1


ANDROID_EMU_dma_v1 10-03 12:20:41.983 24381-24405/? I/OpenGLRenderer:
Initialized EGL, version 1.4 10-03 12:20:41.983 24381-24405/?
D/OpenGLRenderer: Swap behavior 1 10-03 12:20:41.984 24381-24405/?
W/OpenGLRenderer: Failed to choose config with
EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... 10-03 12:20:41.984
24381-24405/? D/OpenGLRenderer: Swap behavior 0 10-03 12:20:41.993
24381-24405/? D/EGL_emulation: eglCreateContext: 0x9dffc920: maj 2 min
0 rcv 2 10-03 12:20:42.040 24381-24405/? D/EGL_emulation:
eglMakeCurrent: 0x9dffc920: ver 2 0 (tinfo 0x9df9f670) 10-03
12:20:42.403 24381-24405/? D/EGL_emulation: eglMakeCurrent:
0x9dffc920: ver 2 0 (tinfo 0x9df9f670) 10-03 12:20:42.670
24381-24405/net.simplifiedcoding.androidcustomgridview
D/EGL_emulation: eglMakeCurrent: 0x9dffc920: ver 2 0 (tinfo
0x9df9f670) 10-03 12:20:42.825
24381-24381/net.simplifiedcoding.androidcustomgridview W/art: Before
Android 4.1, method int
android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int,
boolean) would have incorrectly overridden the package-private method
in android.widget.ListView 10-03 12:20:42.864
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:
org.json.JSONException: No value for image 10-03 12:20:42.865
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at org.json.JSONObject.get(JSONObject.java:389) 10-03 12:20:42.865
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at org.json.JSONObject.getString(JSONObject.java:550) 10-03
12:20:42.865 24381-24381/net.simplifiedcoding.androidcustomgridview
W/System.err: at
net.simplifiedcoding.androidcustomgridview.MainActivity.showGrid(MainActivity.java:96)
10-03 12:20:42.865
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at
net.simplifiedcoding.androidcustomgridview.MainActivity.access$000(MainActivity.java:22)
10-03 12:20:42.865
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at
net.simplifiedcoding.androidcustomgridview.MainActivity$1.onResponse(MainActivity.java:66)
10-03 12:20:42.882
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at
net.simplifiedcoding.androidcustomgridview.MainActivity$1.onResponse(MainActivity.java:58)
10-03 12:20:42.882
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at
com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
10-03 12:20:42.882
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at
com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
10-03 12:20:42.882
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at android.os.Handler.handleCallback(Handler.java:751) 10-03
12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview
W/System.err: at
android.os.Handler.dispatchMessage(Handler.java:95) 10-03 12:20:42.882
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at android.os.Looper.loop(Looper.java:154) 10-03 12:20:42.882
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at android.app.ActivityThread.main(ActivityThread.java:6077) 10-03
12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-03 12:20:42.882
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
10-03 12:20:42.882
24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

Answer Source

Change your getData to accept JSONObject. You are passing Jsonobject from your server

 private void getData(){
    //Showing a progress dialog while our app fetches the data from url
    final ProgressDialog loading = ProgressDialog.show(this, "Please wait...","Fetching data...",false,false);

    //Creating a json array request to get the json from our api
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET,DATA_URL,null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    //Dismissing the progressdialog on response
                    loading.dismiss();
                    try{
                    //Displaying our grid
                    showGrid(response.getJSONArray("images");
                    }catch(Exception e){}
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loading.dismiss();
                    Toast.makeText(getApplicationContext(), error.getMessage() + ".", Toast.LENGTH_LONG).show();
                }
            }
    );

    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    //Adding our request to the queue
    requestQueue.add(jsonObjectRequest);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download