无法使用asynctask从json检索2D数组到android

时间:2016-01-08 11:15:20

标签: php android json android-asynctask 2d

Json文件输出:

  {
  "result": [
  {
        "Owner_ID": "1",
        "Owner_Name": "King",
        "Owner_IC": "997788-01-9267",
        "Owner_Contact": "012-34567890",
        "Owner_AccNum" : "124914848238902",
        "Car": {
            "Car_ID": "1",
            "Car_Name": "Aston Martin",
            "Car_Plate": "P 1"
            "Car_Color": "Red",
            "Car_Hour": "6",
            "Car_Day": "150",
        },
        {
            "Car_ID": "2",
            "Car_Name": "Sonata",
            "Car_Plate": "S 1234"
            "Car_Color": "Red",
            "Car_Hour": "10",
            "Car_Day": "200",
        }
},
{
        "Owner_ID": "2",
        "Owner_Name": "Dragon",
        "Owner_IC": "962738-98-8345",
        "Owner_Contact": "019-86427613",
        "Owner_AccNum" : "124914848238902",
        "Car": {
            "Car_ID": "3",
            "Car_Name": "Lambo",
            "Car_Plate": "L 104"
            "Car_Color": "Blue",
            "Car_Hour": "9",
            "Car_Day": "180",
        }

这是我的代码,如何在android中获取json数据:

package com.example.ryuuji.fstep;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toolbar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends ListActivity
     {
     //DECLARE BUTTON
     UserLocalStore userLocalStore;
     OwnerLocalStore ownerLocalStore;
     CarLocalStore carLocalStore;

    private ProgressDialog pDialog;

    /////////OWNER////////////////////////
    // URL to get contacts JSON
    private static String url = "phpfile";

    // JSON Node names
    private static final String TAG_ID = "Owner_ID";
    private static final String TAG_NAME = "Owner_Name";
    private static final String TAG_IC = "Owner_IC";
    private static final String TAG_CONTACT = "Owner_Contact";
    private static final String TAG_ACCNUM = "Owner_AccNum";
    private static final String TAG_PASSWORD = "Owner_Password";
    private static final String TAG = "result";

    // contacts JSONArray
    JSONArray owners = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> ownerList;

    /////////CAR///////////////////////////

    // JSON Node names
    private static final String TAGCAR_ID = "Car_ID";
    private static final String TAGCAR_NAME = "Car_Name";
    private static final String TAGCAR_PLATE = "Car_Plate";
    private static final String TAGCAR_COLOR = "Car_Color";
    private static final String TAGCAR_HOUR = "Car_Hour";
    private static final String TAGCAR_DAY = "Car_Day";
    private static final String CARTAG = "car";

    // contacts JSONArray
    JSONArray cars = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> carList;

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

        //CALL OTHER CLASS
        userLocalStore = new UserLocalStore(this);
        ownerLocalStore = new OwnerLocalStore(this);
        carLocalStore = new CarLocalStore(this);

        ownerList = new ArrayList<HashMap<String, String>>();
        carList = new ArrayList<HashMap<String, String>>();

        ListView list = getListView();

        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setActionBar(toolbar);

        // Listview on item click listener
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        ////////CONTINUE CAR
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting values from selected ListItem
                String ids = ((TextView) view.findViewById(R.id.ownerid))
                .getText().toString();
                String ownername = ((TextView) view.findViewById(R.id.ownername))
                        .getText().toString();
                String owneric = ((TextView) view.findViewById(R.id.owneric))
                .getText().toString();
                String ownercontact = ((TextView) view.findViewById(R.id.ownercontact))
                        .getText().toString();
                String owneraccnum = ((TextView) view.findViewById(R.id.owneraccnum))
                .getText().toString();
                String password = ((TextView)     view.findViewById(R.id.ownerpassword))
                .getText().toString();
                String ownercar = ((TextView) view.findViewById(R.id.ownercar))
                        .getText().toString();

                // Starting single contact activity
                Intent in = new Intent(getApplicationContext(),
                        Subcontent.class);
                in.putExtra(TAG_NAME, ownername);
                in.putExtra(TAG_ACCNUM, owneraccnum);
                in.putExtra(TAG_CONTACT, ownercontact);
                in.putExtra(TAG_IC, owneric);
                in.putExtra(TAGCAR_NAME, ownercar);
                startActivity(in);
            }
        });
        // Calling async task to get json
        new GetOwners().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        if(userLocalStore.getUserLoggedIn() == true)
            getMenuInflater().inflate(R.menu.secmenu_main, menu);
        else if(ownerLocalStore.getOwnerLoggedIn() == true)
            getMenuInflater().inflate(R.menu.ownmenu_main, menu);
        else
            getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();

        switch (id)
        {
            case R.id.action_login:
                startActivity(new Intent(this,Login.class));
                break;
            case R.id.action_editprofile:
                startActivity(new Intent(this,Profile.class));
                break;
            case R.id.action_setting:
                startActivity(new Intent(this,Setting.class));
                break;
            case R.id.action_about:
                startActivity(new Intent(this,About.class));
                break;
            case R.id.action_logout:
                userLocalStore.clearUserData();
                userLocalStore.setUserLoggedIn(false);

                startActivity(new Intent(this, MainActivity.class));
                break;
            case R.id.action_editprofileowner:
                startActivity(new Intent(this,OwnerProfile.class));
                break;
            case R.id.action_logoutowner:
                ownerLocalStore.clearOwnerData();
                ownerLocalStore.setOwnerLoggedIn(false);

                carLocalStore.clearCarData();
                carLocalStore.setCarLoggedIn(false);

                startActivity(new Intent(this, MainActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //START PROCESS

    InputStream urls = null;
    String result = null;

    //Owner
    /**
     * Async task class to get json by making HTTP call
     * */
    public class GetOwners extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    // Getting JSON Array node
                    owners = jsonObj.getJSONArray(TAG);

                    // looping through All Contacts
                    for (int i = 0; i < owners.length(); i++) {
                        JSONObject c = owners.getJSONObject(i);

                        String ids = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String ic = c.getString(TAG_IC);
                        String contact = c.getString(TAG_CONTACT);
                        String accnum = c.getString(TAG_ACCNUM);
                        String password = c.getString(TAG_PASSWORD);

                        cars = jsonObj.getJSONArray(CARTAG);
                        for (int j = 0; j < cars.length(); j++) {
                            // Phone node is JSON Object
                            JSONObject car = cars.getJSONObject(j);
                            String carid = car.getString(TAGCAR_ID);
                            String carname = car.getString(TAGCAR_NAME);
                            String carplate = car.getString(TAGCAR_PLATE);
                            String carcolor = car.getString(TAGCAR_COLOR);
                            String carhour = car.getString(TAGCAR_HOUR);
                            String carday = car.getString(TAGCAR_DAY);

                            // tmp hashmap for single contact
                            HashMap<String, String> owner = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            owner.put(TAG_ID, ids);
                            owner.put(TAG_NAME, name);
                            owner.put(TAG_IC, ic);
                            owner.put(TAG_CONTACT, contact);
                            owner.put(TAG_ACCNUM, accnum);
                            owner.put(TAG_PASSWORD, password);

                            owner.put(TAGCAR_ID, carid);
                            owner.put(TAGCAR_NAME, carname);
                            owner.put(TAGCAR_PLATE, carplate);
                            owner.put(TAGCAR_COLOR, carcolor);
                            owner.put(TAGCAR_HOUR, carhour);
                            owner.put(TAGCAR_DAY, carday);

                            // adding contact to contact list
                            ownerList.add(owner);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, ownerList,
                    R.layout.ownerlist_main, new String[]{TAG_NAME, TAG_IC,
                    TAG_CONTACT, TAG_ACCNUM}, new int[]{R.id.ownername, R.id.owneric,
                    R.id.ownercontact, R.id.owneraccnum});

            ListAdapter adapterCar = new SimpleAdapter(
                    MainActivity.this, ownerList,
                    R.layout.ownercar_main, new String[]{TAGCAR_NAME}, new int[]{R.id.ownercar});


            setListAdapter(adapter);
            setListAdapter(adapterCar);
        }

    }

    //CAR
    //Owner
    /**
     * Async task class to get json by making HTTP call
     * */
    public class GetCars extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    // Getting JSON Array node
                    owners = jsonObj.getJSONArray(TAG);
                    //cars = jsonObj.getJSONArray(CARTAG);

                    // looping through All Contacts
                    for (int i = 0; i < owners.length(); i++) {
                        JSONObject c = owners.getJSONObject(i);

                        String ids = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String ic = c.getString(TAG_IC);
                        String contact = c.getString(TAG_CONTACT);
                        String accnum = c.getString(TAG_ACCNUM);
                        String password = c.getString(TAG_PASSWORD);

                        cars = c.getJSONArray(CARTAG);
                        for (int j = 0; j < cars.length(); j++) {
                            // Phone node is JSON Object
                            JSONObject car = cars.getJSONObject(j);
                            String carid = car.getString(TAGCAR_ID);
                            String carname = car.getString(TAGCAR_NAME);
                            String carplate = car.getString(TAGCAR_PLATE);
                            String carcolor = car.getString(TAGCAR_COLOR);
                            String carhour = car.getString(TAGCAR_HOUR);
                            String carday = car.getString(TAGCAR_DAY);



                        /*String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String email = c.getString(TAG_EMAIL);
                        String address = c.getString(TAG_ADDRESS);
                        String gender = c.getString(TAG_GENDER);

                        // Phone node is JSON Object
                        JSONObject phone = c.getJSONObject(TAG_PHONE);
                        String mobile = phone.getString(TAG_PHONE_MOBILE);
                        String home = phone.getString(TAG_PHONE_HOME);
                        String office = phone.getString(TAG_PHONE_OFFICE);*/

                            // tmp hashmap for single contact
                            HashMap<String, String> owner = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            owner.put(TAG_ID, ids);
                            owner.put(TAG_NAME, name);
                            owner.put(TAG_IC, ic);
                            owner.put(TAG_CONTACT, contact);
                            owner.put(TAG_ACCNUM, accnum);
                            owner.put(TAG_PASSWORD, password);

                            owner.put(TAGCAR_ID, carid);
                            owner.put(TAGCAR_NAME, carname);
                            owner.put(TAGCAR_PLATE, carplate);
                            owner.put(TAGCAR_COLOR, carcolor);
                            owner.put(TAGCAR_HOUR, carhour);
                            owner.put(TAGCAR_DAY, carday);

                            // adding contact to contact list
                            ownerList.add(owner);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, ownerList,
                    R.layout.ownerlist_main, new String[]{TAG_NAME, TAG_IC,
                    TAG_CONTACT, TAG_ACCNUM}, new int[]{R.id.ownername, R.id.owneric,
                    R.id.ownercontact, R.id.owneraccnum});

            ListAdapter adapterCar = new SimpleAdapter(
                    MainActivity.this, ownerList,
                    R.layout.ownercar_main, new String[]{TAGCAR_NAME}, new int[]{R.id.ownercar});


            setListAdapter(adapter);
            setListAdapter(adapterCar);
        }

    }
}

这是我的ListView

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="75dp" />

<requestFocus />

这是我的ownerlist.xml

<!-- Name Label -->

<!-- Mobile number label -->
<TextView
    android:id="@+id/ownername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:text="Name :"
    android:textColor="#5d5d5d"
    android:textStyle="bold"
    android:layout_alignBaseline="@+id/ownercontact"
    android:layout_alignBottom="@+id/ownercontact"
    android:layout_toRightOf="@+id/imageButton"
    android:layout_toEndOf="@+id/imageButton" />

<TextView
    android:id="@+id/ownercontact"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:text="Contact : "
    android:textColor="#5d5d5d"
    android:textStyle="bold"
    android:layout_alignBaseline="@+id/owneraccnum"
    android:layout_alignBottom="@+id/owneraccnum"
    android:layout_toRightOf="@+id/imageButton"
    android:layout_toEndOf="@+id/imageButton" />

<TextView
    android:id="@+id/owneraccnum"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:text="Account Number : "
    android:textColor="#5d5d5d"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignLeft="@+id/ownername"
    android:layout_alignStart="@+id/ownername" />

<TextView
    android:id="@+id/owneric"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:gravity="left"
    android:text="IC :"
    android:textColor="#5d5d5d"
    android:textStyle="bold"
    android:layout_alignBaseline="@+id/ownercontact"
    android:layout_alignBottom="@+id/ownercontact"
    android:layout_toRightOf="@+id/imageButton"
    android:layout_toEndOf="@+id/imageButton" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Car : "
    android:id="@+id/ownercar" />

<TextView
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:text="New Text"
    android:id="@+id/ownerpassword" />

<TextView
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:text="New Text"
    android:id="@+id/ownerid" />

问题出在AsyncTask中,因为它没有获取任何数据。如果我只在1D阵列中制作它就会成功。但是当我与另一个阵列(汽车)结合时,它就不会成功。抱歉我的英语不好

2 个答案:

答案 0 :(得分:0)

区分大小写在JSON中非常重要,因此请将CARTAG更改为"Car"而不是"car"

大写&#34; C &#34;在你收到的JSON中。

应该是:

private static final String CARTAG = "Car";

答案 1 :(得分:0)

您可以将模型用于此更复杂的JSON。

JSONObject jsonObject = new JSONObject(jsonstr);
            JSONArray jsonArray=jsonObject.getJSONArray("result");
            StringBuffer finalBufferedData=new StringBuffer();

            List <model> modelList=new ArrayList<>();
            for(int i=0; i<jsonObject.length(); i++){
                JSONObject finalObject= jsonArray.getJSONObject(i);
                model movie_model= new model();
                movie_model.setMovie(finalObject.getInt("Owner_ID"));
                movie_model.setYear(finalObject.getString("Owner_Name"));
                movie_model.setRating(finalObject.getString("Owner_IC"));
                movie_model.setDirector(finalObject.getString("Owner_Contact"));
                movie_model.setDuration(finalObject.getDouble("Owner_AccNum"));
                List <model.cast> castList=new ArrayList<>();
                    model.cast cast= new model.cast();
                getJSONObject(0).getInt("Car_ID"));     
                cast.setCar_ID(jsonstr.getJSONArray("cast") //put both these in same line//
                 .getJSONObject(j).getInt("Car_ID"));
                 cast.setCar_Name(jsonstr.getJSONArray("cast")
                  .getJSONObject(0).getString("Car_Name")); 

                //do the rest similarly//
                    castList.add(cast);
                }
                movie_model.setCastList(castList);
                modelList.add(movie_model);
            }
            return modelList;

创建一个名为model

的新java类
public class model {
private String Owner_Name;
private int Owner_ID;
private String Owner_Contact;
private String Owner_IC;
private Double Own_AccNum;
private List<cast> castList;

public String getMovie() {
    return Owner_Name;
}

public void setMovie(String movie) {
    this.Owner_Name = Owner_Name;
}

public int getYear() {
    return year;
}

public void setYear(int Owner_ID) {
    this.Owner_ID = Owner_ID;
}

//SIMILARLY DO FOR OTHERS//

public List<cast> getCastList() {
    return castList;
}

public void setCastList(List<cast> castList) {
    this.castList = castList;
}

public static class cast{
    private int Car_ID;
    private String Name; 
    //SIMILARLY DECLARE OTHERS

    public int getCar_ID(int Car_ID) {
        return this.Car_ID;
    }

    public void setName(int Car_ID) {
        this.Car_ID = Car_ID;
    }

    public int getCar_Name(String Car_Name) {
        return this.Car_ID;
    }

    public void setName(String Car_Name) {
        this.Car_Name = Car_Name
    }
    //SIMILARLY DO FOR OTHERS
}