从列表视图中选择项目

时间:2014-08-04 17:21:29

标签: java android json android-layout android-activity

通过研究和支持,我创建了一个通过JSON数据填充的项目列表。我希望当用户点击其中一个项目数组时,它会将它们重定向到另一个活动,以便为他们提供有关它的更多信息。在帮助下,我试图弄清楚代码,即使有了帮助,到目前为止我的尝试都没有成功。

特别是,我在代码的这一部分遇到以下错误:

listview.setOnItemClickListener(new OnItemClickListener(){

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
                        intent.putExtra("id_item", id);//this is id of the item that you said it. for example id:5544323 from your JSON web service
                        intent.putExtra("position", position); //order position in listview 0-1-2-3...
                        startActivity(intent); //start Activity
                    }

                }

我收到错误的地方有:

“ItemClickListener类型的onItemClick方法(AdapterView,View,int,long)必须覆盖或实现超类型方法”

“在范围内无法访问EventsActivity类型的封闭实例”

“无法从类型Activity”

中对非静态方法startActivity(Intent)进行静态引用

完整的代码可以在下面找到

public class EventsActivity extends Activity{

    private static final String URL_WEB_SERVICE = "http://dooba.ca/analytics/ed.php";
    private GridView gv;
    private ArrayList<Events_List> container;
    private ArrayList<Events_List> items;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.events_list_layout);
        gv = (GridView) findViewById(R.id.gridview);
        container = new ArrayList<Events_List>();
        //download JSON
        listDownload();

        //add interface ItemClickListener
        public interface ItemClickListener {


                listview.setOnItemClickListener(new OnItemClickListener(){

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
                        intent.putExtra("id_item", id);//this is id of the item that you said it. for example id:5544323 from your JSON web service
                        intent.putExtra("position", position); //order position in listview 0-1-2-3...
                        startActivity(intent); //start Activity
                    }

                }


                //catch in the second activity values 
                long id_item = getIntent().getExtras().getLong("id_item");
                int position = getIntent().getExtras().getInt("id_item");


        //Adding reference to id of the item from your json we service in adapter


            public long getItemId(int position) {
                return items.get(position).id; 

    }
        }}





    public void listDownload(){
        RequestQueue volley = Volley.newRequestQueue(this);
        JsonObjectRequest json = new JsonObjectRequest(Method.GET, URL_WEB_SERVICE, null, ResponseListener(), ErrorListener());
        volley.add(json);
    }

    private Response.Listener<JSONObject> ResponseListener() {
        return new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    //your JSON Array
                    JSONArray array = response.getJSONArray("list_item");
                    for(int i = 0; i < array.length(); i++){
                        container.add(convertirAnuncio(array.getJSONObject(i)));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                gv.setAdapter(new AdapterEvents(getApplicationContext(),container));
                }
            };
        };


    private Response.ErrorListener ErrorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) { }
        };
    }

    //object JSON
    private final Events_List convertirAnuncio(JSONObject obj) throws JSONException {
        long id = obj.getLong("id"); //id 
        String list_item_name = obj.getString("list_item_name"); 
        String list_item_description = obj.getString("list_item_description");
        String list_item_price = obj.getString("list_item_price");
        Uri uri = Uri.parse(obj.getString("list_item_bac"));
        return new Events_List(id,list_item_name,list_item_description,list_item_price, uri);
    }
}

提前致谢

根据收到的好建议进行更新

我已根据评论更新了代码,现在面临以下小问题: listview无法解析,在以下行中生成错误:

 listview.setOnItemClickListener(new OnItemClickListener(){

我还遇到了一个次要的格式化问题,我试图通过右键单击&gt;来解决这个问题。来源&gt;格式,但错误仍然存​​在

listview.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
                intent.putExtra("id_item", id);//this is id of the item that you said it. for example id:5544323 from your JSON web service
                intent.putExtra("position", position); //order position in listview 0-1-2-3...
                startActivity(intent); //start Activity
            }
        }

完成下面的更新代码

public class EventsActivity extends Activity{

    private static final String URL_WEB_SERVICE = "http://dooba.ca/analytics/ed.php";
    private GridView gv;
    private ArrayList<Events_List> container;
    private ArrayList<Events_List> items;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.events_list_layout);
        gv = (GridView) findViewById(R.id.gridview);
        container = new ArrayList<Events_List>();
        //download JSON
        listDownload();


        listview.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
                intent.putExtra("id_item", id);//this is id of the item that you said it. for example id:5544323 from your JSON web service
                intent.putExtra("position", position); //order position in listview 0-1-2-3...
                startActivity(intent); //start Activity
            }
        }





    public void listDownload(){
        RequestQueue volley = Volley.newRequestQueue(this);
        JsonObjectRequest json = new JsonObjectRequest(Method.GET, URL_WEB_SERVICE, null, ResponseListener(), ErrorListener());
        volley.add(json);
    }

    private Response.Listener<JSONObject> ResponseListener() {
        return new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    //your JSON Array
                    JSONArray array = response.getJSONArray("list_item");
                    for(int i = 0; i < array.length(); i++){
                        container.add(convertirAnuncio(array.getJSONObject(i)));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                gv.setAdapter(new AdapterEvents(getApplicationContext(),container));
                }
            };
        };


    private Response.ErrorListener ErrorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) { }
        };
    }

    //object JSON
    private final Events_List convertirAnuncio(JSONObject obj) throws JSONException {
        long id = obj.getLong("id"); //id 
        String list_item_name = obj.getString("list_item_name"); 
        String list_item_description = obj.getString("list_item_description");
        String list_item_price = obj.getString("list_item_price");
        Uri uri = Uri.parse(obj.getString("list_item_bac"));
        return new Events_List(id,list_item_name,list_item_description,list_item_price, uri);
    }

更新2 我从logcat收到了以下消息。我已经清理了我的项目,并且已经验证了清单中引用了活动。我相信这可能是以下代码的问题。

Logcat消息:

08-04 20:00:30.492: E/AndroidRuntime(1481): FATAL EXCEPTION: main
08-04 20:00:30.492: E/AndroidRuntime(1481): Process: com.dooba.beta, PID: 1481
08-04 20:00:30.492: E/AndroidRuntime(1481): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.EventsActivity}: java.lang.NullPointerException
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.os.Looper.loop(Looper.java:136)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at java.lang.reflect.Method.invoke(Method.java:515)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at dalvik.system.NativeStart.main(Native Method)
08-04 20:00:30.492: E/AndroidRuntime(1481): Caused by: java.lang.NullPointerException
08-04 20:00:30.492: E/AndroidRuntime(1481):     at com.dooba.beta.EventsActivity.onCreate(EventsActivity.java:54)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.app.Activity.performCreate(Activity.java:5231)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-04 20:00:30.492: E/AndroidRuntime(1481):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-04 20:00:30.492: E/AndroidRuntime(1481):     ... 11 more

更新后的活动代码:

public class EventsActivity extends Activity{

    private static final String URL_WEB_SERVICE = "http://dooba.ca/analytics/ed.php";
    private GridView gv;
    private ArrayList<Events_List> container;
    private ArrayList<Events_List> items;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.events_list_layout);
        gv = (GridView) findViewById(R.id.gridview);
        container = new ArrayList<Events_List>();
        //download JSON
        listDownload();


        ListView s = (ListView) findViewById(R.id.listViewSingleClick);
        s.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
                intent.putExtra("id_item", id);//this is id of the item that you said it. for example id:5544323 from your JSON web service
                intent.putExtra("position", position); //order position in listview 0-1-2-3...
                startActivity(intent); //start Activity
            }
        });
    }
    public void listDownload(){
        RequestQueue volley = Volley.newRequestQueue(this);
        JsonObjectRequest json = new JsonObjectRequest(Method.GET, URL_WEB_SERVICE, null, ResponseListener(), ErrorListener());
        volley.add(json);
    }

    private Response.Listener<JSONObject> ResponseListener() {
        return new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    //your JSON Array
                    JSONArray array = response.getJSONArray("list_item");
                    for(int i = 0; i < array.length(); i++){
                        container.add(convertirAnuncio(array.getJSONObject(i)));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                gv.setAdapter(new AdapterEvents(getApplicationContext(),container));
                }
            };
        };


    private Response.ErrorListener ErrorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) { }
        };
    }

    //object JSON
    private final Events_List convertirAnuncio(JSONObject obj) throws JSONException {
        long id = obj.getLong("id"); //id 
        String list_item_name = obj.getString("list_item_name"); 
        String list_item_description = obj.getString("list_item_description");
        String list_item_price = obj.getString("list_item_price");
        Uri uri = Uri.parse(obj.getString("list_item_bac"));
        return new Events_List(id,list_item_name,list_item_description,list_item_price, uri);
    }
}

2 个答案:

答案 0 :(得分:1)

<强>问题:

public interface ItemClickListener {

您正在将方法调用包装到setOnItemClickListener,这完全在不同的范围内,从而为您提供这些错误,我不知道为什么要将接口放在onCreate方法中,这实际上是一个糟糕的设计。< / p>

<强>溶液

只需删除public interface ItemClickListener {即可使用该类的引用,而不是ItemClickListener

修改

ListView s = (ListView) findViewById(R.id.id_to_list_view);

编辑2:

setOnItemClickListener(new OnItemClickListener(){

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

        }
    });

答案 1 :(得分:1)

试试这段代码: 删除你的接口代码和getItem代码..这就是使itemClickListener工作所需的一切。

                listview.setOnItemClickListener(new OnItemClickListener(){

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
                        intent.putExtra("id_item", id);//this is id of the item that you said it. for example id:5544323 from your JSON web service
                        intent.putExtra("position", position); //order position in listview 0-1-2-3...
                        startActivity(intent); //start Activity
                    }

                }