web-dev-qa-db-ja.com

メソッドgetApplicationContext()は未定義です-フラグメントの問題

次のエラーが表示されます:メソッドgetApplicationContext()は未定義ですメソッドfindViewById(int)はタイプFragment1に対して未定義です

これらのエラーは、クラスがフラグメントに対抗するアクティビティに拡張されると解消されるようですが、このアクティビティがフラグメントのままであることが重要です。

どんな助けも大歓迎です。前もって感謝します。

以下はコードです

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

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();

更新

アクティビティを起動すると、次のメッセージが表示されました。

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

以下は、フラグメントを呼び出すアクティビティページです

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);
    }
}

更新2以下は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

getActivity()を使用して、フラグメントを含むアクティビティを取得できます。

したがって、getActivity().getApplicationContext()は機能します。

getActivity().findViewById(int)も機能します。

ただし、getActivity()の前にonActivityCreated()を使用しないでください。それより前にnullを返すためです。

68
Eran

変化する

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

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