如何使用JSON Parsing解析来自给定URL的数据

时间:2015-09-18 05:05:01

标签: android

我成功地从URL解析了数据,但是我无法解析内部数组中的数据。

我应该怎样做才能使用JSON解析从数组内部的数组中解析数据?

以下是我的代码:

public class MainActivity extends Activity {

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://docs.blackberry.com/sampledata.json";

private static final String TAG_vehicleType = "vehicalType";
private static final String TAG_vehicleColor = "vehicleColor";
private static final String TAG_Fuel = "fuel";
private static final String TAG_Name = "name";
private static final String TAG_ExperiencePoints = "experiencePoints";
private static final String TAG_TREADTYPE = "treadType";
// Hashmap for ListView
ArrayList<Vehical> contactList;
String name, exp;

ListView list;

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

    contactList = new ArrayList<Vehical>();

     list = (ListView) findViewById(R.id.listView1);

    // Calling async task to get json
    new GetContacts().execute();
}

private class GetContacts 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) {
        ServiceHandler sh = new ServiceHandler();

        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

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

        if (jsonStr != null) {

            try {
                JSONArray contacts = new JSONArray(jsonStr);
                Log.d("contacts: ", "> " + contacts);
                Log.d("contacts size: ", "> " + contacts.length() + "");
                for (int j = 0; j < contacts.length(); j++) {

                    JSONObject c = contacts.getJSONObject(j);

                    String fuel = c.getString(TAG_Fuel);
                    String vehicleType = c.getString("vehicleType");
                    String vehicleColor = c.getString("vehicleColor");
                    String treadType = c.getString("treadType");
                    JSONArray approvedarray = c
                            .getJSONArray("approvedOperators");
                    ArrayList<ApprovedOperators> op = new ArrayList<ApprovedOperators>();

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

                        JSONObject d = approvedarray.getJSONObject(i);
                        String name = d.getString(TAG_Name);
                        int exp = d.getInt(TAG_ExperiencePoints);
                        op.add(new ApprovedOperators(name, exp));
                        // exp = c1.getString(TAG_exp);
                    }
                    Vehical contact = new Vehical(vehicleType,
                            vehicleColor, fuel, treadType, op);

                    contactList.add(contact);
                }

            } 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);
        if (pDialog.isShowing())
            pDialog.dismiss();
        list.setAdapter(new CustomAdapter(MainActivity.this, contactList));
    }

}}

这是我的CustomAdapter课程:

public class CustomAdapter extends BaseAdapter{
Activity context;
ArrayList<Vehical>arrayList;
LayoutInflater inflater;

public CustomAdapter(Context context ,ArrayList<Vehical>Arraylist){
    this.context = (Activity)context;
    this.arrayList = Arraylist;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return arrayList.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return arrayList.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = context.getLayoutInflater();
    convertView = inflater.inflate(R.layout.list_item, parent,false);
    TextView Type =(TextView)convertView.findViewById(R.id.type);
    TextView color =(TextView)convertView.findViewById(R.id.color);
    TextView fuel =(TextView)convertView.findViewById(R.id.fuel);
    TextView treadType =(TextView)convertView.findViewById(R.id.textviewname);

    Type.setText(arrayList.get(position).getVehicleType());
    color.setText(arrayList.get(position).getVehicleColor());
    fuel.setText(arrayList.get(position).getFuel());
    treadType.setText(arrayList.get(position).getTreadType());

    // TODO Auto-generated method stub
    return convertView;
}
}

1 个答案:

答案 0 :(得分:0)

制作服务处理程序类,而不是使用以下代码

公共类MainActivity扩展了Activity {

// new url
// String url = "http://demo.mysamplecode.com/Servlets_JSP/CountryJSONData";
private ProgressDialog pDialog;

// URL to get JSON Contacts
private static String url = "http://docs.blackberry.com/sampledata.json";

// JSON Node names

private static final String TAG_CONTACTS = "approvedOperators";
private static final String TAG_VEICHLETYPE = "vehicleType";
private static final String TAG_VEHICLECOLOR = "vehicleColor";
private static final String TAG_FUEL = "fuel";

 String name;
String experiencePoints;
CustomAdapter Adapter;
Context context;
ListView listview;
 TextView textView;
// Contacts JSONArray
JSONArray Contacts = null;
JSONArray approvedOperators = null;
ArrayList<VehicleItem> vehicleDetailList;
ArrayList<OperaterItems> operatorDataList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    vehicleDetailList = new ArrayList<VehicleItem>();
    operatorDataList = new ArrayList<OperaterItems>();
    context = this;
    listview = (ListView) findViewById(R.id.listview);
    //textView = (TextView)findViewById(R.id.textView);







    // Calling async task to get Json
    new GetContacts().execute();

    /*listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
    public void onItemClick(AdapterView<?> ADAPTER, View view, int position,
            long id) {
            // TODO Auto-generated method stub
            String NAME = null, EXPERIENCE = null ;
            ArrayList<OperaterItems> secondList = vehicleDetailList.get(position).getOperatorDataList();
            for(int i = 0; i < secondList.size(); i++){
                OperaterItems items = new OperaterItems();
                NAME += secondList.get(i).getName();
                EXPERIENCE += secondList.get(i).getExperiencePoints();
                name="";
                name+= "Name:"+NAME+"\n"; 
                name+="Experience: "+EXPERIENCE+"\n";
                textView.setText(name);
            }

            Toast.makeText(context, 
                    "NAME ON CLICKED POSITION..."+position+"\n"+NAME+"\n EXPERIENCE"+"\n"+EXPERIENCE,
                    Toast.LENGTH_LONG).show();
        }
    });*/

}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    protected void onPreExecute() {
        super.onPreExecute();
        // Showing Progress Dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please Wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected Void doInBackground(Void... arg0) {
        // Creating ServiceHandeler Class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonstr = sh.makeServiceCall(url, ServiceHandler.GET);
        Log.d("Responce:", ">" + jsonstr);

        if (jsonstr != null) {
            // vehicleDetailList = new ArrayList<VehicleItem>();
            // ArrayList<OperaterItems> operatorDataList;
            try {
                JSONArray Contacts = new JSONArray(jsonstr);

                // looping through all contacts
                for (int i = 0; i < Contacts.length(); i++) {

                    JSONObject c = Contacts.getJSONObject(i);

                    VehicleItem vehiclesItem = new VehicleItem();

                    vehiclesItem.setVehicleType(c.getString("vehicleType"));
                    vehiclesItem.setVehicleColor(c
                            .getString("vehicleColor"));
                    vehiclesItem.setFuel(c.getString("fuel"));
                    vehiclesItem.setTreadType(c.getString("treadType"));

                    Log.d("FIRST DATA........", "vehicleType" + "\n"
                            + "vehicleColor" + "\n" + "fuel" + "\n"
                            + "treadType");

                    JSONArray approvedOperators = c
                            .getJSONArray("approvedOperators");
                    ArrayList<OperaterItems> operatorDataList = new ArrayList<OperaterItems>();

                    for (int j = 0; j < approvedOperators.length(); j++) {

                        JSONObject b = approvedOperators.getJSONObject(j);
                        OperaterItems operatersItem = new OperaterItems();

                        operatersItem.setName(b.getString("name"));
                        operatersItem.setExperiencePoints(b
                                .getString("experiencePoints"));
                        Log.d("dg......", "opName" + "\n" + "opexp");

                        operatorDataList.add(operatersItem);
                        // vehiclesItem.setOperatorDataList(operatorDataList);

                        // String opName = b.getString("name");
                        // String opexp = b.getString("experiencePoints");
                        // hashmap.put(i, opName);
                        // Log.d(i+"",opName+"");

                    }

                    vehiclesItem.setOperatorDataList(operatorDataList);

                    vehicleDetailList.add(vehiclesItem);

                }

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

        } else {
            Log.e("ServiceHandler", "Coludn't get any data from url");
        }

        return null;

    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress Dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

        CustomAdapter apdapter = new CustomAdapter(context,
                vehicleDetailList);
        listview.setAdapter(apdapter);

        // vehicleDetailList.get(0).getOperatorDataList().get(0).getName();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

公共类CustomAdapter扩展了BaseAdapter {

Activity context;
ArrayList<OperaterItems> operatorDataList;
ArrayList<VehicleItem>vhlist;
LayoutInflater inflater;

/*public CustomAdapter(ArrayList<OperaterItems>oplist,Context context){
    this.context1 = (Activity)context1;
    this. operatorDataList = oplist;
}*/

public CustomAdapter(Context context,ArrayList<VehicleItem>vlist){
    this.context = (Activity)context;
    this.vhlist = vlist;
}


@Override
public int getCount() {
    // TODO Auto-generated method stub
    return  vhlist.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return  vhlist.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub


    LayoutInflater inflater = context.getLayoutInflater();
    convertView = inflater.inflate(R.layout.list_item, parent,false);

    LinearLayout linearLayout = (LinearLayout)convertView.findViewById(R.id.customLinearLayout);
    TextView vehicleType = (TextView)convertView.findViewById(R.id.vehicleType);
    TextView vehiclecolor = (TextView)convertView.findViewById(R.id.vehicleColor);
    TextView fuel = (TextView)convertView.findViewById(R.id.fuel);
    TextView treadType = (TextView)convertView.findViewById(R.id.treadType);
    TextView objname = (TextView)convertView.findViewById(R.id.name);
    TextView exp = (TextView)convertView.findViewById(R.id.exp);

    //VehicleItem veItem = new VehicleItem();
    vehicleType.setText(vhlist.get(position).getVehicleType());
    vehiclecolor.setText(vhlist.get(position).getVehicleColor());
    fuel.setText(vhlist.get(position).getFuel());
    treadType.setText(vhlist.get(position).getTreadType());
    //objname.setText(vhlist.get(position).g)

//OperaterItems items = new OperaterItems();
    ArrayList<OperaterItems> opList = vhlist.get(position).getOperatorDataList();
    for(int i = 0; i < opList.size(); i++){

        TextView tv = new TextView(context);
        tv.setText(opList.get(i).getName());
        tv.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
        TextView tv2 = new TextView(context);
        tv2.setText(opList.get(i).getExperiencePoints());
        tv2.setTextColor(context.getResources().getColor(android.R.color.holo_purple));
        linearLayout.addView(tv);
        linearLayout.addView(tv2);
        //vhlist.aa
    }

// objname.setText(vhlist.get(position).getOperatorDataList()。get); // exp.setText(operatorDataList.get(position).getExperiencePoints());

    return convertView;
}

}

public class OperaterItems {

private String name, experiencePoints;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getExperiencePoints() {
    return experiencePoints;
}

public void setExperiencePoints(String experiencePoints) {
    this.experiencePoints = experiencePoints;
}

}

public class VehicleItem {

private String vehicleType, vehicleColor, fuel, treadType;
private ArrayList<OperaterItems> operatorDataList;

public ArrayList<OperaterItems> getOperatorDataList() {
    return operatorDataList;
}

public void setOperatorDataList(ArrayList<OperaterItems> operatorDataList) {
    this.operatorDataList = operatorDataList;
}

public String getVehicleType() {
    return vehicleType;
}

public void setVehicleType(String vehicleType) {
    this.vehicleType = vehicleType;
}

public String getVehicleColor() {
    return vehicleColor;
}

public void setVehicleColor(String vehicleColor) {
    this.vehicleColor = vehicleColor;
}

public String getFuel() {
    return fuel;
}

public void setFuel(String fuel) {
    this.fuel = fuel;
}

public String getTreadType() {
    return treadType;
}

public void setTreadType(String treadType) {
    this.treadType = treadType;
}

}