简体   繁体   中英

intent keeps crashing my app?

I'm building a simple menu app for my class. I have a ListView on my app and I am trying to make it so that when you click an item in the the list you are taken to the appropiate activity for that item. So far I got intents working outside my function but when I run it inside a function it crashes my program. can any one point me out in the right direction

    //set the item listener
    menu.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String selected = ((TextView) view.findViewById(R.id.complaint)).getText().toString();
            if(selected.equals("Pasta")){
                runPasta();
            }
        }
    });


}

public void runPasta(){
    //Intent myIntent = new Intent(this, PastaItems.class);
    //myIntent.putStringArrayListExtra("finalList", foodList);
    this.startActivity(new Intent(this,PastaItems.class));

}

You're calling the runPasta() function from inside the OnItemClickListener which means that this refers to the OnItemClickListener instance. Try using ActivityClassName.this instead of just this .

You are using this as a context , it wont work inside setOnItemClickListener because it creates an anonymous inner class . So you need to be more specific. Replace this with YourActivity.this

This might solve your problem. Using getContext() gives you the appropriate context. Try this :

startActivity(new Intent(getContext(),PastaItems.class));

您可以将adapterView上的实例adapterView给runPasta方法,并从runPasta方法传递它,您可以将其称为startActivity(new Intent(adapterView.getContext(),PastaItems.class));

确保已在清单中声明了PastaItems活动。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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