如何将从服务器获取的listview项的ID传递给另一个活动onclick?

时间:2018-07-29 09:05:02

标签: android listview listviewitem

在一些联机帮助下,我已成功从服务器获取数据到列表视图。我想要去的另一个活动是获取列表视图项的“ id”并显示它。

我一直在努力解决这个问题,但没有成功。

我的mainactivity.java文件

public class MainActivity extends AppCompatActivity {

ListView listView;

Button button;

// Server Http URL
String HTTP_URL = "http://192.168.100.48/listview/index.php";

// String to hold complete JSON response object.
String FinalJSonObject ;

ProgressBar progressBar;

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

    // Assign ID's to ListView.
    listView = (ListView) findViewById(R.id.listView1);

    button = (Button)findViewById(R.id.button);

    progressBar = (ProgressBar)findViewById(R.id.ProgressBar1);

    // Adding click listener to button.
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //Showing progress bar just after button click.
            progressBar.setVisibility(View.VISIBLE);

            // Creating StringRequest and set the JSON server URL in here.
            StringRequest stringRequest = new StringRequest(HTTP_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                            // After done Loading store JSON response in FinalJSonObject string variable.
                            FinalJSonObject = response ;

                            // Calling method to parse JSON object.
                            new ParseJSonDataClass(MainActivity.this).execute();

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                            // Showing error message if something goes wrong.
                            Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();

                        }
                    });

            // Creating String Request Object.
            RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

            // Passing String request into RequestQueue.
            requestQueue.add(stringRequest);

        }
    });
}

// Creating method to parse JSON object.
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {

    public Context context;

    // Creating List of Subject class.
    List<Subject> CustomSubjectNamesList;

    public ParseJSonDataClass(Context context) {

        this.context = context;
    }

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        try {

            // Checking whether FinalJSonObject is not equals to null.
            if (FinalJSonObject != null) {

                // Creating and setting up JSON array as null.
                JSONArray jsonArray = null;
                try {

                    // Adding JSON response object into JSON array.
                    jsonArray = new JSONArray(FinalJSonObject);

                    // Creating JSON Object.
                    JSONObject jsonObject;

                    // Creating Subject class object.
                    Subject subject;

                    // Defining CustomSubjectNamesList AS Array List.
                    CustomSubjectNamesList = new ArrayList<Subject>();

                    for (int i = 0; i < jsonArray.length(); i++) {

                        subject = new Subject();

                        jsonObject = jsonArray.getJSONObject(i);

                        //Storing ID into subject list.
                        subject.Subject_ID = jsonObject.getString("id");

                        //Storing Subject name in subject list.
                        subject.Subject_Name = jsonObject.getString("subject_Name");

                        // Adding subject list object into CustomSubjectNamesList.
                        CustomSubjectNamesList.add(subject);



                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)

    {
        // After all done loading set complete CustomSubjectNamesList with application context to ListView adapter.
        ListViewAdapter adapter = new ListViewAdapter(CustomSubjectNamesList, context);

        // Setting up all data into ListView.
        listView.setAdapter(adapter);

        // Hiding progress bar after all JSON loading done.
        progressBar.setVisibility(View.GONE);

    }
}

}

我的Listviewadapter.java文件

public class ListViewAdapter extends BaseAdapter
{
Context context;

List<Subject> TempSubjectList;

public ListViewAdapter(List<Subject> listValue, Context context)
{
    this.context = context;
    this.TempSubjectList = listValue;
}

@Override
public int getCount()
{
    return this.TempSubjectList.size();
}

@Override
public Object getItem(int position)
{
    return this.TempSubjectList.get(position);
}

@Override
public long getItemId(int position)
{
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    ViewItem viewItem = null;

    if(convertView == null)
    {
        viewItem = new ViewItem();

        LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        convertView = layoutInfiater.inflate(R.layout.listview_items, null);

        viewItem.IdTextView = (TextView)convertView.findViewById(R.id.textviewID);

        viewItem.NameTextView = (TextView)convertView.findViewById(R.id.textviewSubjectName);

        convertView.setTag(viewItem);
    }
    else
    {
        viewItem = (ViewItem) convertView.getTag();
    }

    viewItem.IdTextView.setText(TempSubjectList.get(position).Subject_ID);

    viewItem.NameTextView.setText(TempSubjectList.get(position).Subject_Name);

    return convertView;
}
}
class ViewItem    {
  TextView IdTextView;
  TextView NameTextView;
 }

当然还有我的subject.java文件

public class Subject {

public String Subject_ID;
public String Subject_Name;

}

IMAGE - It successfully shows the data from server. But I haven't figured it out how to make what I want to do when I click the item.

是的,这就是我的睡眠与安宁。

2 个答案:

答案 0 :(得分:0)

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

        Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
        intent.putExtra("ID",CustomSubjectNamesList.get(position).Subject_ID);
        startActivity(intent);
    }
});

并且来自另一个活动

首先,使用getIntent()方法获取开始活动的意图:

Intent intent = getIntent();

如果多余的数据以字符串表示,则可以使用intent.getStringExtra(String name)方法。就您而言:

Intent intent = getIntent();
String id = intent.getStringExtra("ID");

答案 1 :(得分:0)

您可以使用Serializable将字符串或整数或仅将实现intent.putExtra()的任何对象发送给另一个活动

listView.setOnItemClickListener(new AdapaterView.OnItemClickListener() {

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

        Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
        intent.putExtra("id",CustomSubjectNamesList.get(position).Subject_ID;
        startActivity(intent);
    }
});

然后在您的新活动中接收到您刚刚使用getIntent.getIntExtra("id")getIntent.getStringExtra()发送的信息。或根据您发送的内容使用其他方法。