将Android listview字符串值传递给另一个活动

时间:2014-05-19 11:29:01

标签: android listview select android-listview

我在Android应用程序上遇到问题,我使用JSON解析从mysql获取数据。

当我选择一个listview项目并将其传递给另一个活动时,它会取一个随机值而不是我选择的那个。

以下是listview活动中的代码。

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

}

我的下一个活动的代码是这个。我想测试我是否使用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);

}

 }

你的帮助在我心中永远受到赞赏。即使是其他方法,我也欢迎他们做同样的工作。非常感谢你们。

2 个答案:

答案 0 :(得分:0)

更改此

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

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

您需要使用view查找视图。您可以按照以下方式进行意见化,而不是

另一种方式

  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

       }
   });

答案 1 :(得分:0)

使用以下:

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

    }
});