web-dev-qa-db-fra.com

La méthode getApplicationContext () n'est pas définie - problèmes de fragments

Je reçois les erreurs suivantes: La méthode getApplicationContext () n'est pas définie La méthode findViewById (int) n'est pas définie pour le type Fragment1

Ces erreurs semblent être éliminées lorsque ma classe est étendue à une activité par opposition à un fragment, mais il est important que cette activité reste en tant que fragment, donc je ne sais pas trop comment résoudre ce problème.

Toute aide serait grandement appréciée. Merci d'avance.

Ci-dessous le 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();
            }
        }
    });
}
}

Mettre à jour l'erreur de code inaccessible pour 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();

Mise à jour

Lors du lancement de l'activité, j'ai reçu le message suivant:

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

Ci-dessous, la page d'activité qui appelle le 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);
    }
}

pdate 2 Ci-dessous le message que je reçois dans 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)
16
John

Vous pouvez obtenir l'activité qui contient le fragment avec getActivity().

Par conséquent, getActivity().getApplicationContext() fonctionnerait.

getActivity().findViewById(int) fonctionnerait également.

Assurez-vous cependant que vous n'utilisez pas getActivity() avant onActivityCreated(), car il retournerait null avant cela.

68
Eran

Changement

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

à

Intent intent = new Intent(getActivity(), LoginActivity.class);
1
Chefes