jsonobject无法转换为jsonarray android studio

时间:2017-10-03 01:29:24

标签: php android json

我想显示已经使用JSON上传到我的数据库SQL的图像

我已经为我的Android和我的服务器端制作了这段代码

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);

然后对于Android代码,我制作MainActivity类

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);
    }

}

但结果是错误JSONObject无法转换为JSONarray?

请帮我修复代码 我在工作中需要这个代码,而且我很难理解代码

=============================== 这里是我的gridView类

    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监视器

  
    

10-03 12:20:41.285 24381-24381 /?我/艺术:不迟到-Xcheck:jni(已经开启)10-03 12:20:41.285 24381-24381 /? W / art:使用默认值的X86的意外CPU变体:x86 10-03 12:20:41.461     24381-24388 /?我/艺术:调试器不再有效10-03 12:20:41.461     24381-24388 /?我/艺术:开始阻止GC仪器10-03     12:20:41.543 24381-24381 /? W / System:ClassLoader引用未知     路径:/data/app/net.simplifiedcoding.androidcustomgridview-1/lib/x86     10-03 12:20:41.560 24381-24381 /? I / InstantRun:开始即时运行     服务器:主流程10-03 12:20:41.935 24381-24410 /?     D / NetworkSecurityConfig:未使用指定的Network Security Config     平台默认

  
                                                      [ 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:   初始化的EGL,版本1.4 10-03 12:20:41.983 24381-24405 /?   D / OpenGLRenderer:交换行为1 10-03 12:20:41.984 24381-24405 /?   W / OpenGLRenderer:无法选择配置   EGL_SWAP_BEHAVIOR_PRESERVED,重试没有... 10-03 12:20:41.984   24381-24405 /? D / OpenGLRenderer:交换行为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:之前   Android 4.1,方法int   android.support.v7.widget.ListViewCompat.lookForSelectablePosition(INT,   boolean)会错误地重写package-private方法   在android.widget.ListView 10-03 12:20:42.864中   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:   org.json.JSONException:图片10-03 12:20:42.865没有值   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在org.json.JSONObject.get(JSONObject.java:389)10-03 12:20:42.865   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在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:
  在   net.simplifiedcoding.androidcustomgridview.MainActivity.access $ 000(MainActivity.java:22)   10-03 12:20:42.865   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在   net.simplifiedcoding.androidcustomgridview.MainActivity $ 1.onResponse(MainActivity.java:66)   10-03 12:20:42.882   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在   net.simplifiedcoding.androidcustomgridview.MainActivity $ 1.onResponse(MainActivity.java:58)   10-03 12:20:42.882   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在   com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)   10-03 12:20:42.882   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在   com.android.volley.ExecutorDelivery $ ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)   10-03 12:20:42.882   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在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:
  在android.os.Looper.loop(Looper.java:154)10-03 12:20:42.882   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在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:
  在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:866)   10-03 12:20:42.882   24381-24381 / net.simplifiedcoding.androidcustomgridview W / System.err:
  在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

2 个答案:

答案 0 :(得分:0)

您没有从PHP返回JSON数组。直接回显json_encode($temp)而不将其推入数组或使用JSONObjectRequest代替JSONArrayRequest并相应地解析它。

答案 1 :(得分:0)

更改getData以接受JSONObject。您正在从服务器传递Jsonobject

 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);
}