为什么我在解析json响应时会看到最后一项?

时间:2014-10-02 20:07:27

标签: java android json arrays

我正在和Json合作。我的json看起来像这个结构

this is a my json

我使用asynctask解析我的json并在listview中显示它有一个问题Info jsonarray。我也解析时间jsonobject但在arraylist中只添加了最后一个对象。这是我的源代码

private class CustomerStatistic extends AsyncTask<String, Void, String> {

    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(getActivity());

        pDialog.setCancelable(false);
        pDialog.show();
        pDialog.setContentView(R.layout.custom_progressdialog);
    }

    @Override
    protected String doInBackground(String... params) {

        return Utils.getJSONString(params[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        try {

            JSONArray mainJson = new JSONArray(result);

            for (int i = 0; i < mainJson.length(); i++) {
                JSONObject objJson = mainJson.getJSONObject(i);

                objItem = new ServerItems();

                objItem.setImage(imageurl + objJson.getString("ipone_4"));
                objItem.setTitle(objJson.getString("title"));
                objItem.setYoutube(objJson.getString("youtube"));
                objItem.setWritten(objJson.getString("written"));
                objItem.setCategory(objJson.getString("category"));
                objItem.setDescraption(objJson.getString("descraption"));
                objItem.setGeorgia_time(objJson.getString("georgia_time"));
                objItem.setWold_time(objJson.getString("wold_time"));
                objItem.setStars(objJson.getString("stars"));
                objItem.setBlurimage(imageurl
                        + objJson.getString("ipone_4_blur"));

                JSONObject cinema = objJson.getJSONObject("Cinemas");
                JSONArray cinemasarray = cinema.getJSONArray("Cinemaname");

                for (int j = 0; j < cinemasarray.length(); j++) {
                    JSONObject objJson1 = cinemasarray.getJSONObject(j);

                    JSONArray info = objJson1.getJSONArray("info");
                    for (int k = 0; k < info.length(); k++) {
                        JSONObject information = info.getJSONObject(k);



                        objItem.setTime(information.getString("time"));
                        Log.e("time is", objItem.getTime());

                    }

                }

                arrayOfList.add(objItem);

            }

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

        if (pDialog != null) {
            pDialog.dismiss();

            pDialog = null;
        }
        setAdapterToListview();

    }
}

并且在listview的点击中我替换了新的片段,我也按位置填充了我的元素。我只有一个问题'时间'jsobobject 这是我的listview的onclick java代码

main_listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            mPosition = position;

            MoviewListResult newFragment = new MoviewListResult();

            FragmentTransaction transaction = getFragmentManager()
                    .beginTransaction();

            Bundle bundle = new Bundle();

            bundle.putString("image", arrayOfList.get(position)
                    .getBlurimage());
            bundle.putString("title", arrayOfList.get(position).getTitle());
            bundle.putString("trailer", arrayOfList.get(position)
                    .getYoutube());
            bundle.putString("category", arrayOfList.get(position)
                    .getCategory());
            bundle.putString("writer", arrayOfList.get(position)
                    .getWritten());
            bundle.putString("stars", arrayOfList.get(position).getStars());
            bundle.putString("geotime", arrayOfList.get(position)
                    .getGeorgia_time());
            bundle.putString("worldtime", arrayOfList.get(position)
                    .getWold_time());
            bundle.putString("descraption", arrayOfList.get(position)
                    .getDescraption());

            bundle.putString("time", arrayOfList.get(position).getTime());

            newFragment.setArguments(bundle);
            transaction.replace(R.id.content_frame, newFragment);

            transaction.commit();

        }
    });
我在做错了什么?如果有人知道解决方案,请帮助我 P.S 我是新用户,我无法发布图片,请看我的Url.i上传了我的图片

1 个答案:

答案 0 :(得分:0)

将此作为JSONParser使用:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";
  // constructor
  public JSONParser() {
  }
  public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
      // defaultHttpClient
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      HttpResponse httpResponse = httpClient.execute(httpPost);
      HttpEntity httpEntity = httpResponse.getEntity();
      is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          is, "iso-8859-1"), 8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "n");
      }
      is.close();
      json = sb.toString();
    } catch (Exception e) {
      Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
      Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
  }
}

然后是活动和AsyncTask实现:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import learn2crack.asynctask.library.JSONParser;
public class MainActivity extends Activity {
  TextView uid;
  TextView name1;
  TextView email1;
  Button Btngetdata;
  //URL to get JSON Array
  private static String url = "http://10.0.2.2/JSON/";
  //JSON Node Names
  private static final String TAG_USER = "user";
  private static final String TAG_ID = "id";
  private static final String TAG_NAME = "name";
  private static final String TAG_EMAIL = "email";
  JSONArray user = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Btngetdata = (Button)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
             new JSONParse().execute();
      }
    });
    }
    private class JSONParse extends AsyncTask<String, String, JSONObject> {
       private ProgressDialog pDialog;
      @Override
        protected void onPreExecute() {
            super.onPreExecute();
             uid = (TextView)findViewById(R.id.uid);
       name1 = (TextView)findViewById(R.id.name);
       email1 = (TextView)findViewById(R.id.email);
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
      }
      @Override
        protected JSONObject doInBackground(String... args) {
        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        return json;
      }
       @Override
         protected void onPostExecute(JSONObject json) {
         pDialog.dismiss();
         try {
            // Getting JSON Array
            user = json.getJSONArray(TAG_USER);
            JSONObject c = user.getJSONObject(0);
            // Storing  JSON item in a Variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            //Set JSON Data in TextView
            uid.setText(id);
            name1.setText(name);
            email1.setText(email);
        } catch (JSONException e) {
          e.printStackTrace();
        }
       }
    }
}

了解详情:

http://www.learn2crack.com/2013/10/android-asynctask-json-parsing-example.html