所以我目前在我的应用程序上有一个返回的JSON
对象列表作为ListView
,我正在尝试创建它以便我可以单击该对象然后编辑详细信息,但是关于为什么我的setOnItemClickListener
无法正常工作,代码如下
package mmu.tom.linkedviewproject;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private ListView GetAllDevicesListView;
private JSONArray jsonArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.GetAllDevicesListView = (ListView) this.findViewById(R.id.GetAllDevicesListView);
new GetAllDevicesTask().execute(new ApiConnector());
GetAllDevicesTask.setOnItemClickListener (new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
try
{
//GetDevice that was clicked
JSONObject deviceClicked = jsonArray.getJSONObject(position);
//Send DeviceId
Intent showDetails = new Intent(getApplicationContext(), DeviceDetailsActivity.class);
showDetails.putExtra("deviceID", deviceClicked.getString("deviceID"));
}
catch(
JSONException e
)
{
e.printStackTrace();
}
}
});
}
public void setListAdapter(JSONArray jsonArray){
this.jsonArray = jsonArray;
this.GetAllDevicesListView.setAdapter((new GetAllDeviceListViewAdapter(jsonArray,this)));
}
private class GetAllDevicesTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
@Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllDevicesState();
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
}
答案 0 :(得分:0)
您没有在setOnItemClickListener
上设置ListView
,而是在班级名称上设置。{/ p>
更改
GetAllDevicesTask.setOnItemClickListener (new AdapterView.OnItemClickListener() {
到
GetAllDevicesListView.setOnItemClickListener (new AdapterView.OnItemClickListener() {
答案 1 :(得分:0)
您没有使用列表视图对象。
改为此。
GetAllDevicesListView.setOnItemClickListener (new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
try
{
//GetDevice that was clicked
JSONObject deviceClicked = jsonArray.getJSONObject(position);
//Send DeviceId
Intent showDetails = new Intent(getApplicationContext(), DeviceDetailsActivity.class);
showDetails.putExtra("deviceID", deviceClicked.getString("deviceID"));
}
catch(
JSONException e
)
{
e.printStackTrace();
}
}
});