list view使用intent将数据解析到另一个活动

时间:2014-01-10 07:32:53

标签: android json android-intent android-activity

我现在有一个listview我需要将listview数据传递给另一个活动我该怎么做?

MainActivity

    package learn2crack.listview;

    import java.util.ArrayList;
    import java.util.HashMap;

    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.AdapterView;
    import android.widget.Button;
    import java.util.List;
    import android.view.Menu;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    import android.widget.Toast;



    import learn2crack.listview.library.JSONParser;



    public class MainActivity extends Activity {
        ListView list;
        TextView ver;
        TextView name;
        TextView api;
        Button Btngetdata;
        ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();


        private static String url = "http://216.185.116.35/LOGISTIC/WebServices/json/getDeliveriItems_bak.ashx?id=485";

        private static final String TAG_OS = "android";
        private static final String TAG_VER = "BagNumber";
        private static final String TAG_NAME = "COD";
        private static final String TAG_API = "OrderNo";

        JSONArray android = null;




        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);
            oslist = new ArrayList<HashMap<String, String>>();



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

                 ver = (TextView)findViewById(R.id.vers);
                 name = (TextView)findViewById(R.id.name);
                 api = (TextView)findViewById(R.id.api);
                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();


                JSONObject json = jParser.getJSONFromUrl(url);
                return json;
            }
             @Override
             protected void onPostExecute(JSONObject json) {
                 pDialog.dismiss();
                 try {

                        android = json.getJSONArray(TAG_OS);
                        for(int i = 0; i < android.length(); i++){
                        JSONObject c = android.getJSONObject(i);


                        String ver = c.getString(TAG_VER);
                        String name = c.getString(TAG_NAME);
                        String api = c.getString(TAG_API);







                        HashMap<String, String> map = new HashMap<String, String>();

                        map.put(TAG_VER, ver);
                        map.put(TAG_NAME, name);
                        map.put(TAG_API, api);

                        oslist.add(map);
                        list=(ListView)findViewById(R.id.list);
                    listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
                                        R.id.vers,R.id.name, R.id.api});

                        list.setAdapter(adapter);


                        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {


                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();




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



             }
            }
            }

JSONParser.java

package learn2crack.listview.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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 = "";


    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {


        try {

            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);
            }
            is.close();
            json = sb.toString();
            json = "{ \"android\":"+json+"}";
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }


        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }


        return jObj;

    }
    }

我已经找到了一些如何传递数据的解释,但我遇到了新的AdapterView.OnItemClickListener()

的问题

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

问题是

oslist.get(+position)    

应该是

oslist.get(position)

你也有

 private static final String TAG_NAME = "COD"; // key for name is COD
 map.put(TAG_NAME, name);

然后

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent,  View view, int position, long id) {
 String name = oslist.get(position).get("COD");
 Intent intent = new Intent(ActivityName.this, YOURACTIVITY.class);
 intent.putExtra("key", name);
 startActivity(intent);

}
});

应将setAdapter coe移出for循环

也改为

@Override
protected void onPostExecute(JSONObject json) {
    super.onPostExecute(json); 
    pDialog.dismiss();
    try {

           android = json.getJSONArray(TAG_OS);
           for(int i = 0; i < android.length(); i++){
           JSONObject c = android.getJSONObject(i);
           String ver = c.getString(TAG_VER);
           String name = c.getString(TAG_NAME);
           String api = c.getString(TAG_API);
           HashMap<String, String> map = new HashMap<String, String>();
           map.put(TAG_VER, ver);
           map.put(TAG_NAME, name);
           map.put(TAG_API, api);

           oslist.add(map);
           }
           } catch (JSONException e) {
               e.printStackTrace();
           }
           list=(ListView)findViewById(R.id.list);
           listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
                           R.id.vers,R.id.name, R.id.api});
           list.setAdapter(adapter)
           list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
           String name = oslist.get(position).get("COD");
           String ver = oslist.get(position).get(TAG_VER);
           String api = oslist.get(position).get(TAG_API);
           Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
           intent.putExtra("key", name);
           intent.putExtra("key1", ver);
           intent.putExtra("key2", api);
           startActivity(intent);

           }
           });
}

在另一个活动中

String name =getIntent().getStringExtra("key");
String api =getIntent().getStringExtra("key1");
String ver =getIntent().getStringExtra("key"2);

答案 2 :(得分:0)

您应该创建自定义适配器。还要创建一个DataModel,它将包含所有3个值(Version,Name和Api)。使其可序列化。

public class MyModel implements Serializable{

    private static final long serialVersionUID = 1L;
    String version, name, api;
    public MyModel(String modelVer, String modelName, String modelApi){
        version = modelVer;
        name = modelName ;
        api = modelApi;
    }

    //Add Getters and Setters
}

而不是创建HashMap<String, String> map = new HashMap<String, String>();创建

ArrayList<MyModel> modelList = new ArrayList<MyModel>();

然后在OnItemClickListener()

//To send data
MyModel modelToPass = modelList.get(position);
intent.putExtra("MyObject", modelToPass);

//To get data
getIntent().getSerializableExtra("MyObject");