简体   繁体   中英

Passing Android listview string values to another activity

I am having a problem on my android application , i am getting data from mysql using JSON Parsing.

When i select a listview item and pass it to another activity it takes a random value instead of the one i have selected.

Here is my code in the listview activity.

public class Outlets extends ListActivity{

// Progress Dialog
    private ProgressDialog pDialog;


    // testing on Emulator:
    private static final String READ_OUTLETS_URL = "http://10.0.2.2:8081/bfc_webservice/outlet_list.php";



    // JSON IDS:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_OUTLET_NAME = "outlet_name";
    private static final String TAG_SPARKLING_CLASSIFICATION = "sparkling_classification";
    private static final String TAG_ID = "id";
    private static final String TAG_POSTS= "posts";
    private static final String TAG_SPARKLING_CHANNEL = "sparkling_channel";



    // An array of all of our comments
    private JSONArray mOutlets = null;
    // manages all of our comments in a list.
    private ArrayList<HashMap<String, String>> mOutletsList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.outlets);



}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    // loading the comments via AsyncTask
    new LoadComments().execute();
}

/*public void addComment(View v) {
    Intent i = new Intent(ShowComments.this, PostComment.class);
    startActivity(i);
}
    */
/**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {

    // Instantiate the arraylist to contain all the JSON data.
    // we are going to use a bunch of key-value pairs, referring
    // to the json element name, and the content.

    mOutletsList = new ArrayList<HashMap<String, String>>();

    // Instantiating the json parser J parser
    JSONParser jParser = new JSONParser();
    // Feed the beast our comments url, and it spits us
    // back a JSON object. Boo-yeah Jerome.
    JSONObject json = jParser.getJSONFromUrl(READ_OUTLETS_URL);

    //Catcing Exceptions
    try {
        //Checking the amount of data rows.
        mOutlets = json.getJSONArray(TAG_POSTS);

        // looping through the database
        for (int i = 0; i < mOutlets.length(); i++) {
            JSONObject c = mOutlets.getJSONObject(i);

            // gets the content of each tag
            String outletname = c.getString(TAG_OUTLET_NAME);
            String spark_channel = c.getString(TAG_SPARKLING_CHANNEL);
            String spark_class = c.getString(TAG_SPARKLING_CLASSIFICATION);

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

            map.put(TAG_OUTLET_NAME, outletname);
            map.put(TAG_SPARKLING_CHANNEL, spark_channel);
            map.put(TAG_SPARKLING_CLASSIFICATION, spark_class);

            // adding HashList to ArrayList
            mOutletsList.add(map);

            // JSON data parsing completed by hash mappings
            // list
        }

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

/**
 * Inserts the parsed data into the listview.
 */
private void updateList() {
    // For a ListActivity we need to set the List Adapter, and in order to do
    //that, we need to create a ListAdapter.  This SimpleAdapter,
    //will utilize our updated Hashmapped ArrayList, 
    //use our single_post xml template for each item in our list,
    //and place the appropriate info from the list to the
    //correct GUI id.  Order is important here.
    ListAdapter adapter = new SimpleAdapter(this, mOutletsList,
            R.layout.single_outlet, new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL,
            TAG_SPARKLING_CLASSIFICATION }, new int[] { R.id.outlet_name, R.id.sparkling_channel,
                    R.id.sparkling_classification });

    // I shouldn't have to comment on this one:
    setListAdapter(adapter);

    // Optional: when the user clicks a list item we 
    //could do something.  However, we will choose
    //to do nothing...
    ListView lv = getListView();    
    lv.setOnItemClickListener(new OnItemClickListener() {

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

            int itemPosition = position;


            TextView outname = (TextView)findViewById(R.id.outlet_name);
            TextView channel = (TextView)findViewById(R.id.sparkling_channel);
            TextView clas = (TextView)findViewById(R.id.sparkling_classification);

            String foutname = outname.getText().toString();
            String fchannel = channel.getText().toString();
            String fclass = clas.getText().toString();


             Intent i = new Intent(Outlets.this, ScoreSheet.class);
             i.putExtra("outlt", foutname);
             i.putExtra("chnl", fchannel);
             i.putExtra("cls", fclass);
             startActivity(i);

        }
    });
}

public class LoadComments extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Outlets.this);
        pDialog.setMessage("Loading Outlets...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
        updateJSONdata();
        return null;

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        updateList();
    }
}

}

And the code for my next activity is this one.I want just to test if i am getting the correct value using TextViews.

 public class ScoreSheet extends Activity{

TextView oname, sch, scls;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.score_sheet);

    oname = (TextView)findViewById(R.id.txtoutname);
    sch = (TextView)findViewById(R.id.txtspchannel);
    scls = (TextView)findViewById(R.id.txtspclass);

    Intent myIntent = getIntent();

    String ot = myIntent.getStringExtra("outlt");
    String ch = myIntent.getStringExtra("chnl");
    String cls = myIntent.getStringExtra("cls");

    oname.setText(ot);
    sch.setText(ch);
    scls.setText(cls);

}

 }

Your help is so much appreciated forever in my heart guys.Even other methods of doing the same tasks i welcome them.Thank you so much in advance.

Change this

 TextView outname = (TextView)findViewById(R.id.outlet_name);
 TextView channel = (TextView)findViewById(R.id.sparkling_channel);
 TextView clas = (TextView)findViewById(R.id.sparkling_classification);

to

 TextView outname = (TextView)view.findViewById(R.id.outlet_name);
 TextView channel = (TextView)view.findViewById(R.id.sparkling_channel);
 TextView clas = (TextView)view.findViewById(R.id.sparkling_classification);

You need to use the view to find views. Instead of initalizing views you can do as below

The other way

  lv.setOnItemClickListener(new OnItemClickListener() {

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

          HashMap<String,String> map=  (HashMap<String, String>) parent.getItemAtPosition(position); // use postion. get the map
          String foutname =map.get(TAG_OUTLET_NAME); // get the value using key
          String fchannel = map.get(TAG_SPARKLING_CHANNEL);
          String fclass = map.get(TAG_SPARKLING_CLASSIFICATION);
          ...// rest of the code

       }
   });

Use Following:

lv.setOnItemClickListener(new OnItemClickListener() {

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

        int itemPosition = position;

           View view1=(View) lv.getItemAtPosition(itemPosition );
        TextView outname = (TextView)view1.findViewById(R.id.outlet_name);
        TextView channel = (TextView)view1.findViewById(R.id.sparkling_channel);
        TextView clas = (TextView)view1.findViewById(R.id.sparkling_classification);

        String foutname = outname.getText().toString();
        String fchannel = channel.getText().toString();
        String fclass = clas.getText().toString();


         Intent i = new Intent(Outlets.this, ScoreSheet.class);
         i.putExtra("outlt", foutname);
         i.putExtra("chnl", fchannel);
         i.putExtra("cls", fclass);
         startActivity(i);

    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM