0

我有以下代码检索 JSON 文件:

public class GetJSON extends AsyncTask<Void, Void, Void> {
     @Override
     protected Void doInBackground(Void... params) { //Running in background
         try {
             httpclient = new DefaultHttpClient(new BasicHttpParams());
             HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
             // Depends on your web service
             httppost.setHeader("Content-type", "application/json");
            HttpResponse response = httpclient.execute(httppost);           
            HttpEntity entity = response.getEntity();

            inputStream = entity.getContent();
            // json is UTF-8 by default
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            result = sb.toString();

        } catch (Exception e) {
            Log.i("TEST", e.toString());
            // Oops
        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }
        return null;
     }

     @Override
     protected  void onPreExecute() { //Activity is on progress
     }

     @Override
     protected void onPostExecute(Void v) { //Activity is done...
         Toast.makeText(getActivity(), result, 2000).show();
         int k = 0;
         try {
             JSONArray jsonall = new JSONArray();
            jsonArray = new JSONArray(result);
            for(int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object
                if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value
                    k++;
                    jsonall.put(jsonObj);
                    sId = new String[jsonall.length()];
                    sType = new String[jsonall.length()];
                    sData = new String[jsonall.length()];
                    for (int m = 0 ; m < jsonall.length(); m++){ //4 entries made
                        JSONObject c = jsonall.getJSONObject(m);

                        String id = c.getString("id");
                        String type = c.getString("type");
                        String data = c.getString("data");

                        sId[m] = id;
                        sType[m] = type;
                        sData[m] = data;
                    }
                }
            }
            Toast.makeText(getActivity(), String.valueOf(k), 2000).show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
     }
}

在该onPostExecute()功能上,我能够反序列化数据,在本例中为TYPE.

我有以下代码CustomAdapter

public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> {
    Context context;
   int layoutResourceId;
   ArrayList<SetRows> data=new ArrayList<SetRows>();
   public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) {
       super(context, layoutResourceId, data);
       this.layoutResourceId = layoutResourceId;
       this.context = context;
       this.data = data;
   }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
       View row = convertView;
       ImageHolder holder = null;

       if(row == null)
       {
           LayoutInflater inflater = ((Activity)context).getLayoutInflater();
           row = inflater.inflate(layoutResourceId, parent, false);

           holder = new ImageHolder();
           holder.tID = (TextView)row.findViewById(R.id.tvID);
           holder.tType = (TextView)row.findViewById(R.id.tvType);
           holder.tData = (TextView)row.findViewById(R.id.tvData);
           row.setTag(holder);
       }
       else
       {
           holder = (ImageHolder)row.getTag();
       }

       SetRows myImage = data.get(position);
       holder.tID.setText(myImage.id);
       holder.tType.setText(myImage.type);
       holder.tData.setText(myImage.data);
      return row;

   }

   static class ImageHolder
   {
       TextView tID;
       TextView tType;
       TextView tData;
   }
}

我的SetRows代码是:

public class SetRows {

    String id;
    String type;
    String data;

    public String getData () {
        return data;
    }

    public void setData (String data) {
        this.data = data;
    }

    public String getID () {
        return id;
    }

    public void setID (String id) {
        this.id = id;
    }
    public String getType () {
        return type;
    }

    public void setType (String type) {
        this.type = type;
    }

    public SetRows(String id, String type, String data) {
        super();
        this.id = "ID: \t" + id;
        this.type = "TYPE: \t" + type;
        this.data = "DATA: \t" + data;
    }
}

我的布局文件的 XML 文件是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <ListView android:id="@+id/lvAll"
        android:layout_height="match_parent"
        android:layout_width="match_parent" />
</RelativeLayout>

ListView 的自定义布局是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="@dimen/list_row_pad"
    android:background="@drawable/list_row_bg" >

    <TextView
        android:id="@+id/tvID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="@dimen/margin_left_tv"
        android:text="ID: "
        android:textStyle="bold"
        android:textColor="#FFFFFF" />
    <TextView
        android:id="@+id/tvType"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvID"
        android:layout_alignLeft="@+id/tvID"
        android:text="TYPE: "
        android:textStyle="bold"
        android:textColor="#FFFFFF" />
    <TextView
        android:id="@+id/tvData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvType"
        android:layout_alignLeft="@+id/tvType"
        android:text="DATA: "
        android:textStyle="bold"
        android:textColor="#FFFFFF" />
</RelativeLayout>

我想在ListView我的服务器的 JSON 文件中显示这样的数据:

在此处输入图像描述

我想我有所有需要的信息。我现在只需要知道如何显示信息。非常感谢所有帮助。谢谢!

更新:以下代码正在运行,但它为每个输入多个条目

public class GetJSON extends AsyncTask<Void, Void, Void> {
         @Override
         protected Void doInBackground(Void... params) { //Running in background
             try {
                 httpclient = new DefaultHttpClient(new BasicHttpParams());
                 HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
                 // Depends on your web service
                 httppost.setHeader("Content-type", "application/json");
                HttpResponse response = httpclient.execute(httppost);           
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();

            } catch (Exception e) {
                Log.i("TEST", e.toString());
                // Oops
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return null;
         }

         @Override
         protected  void onPreExecute() { //Activity is on progress
         }

         @Override
         protected void onPostExecute(Void v) { //Activity is done...
             //Toast.makeText(getActivity(), result, 2000).show();
             int k = 0;
             try {
                 JSONArray jsonall = new JSONArray();
                jsonArray = new JSONArray(result);
                for(int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object
                    if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value
                        k++;
                        jsonall.put(jsonObj);
                        sId = new String[jsonall.length()];
                        sType = new String[jsonall.length()];
                        sData = new String[jsonall.length()];
                        for (int m = 0 ; m < jsonall.length(); m++){
                            JSONObject c = jsonall.getJSONObject(m);

                            String id = c.getString("id");
                            String type = c.getString("type");
                            String data = c.getString("data");

                            //sId[m] = id;
                            //sType[m] = type;
                            //sData[m] = data;
                            contents.add(new SetRows(id, type, data));
                        }
                    }
                    adapter = new SetRowsCustomAdapter(getActivity(), R.layout.listrow, contents);
                    lAll.setAdapter(adapter);
                    lAll.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
                            Intent myIntent = new Intent(getActivity(), DisplayWeb.class);
                            startActivityForResult(myIntent, 0);
                        }
                    });
                }
                //Toast.makeText(getActivity(), String.valueOf(k), 2000).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
         }
    }

副本显示如下:

在此处输入图像描述

4

1 回答 1

2
  1. SublacssListActivy并创建一个包含 ID 为 ListView 的布局@android:id/list
  2. 把你的 AsyncTask 放在这个子类中,并在 on create 中执行它。
  3. onPostExecute被调用时,在你解析之后JSON,创建一个实例SetRowsCustomAdapter
  4. 打电话getListView().setAdapter(adapterInstance)

     @Override
     protected void onPostExecute(Void v) {
         ArrayList<SetRows> contents = new ArrayList<SetRows>();
          // other code
    
           //instead of those
           //sId[m] = id;
           //sType[m] = type;
           //sData[m] = data;
            //add 
           contents.add(new SetRows(id, type, data));
     }
    

    编辑 2:您有两个重复条目,因为您有一个无用的 for 循环(内部循环)。海事组织您的代码应如下所示:

          for(int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObj = (JSONObject)jsonArray.get(i);  
                if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) {  
    
                        String id =   jsonObj.getString("id");
                        String type = jsonObj.getString("type");
                        String data = jsonObj.getString("data");
    
                        contents.add(new SetRows(id, type, data));
                    }
                }
                // the other stuff
    

附言。检查错字

于 2013-11-11T15:24:43.973 回答