list view parsing data to another activity using i

2019-06-07 07:33发布

I have a listview now i need to pass the listview data to a another activity how do i do it ?

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;

    }
    }

I have found some explanation how to pass data but I am having problem at new AdapterView.OnItemClickListener()

3条回答
女痞
2楼-- · 2019-06-07 08:02

for example you can pass the position of item that is clicked by below code

public void onListItemClick(ListView parent, View v, int position, 
        long id){

    Intent intent = new Intent(getApplicationContext(), YourActivity.class);
    intent.putExtra("pos", position);
    startActivity(intent);

    }

in YourActivity oncreate() method

Intent current=getIntent();
int position=current.getExtras().getInt("pos");

for sending your data you can make class below

public class Information implements Serializable {

public String BagNumber;
public String COD;
public String OrderNo;
public String SubOrderNo;
    ......
    ......
}

and for send it

Information details = new Information ();
details.BagNumber = "";
details.COD = "12";
details.OrderNo = "ff";
....
....

Intent i = new Intent(getApplicationContext(), YourActivity.class);
i.putExtra("inf", details);
startActivity(i);

For receive it

Information model = (Information ) getIntent().getSerializableExtra("inf");
查看更多
Ridiculous、
3楼-- · 2019-06-07 08:04

The problem is

oslist.get(+position)    

should be

oslist.get(position)

Also you have

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

then

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

}
});

Should move setAdapter coe out of for loop

Also change to

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

           }
           });
}

In Another Activtiy

String name =getIntent().getStringExtra("key");
String api =getIntent().getStringExtra("key1");
String ver =getIntent().getStringExtra("key"2);
查看更多
别忘想泡老子
4楼-- · 2019-06-07 08:12

You should create a custom adapter. Also create a DataModel which will hold all the 3 values (Version, Name and Api). Make it Serializable.

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
}

Instead of creating HashMap<String, String> map = new HashMap<String, String>(); Create

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

then in OnItemClickListener()

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

//To get data
getIntent().getSerializableExtra("MyObject");
查看更多
登录 后发表回答