简体   繁体   English

在列表视图项上按ID打开新活动,请点击

[英]Open New Activity by id on Listview Item Click

My ListView is opening and everything is ok. 我的ListView正在打开,一切正常。 I don´t know how to pass params from onPostExecute() to onItemClick() to open a new activity (SingleItem.java) by id. 我不知道如何将参数从onPostExecute()传递给onItemClick(),以按ID打开新活动(SingleItem.java)。 Nothing that I´ve tried has worked. 我尝试过的所有方法均无济于事。

ListItems.java ListItems.java

public class ListItems extends Activity {

private ListView listV;
TextView estado, cidade, noItem;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_items);

    listV = (ListView) findViewById(R.id.listV);

    estado = (TextView) findViewById(R.id.Estado);
    cidade = (TextView) findViewById(R.id.Cidade);
    noItem = (TextView) findViewById(R.id.noItem);

    estado.setText(getIntent().getExtras().getString("state"));     
    cidade.setText(getIntent().getExtras().getString("city"));

    Task task = new Task();
    task.execute();

    listV.setOnItemClickListener(new OnItemClickListener() {

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

            Intent intent = new Intent(getApplicationContext(), SingleItem.class);

            startActivity(intent);
        }
    });
}

public class Task extends AsyncTask<String, String, Void>{

    private ProgressDialog progressDialog = new ProgressDialog(ListItems.this);

    InputStream is = null;
    String result = "";

    protected void onPreExecute() {
        progressDialog.setMessage("Listing Items...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                Task.this.cancel(true);
            }
        });
    };

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

        String url = "http://myip/webviews/jsonlistItems.php";

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(param));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            is = httpEntity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error connecting to database " + e.toString());
            Toast.makeText(ListItems.this, "Try again.", Toast.LENGTH_LONG).show();
        }

        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = "";

            while((line = br.readLine()) != null){
                sb.append(line+"\n");
            }
                is.close();
                result = sb.toString();

        }catch(Exception e){
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        return null;
    }

    protected void onPostExecute(Void v){

        try {
            JSONArray Jarray = new JSONArray(result);
            for (int i = 0; i < Jarray.length(); i++) {
                JSONObject jsonObject = null;
                jsonObject = Jarray.getJSONObject(i);

                // output
                String item_id = jsonObject.getString("item_id");

                String item_name = jsonObject.getString("item_name");
                String item_color = jsonObject.getString("item_color");
                String city = jsonObject.getString("city");
                String statee = jsonObject.getString("state");

                if(estado.getText().toString().equalsIgnoreCase(statee) && 
                        cidade.getText().toString().equalsIgnoreCase(city)){

                    String[] values = new String[] {item_name, item_color};

                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);

                    listV.setAdapter(adapter);
                    break;
                }
                else{
                    noItem.setText("No Item to show");
                }
            }
            this.progressDialog.dismiss();
        } catch (Exception e) {
            Log.e("log_tag", "Error parsing data "+e.toString());
        }
    }

}


public class ItemById{

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.list_events, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

SingleItem.java SingleItem.java

public class SingleItem extends Activity {

TextView item_name, item_color;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_singleitem);

    item_name = (TextView) findViewById(R.id.item_name);
    item_color = (TextView) findViewById(R.id.item_color);


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.event, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

How to pass params from onPostExecute() to onItemClick() to open a new activity (SingleItem.java) by id? 如何将参数从onPostExecute()传递给onItemClick()以通过ID打开新活动(SingleItem.java)?

The adapter looks like it's populated only by each attribute of your JSON object (one row for item_name, one row for item_color). 适配器看起来只由JSON对象的每个属性填充(item_name的一行,item_color的一行)。 If this is what you want the naturally you won't get item_id because it's not there. 如果这是您想要的,自然就不会得到item_id,因为它不存在。

If you want each row to correspond to each of your JSON objects then you should modify your adapter. 如果希望每一行都对应于每个JSON对象,则应修改适配器。

First make your own class like so 首先像这样使自己的课

class Wrap{
    String itemId, itemName, city, statee;
}

And then create your own Adapter class that extends ArrayAdapter<Wrap> . 然后创建扩展ArrayAdapter<Wrap>自己的Adapter类。

This way every time a row is clicked, you can get the Wrap object which contains everything, including id. 这样,每次单击一行时,您都可以获得包含所有内容(包括ID)的Wrap对象。 Then you can pass these values to your next Activity. 然后,您可以将这些值传递给下一个活动。

It all depends what your SingleItem Activity is supposed to show when it's opened. 这完全取决于您的SingleItem Activity打开时应显示的内容。 If you only need the name of the selected item then you simply retrieve the item name in the onItemClick method and pass it as parameter to SingleItem: 如果只需要选定项目的名称,则只需在onItemClick方法中检索项目名称,然后将其作为参数传递给SingleItem:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent(getApplicationContext(), SingleItem.class);
    String name = adapter.getItem(position);
    intent.putExtra("yourItem", name);
    startActivity(intent);
}

In order for this to work the adapter needs to be a variable in the Activity: 为了使它起作用,适配器需要是Activity中的变量:

public class ListItems extends Activity {
    private ArrayAdapter<String> adapter;

and this: 和这个:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);

becomes this: 变成这个:

adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);

If you need more information in the SingleItem Activity than just the name of the item you'd have to create an Item class to hold that information: 如果您在SingleItem Activity中需要的不仅仅是信息名称,还需要创建一个Item类来保存该信息:

public static class Item implements Serializable {
    String mName;
    String mColor;
    // more data

    @Override
    public String toString() {
        return mName;
    }
}

your onItemClick becomes: 您的onItemClick变为:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent(getApplicationContext(), SingleItem.class);
    Item item = adapter.getItem(position);
    intent.putExtra("yourItem", name);
    startActivity(intent);
}

Your adapter would be: 您的适配器为:

ArrayAdapter<Item> adapter;
adapter = new ArrayAdapter<Item>(ListItems.this, android.R.layout.simple_list_item_1, itemArray);

Of course you'd need to create the itemArray when parsing the json stream. 当然,在解析json流时,您需要创建itemArray。

The activity could easily read the selected item from the intent like so: 该活动可以轻松地从意图中读取所选项目,如下所示:

getIntent().getSerializableExtra("yourItem");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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