1

I have a listview and when it clicks on a certain option I want it to create a new intent. Like a menu item. This is my first time working with list views, so I'm probably just missing the right way to do this, but is there an easy fix?

private void registerClickCallback() {
    ListView list = (ListView) findViewById(R.id.mainlist);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
        TextView textView = (TextView) viewClicked;
        Toast.makeText(main.this, position, Toast.LENGTH_SHORT).show();
        if(textView.getText().toString() == "my Profile"){
            Intent intent = new Intent(this.getApplicationContext(), myProfile.class);
            startActivity(intent);
        }
    }
});

cannot resolve method 'getapplicationcontext'

Jeff
  • 12,555
  • 5
  • 33
  • 60
Bahamit
  • 103
  • 6
  • Looks like you are comparing Strings wrong. You should use `.equals()` instead of `==`. If there is another problem then you need to be more clear on exactly what is/isn't happening – codeMagic Apr 21 '16 at 23:14
  • 1
    @codeMagic This question has little to do with string comparison.. the `IF` surely needs to be fixed but the actual question is about the error `cannot resolve method 'getApplicationContext()' hence the question is different.. imho – fredmaggiowski Apr 21 '16 at 23:15
  • 1
    @FredMaggiowski yep, I missed that. Thanks for pinging me and pointing it out. I will reopen. The String comparison will be the next issue most likely. Bahamit, use `viewClicked.getContext()` instead. – codeMagic Apr 21 '16 at 23:34
  • No prob :) yeah, the string comparison **must** to be fixed – fredmaggiowski Apr 21 '16 at 23:41
  • Thank you all for the comments! I have taken your input into consideration and I got my application running again. However, now I have a new problem: java.lang.OutOfMemoryError: Failed to allocate a 108000012 byte allocation with 8388608 free bytes and 46MB until OOM... I'm running out of memory. Do I have to close out of my previous intents/activities? – Bahamit Apr 22 '16 at 22:16

2 Answers2

2

You can't use this.getApplicationContext() since you're inside a new AdapterView.OnItemClickListener() and there,this doesn't have that method.

You should create a class field containing the application context and use it or use viewClicked.getContext() as suggested by @codeMagic.

Also, as you might have been read in the comments, you should use .equals for string comparison. The == operator is not enough.

fredmaggiowski
  • 2,232
  • 3
  • 25
  • 44
1

Try -

Intent intent = new Intent(MainActivity.this, myProfile.class);
startActivity(intent);

Where MainActivity is he activity where you implemented onItemClick(). You should replace it by your activity name.

Shadab Ansari
  • 7,022
  • 2
  • 27
  • 45