The method getApplicationContext() is undefined - fragment issues
Asked Answered
G

3

22

I am getting the following errors: The method getApplicationContext() is undefined The method findViewById(int) is undefined for the type Fragment1

These errors seem to be eliminated when my class is extended to an Activity as oppose to a fragment, but it is important that this activity remains as a fragment, so I am not too sure how to work this out.

Any help would be greatly appreciated. Thanks in advance.

Below is the code

public class Fragment1 extends Fragment {

    private String currentUserId;
    private ArrayAdapter<String> namesArrayAdapter;
    private ArrayList<String> names;
    private ListView usersListView;
    private Button logoutButton;
    String userGender = ParseUser.getCurrentUser().getString("Gender");
    String activityName = ParseUser.getCurrentUser().getString("ActivityName");
    Number maxDistance = ParseUser.getCurrentUser().getNumber("Maximum_Distance");


    String userLookingGender = ParseUser.getCurrentUser().getString("Looking_Gender");
    Number minimumAge = ParseUser.getCurrentUser().getNumber("Minimum_Age");
    Number maximumAge = ParseUser.getCurrentUser().getNumber("Maximum_Age");
    Number userage = ParseUser.getCurrentUser().getNumber("Age");


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (container == null){
            return null;
        }

        return (LinearLayout)inflater.inflate(R.layout.fragment1_layout, 
                container,false);

    logoutButton = (Button) findViewById(R.id.logoutButton);
    logoutButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ParseUser.logOut();
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
        }
    });

    setConversationsList();
}
private void setConversationsList() {
    currentUserId = ParseUser.getCurrentUser().getObjectId();
    names = new ArrayList<String>();
    // String userActivitySelectionName = null;

    ParseQuery<ParseUser> query = ParseUser.getQuery();

    //  query.whereEqualTo("ActivityName",userActivitySelectionName);

    query.whereNotEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
    // users with Gender = currentUser.Looking_Gender
    query.whereEqualTo("Gender", userLookingGender);
    // users with Looking_Gender = currentUser.Gender
    query.whereEqualTo("Looking_Gender", userGender);
    query.setLimit(1);
    query.whereEqualTo("ActivityName", activityName);
    query.whereGreaterThanOrEqualTo("Minimum_Age", minimumAge).whereGreaterThanOrEqualTo("Age", userage);
    query.whereLessThanOrEqualTo("Maximum_Age", maximumAge).whereLessThanOrEqualTo("Age", userage);
    //  query.whereWithinKilometers("Maximum_Distance", point, maxDistance)





    query.findInBackground(new FindCallback<ParseUser>() {

        public void done(List<ParseUser> userList, ParseException e) {
            if (e == null) {
                for (int i=0; i<userList.size(); i++) {
                    names.add(userList.get(i).get("Name").toString());
                    names.add(userList.get(i).get("Headline").toString());
                    names.add(userList.get(i).get("Age").toString());

                    //       names.add(userList.get(i).getParseObject("ProfilePicture").;


                }




                usersListView = (ListView)findViewById(R.id.usersListView);
                namesArrayAdapter =
                        new ArrayAdapter<String>(getApplicationContext(),
                                R.layout.user_list_item, names);
                usersListView.setAdapter(namesArrayAdapter);

                usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> a, View v, int i, long l) {
                        openConversation(names, i);
                    }
                });

            } else {
                Toast.makeText(getApplicationContext(),
                        "Error loading user list",
                        Toast.LENGTH_LONG).show();
            }
        }
    });
}

public void openConversation(ArrayList<String> names, int pos) {
    ParseQuery<ParseUser> query = ParseUser.getQuery();
    query.whereEqualTo("Name", names.get(pos));
    query.findInBackground(new FindCallback<ParseUser>() {
        public void done(List<ParseUser> user, ParseException e) {
            if (e == null) {
                Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
                intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
                startActivity(intent);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Error finding that user",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });
}
}

Update Unreachable code error for setConversationList

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (container == null){
            return null;
        }

        return (LinearLayout)inflater.inflate(R.layout.fragment1_layout, 
                container,false);

    setConversationsList();
}
private void setConversationsList() {
    currentUserId = ParseUser.getCurrentUser().getObjectId();
    names = new ArrayList<String>();
    // String userActivitySelectionName = null;

    ParseQuery<ParseUser> query = ParseUser.getQuery();

Update

Upon launching the activity, I received the following message:

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

Below is the activity page that calls for the fragment

import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;



public class usermatch extends FragmentActivity {
    private PageAdapter mPagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewpager_layout);
        initialisePaging();

    }

    private void initialisePaging() {
        // TODO Auto-generated method stub
        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
        fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
        fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
        mPagerAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
        ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        pager.setAdapter(mPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mood, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Update 2 Below is the message I receive in logcat

08-15 17:42:28.863: E/AndroidRuntime(4974): FATAL EXCEPTION: main
08-15 17:42:28.863: E/AndroidRuntime(4974): Process: com.dooba.beta, PID: 4974
08-15 17:42:28.863: E/AndroidRuntime(4974): java.lang.NullPointerException
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.dooba.beta.Fragment1$1.done(Fragment1.java:108)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.FindCallback.internalDone(FindCallback.java:45)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.FindCallback.internalDone(FindCallback.java:1)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.parse.Parse$6$1.run(Parse.java:888)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Handler.handleCallback(Handler.java:733)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.os.Looper.loop(Looper.java:136)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at java.lang.reflect.Method.invokeNative(Native Method)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at java.lang.reflect.Method.invoke(Method.java:515)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 17:42:28.863: E/AndroidRuntime(4974):     at dalvik.system.NativeStart.main(Native Method)
Godly answered 15/8, 2014 at 15:26 Comment(0)
B
94

You can get the activity that contains the fragment with getActivity().

Therefore getActivity().getApplicationContext() would work.

getActivity().findViewById(int) would also work.

Make sure, though, you don't use getActivity() prior to onActivityCreated(), since it would return null prior to that.

Braun answered 15/8, 2014 at 15:29 Comment(12)
thanks for your prompt response, and I have applied your suggestions, however, the following line seems to be problematic logoutButton = (Button) getActivity().findViewById(R.id.logoutButton);Godly
@Braun what abt 'Intent intent = new Intent(getActivity(), LoginActivity.class);' this will also work rit..?Geometer
@SaravanarajaT Depends on what context you wish to use. getActivity() by itself can serve as a context (since it's a sub-class of Context). getActivity().getApplicationContext() returns the single, global Application object of the current process.Braun
@user3907211 You are making this call in onCreateView() which is called prior to onActivityCreated(), so getActivity() probably returns null. Can you move this code to onActivityCreated()?Braun
Thanks for your response. I have deleted the logoutButton = (Button) getActivity().findViewById(R.id.logoutButton); as it was not a necessity. However, in doing so i have encountered the following error - Unreachable code for the following line setConversationsList(); which I cant seem to fix. I have updated this under my initial postGodly
@user3907211 You are calling setConversationsList(); after a return statement. That's why it's unreachable.Braun
Thank you for your support and your prompt responses. Upon running the code, which ran initially, I received an unexpected nullpointer exception error. I tried to dive into it, but couldn't solve it. I have attached the logcat message under the update section of my initial post. If you could further assist me with that I am be greatly thankful.Godly
@user3907211 What's in usermatch.java, line 32?Braun
usermatch.java is the activity class that calls the fragment. In the sense that when the activity launches it direct itself to usermatch and where users swipe left and right between different fragments like the fragment I included here (fragment 1). I have included the usermatch activity code under the update section of my initial post. ThanksGodly
@user3907211 I asked what's in line 32, since the exception happens there.Braun
Thanks for your reply. I think the error occurred because I launched directly into this activity, where it could not detect the current user. Usually it would launch in the login screen, where users would have to signin and hence would become the current user. I have managed to solve that null exception, but I don't understand as to why I am getting another one when that fragment activity is launched, despite the user already signin. I have attached the updated logcat under the update section of my initial post. Thanks mcuhGodly
@Braun +1 for the reason of null :)Wart
O
1

Change

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);

to

Intent intent = new Intent(getActivity(), LoginActivity.class);
Ovariectomy answered 15/8, 2014 at 15:27 Comment(3)
should I use getActivity().getApplicationContext() or getActivity() thanks for your responseGodly
getActivity() is for me the best option, because never going to be null in a fragment.Ovariectomy
Thank you for your responses and support. Upon launching the activity, I recieved an unexpected null pointer exception error in response to that. I have updated my issues under the update section of my initial post. If you could look into that, I would greatly thankful.Godly
K
0

you can access context from onAttach() like below example

 @Override
    public void onAttach(@NonNull Context context) {


        super.onAttach(context);
    }
Killigrew answered 19/2, 2020 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.