使用PreferenceFragment

时间:2017-09-09 12:56:55

标签: java android mysql android-volley preferencefragment

我试图制作一个用户可以登录并将用户数据保存到mysql-db的应用程序。 我使用PreferenceActivity和PreferenceFragment来处理这个问题。通常情况下,这可以正常工作,直到我改变用户...

  • 所以“用户A”更改PreferenceFragment中的值。比如他的城市。 (即“mainroad 1”)
  • 数据存储在SharedPrefs中并发送到Web。 -PreferenceScreen使用新数据进行更新。 - 一切都很好。
  • UserA更改下一个值,即他的电子邮件(userA@user.com)

现在,当用户A注销并且用户B登录时,会发生错误。(在注销时,使用clear()。和commit()清除共享首选项。)

  • 用户B从Web获取自己的数据
  • 数据在偏好设置屏幕中正确显示
  • 用户B也想更改他的电子邮件地址。
  • 现在,当我单击EditTextPreference项目时,可以看到来自UserA的旧EditTextPreference值(userA@user.com)(不知道这是否导致了错误)
  • UserB将其删除并输入新的电子邮件(userB@user.com)。

应用程序停止

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()'
on a null object reference
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java: 43)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java: 78)
at com.jamp.jamp.UserProfileSettingsFragment.onSharedPreferenceChanged(UserProfileSettingsFragment.java: 171)
at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners(SharedPreferencesImpl.java: 479)
at android.app.SharedPreferencesImpl$EditorImpl.apply(SharedPreferencesImpl.java: 387)
at android.preference.Preference.tryCommit(Preference.java: 1415)
at android.preference.Preference.persistString(Preference.java: 1448)
at android.preference.EditTextPreference.setText(EditTextPreference.java: 94)
at android.preference.EditTextPreference.onDialogClosed(EditTextPreference.java: 148)
at android.preference.DialogPreference.onDismiss(DialogPreference.java: 395)
at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java: 1337)
at android.os.Handler.dispatchMessage(Handler.java: 102)
at android.os.Looper.loop(Looper.java: 154)
at android.app.ActivityThread.main(ActivityThread.java: 6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 756)

现在这是片段的代码

package com.jamp.jamp;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by Erikken on 05.09.2017.
 */

public class UserProfileSettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
  SessionManager session;
  SharedPreferences prefs;

  String prefs_realname;
  String prefs_email;
  String prefs_streetname;
  String prefs_postcode;
  String prefs_city;
  String prefs_state;

  @Override
  public void onCreate(final Bundle savedInstanceState) {
    prefs = this.getActivity().getSharedPreferences("JampSharedPrefs", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = prefs.edit();
    PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(this);



    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.usersettings);

    session = new SessionManager(this.getActivity().getApplicationContext());


    HashMap < String, String > user = session.getUserDetails();
    final String sessionUsername = user.get(SessionManager.KEY_USERNAME);

    // ResponseListener um Request Nutzerdaten auszulesen.
    Response.Listener < String > UserDataResponseListener = new Response.Listener < String > () {
      @Override
      public void onResponse(String response) {
        try {
          JSONObject jsonResponse = new JSONObject(response);
          boolean success = jsonResponse.getBoolean("success");

          // Wenn Datenabfrage erfolgreich, JSONResponse auswerten. // If successful, import data from mysql database
          if (success) {
            String responseRealName = jsonResponse.getString("realname");
            if (responseRealName.equals("")) {
              responseRealName = getResources().getString(R.string.MissingRealName);
            }
            String responseEmail = jsonResponse.getString("email");
            if (responseEmail.equals("")) {
              responseEmail = getResources().getString(R.string.MissingEmail);
            }
            String responseStreetName = jsonResponse.getString("streetname");
            if (responseStreetName.equals("")) {
              responseStreetName = getResources().getString(R.string.MissingStreetName);
            }
            String responsePostcode = jsonResponse.getString("postcode");
            if (responsePostcode.equals("")) {
              responsePostcode = getResources().getString(R.string.MissingPostcode);
            }
            String responseCity = jsonResponse.getString("city");
            if (responseCity.equals("")) {
              responseCity = getResources().getString(R.string.MissingCity);
            }
            String responseState = jsonResponse.getString("state");
            if (responseState.equals("")) {
              responseState = getResources().getString(R.string.MissingState);
            }
            int responseAge = jsonResponse.getInt("age");
            int responseIsPremium = jsonResponse.getInt("isPremium"); // BOOLEAN

            // Add data to shared prefs
            editor.putString("realname", responseRealName);
            editor.putString("email", responseEmail);
            editor.putString("streetname", responseStreetName);
            editor.putString("postcode", responsePostcode);
            editor.putString("city", responseCity);
            editor.putString("state", responseState);
            editor.commit();

            prefs_realname = prefs.getString("realname", "");
            prefs_email = prefs.getString("email", "");
            prefs_streetname = prefs.getString("streetname", "");
            prefs_postcode = prefs.getString("postcode", "");
            prefs_city = prefs.getString("city", "");
            prefs_state = prefs.getString("state", "");

            Preference prefUserData = (Preference) findPreference("preferencescreen_userdata");
            prefUserData.setTitle(sessionUsername);
            prefUserData.setSummary(prefs_realname + "\n" +
              prefs_email + "\n" +
              prefs_streetname + "\n" +
              prefs_postcode + " " + prefs_city + "\n" +
              prefs_state);

            findPreference("settings_username").setTitle(sessionUsername);
            findPreference("settings_realname").setSummary(prefs_realname);
            findPreference("settings_email").setSummary(prefs_email);
            findPreference("settings_streetname").setSummary(prefs_streetname);
            findPreference("settings_postcode").setSummary(prefs_postcode);
            findPreference("settings_city").setSummary(prefs_city);
            findPreference("settings_state").setSummary(prefs_state);


          } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("Konnte Nutzerdaten nicht abrufen.")
              .setNegativeButton("Nochmal", null)
              .create()
              .show();
          }

        } catch (JSONException e) {
          e.printStackTrace();
        }

      }


    };
    // Request an userdatarequest.php senden / Send request to userdatarequest.php
    UserDataRequest userDataRequest = new UserDataRequest(sessionUsername, UserDataResponseListener);
    RequestQueue queue = Volley.newRequestQueue(this.getActivity());
    queue.add(userDataRequest);
  }

  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    HashMap < String, String > user = session.getUserDetails();
    final String sessionUsername = user.get(SessionManager.KEY_USERNAME);
    final String sessionPassword = user.get(SessionManager.KEY_PASSWORD);

    Context mContext = getActivity().getApplicationContext();

    Response.Listener < String > UpdateUserDataResponseListener = new Response.Listener < String > () {

      @Override
      public void onResponse(String response) {
        try {
          JSONObject jsonResponse = new JSONObject(response);
          boolean success = jsonResponse.getBoolean("success");

          if (success) {
            Toast.makeText(getActivity().getApplicationContext(), "Change Successful", Toast.LENGTH_LONG).show();
          } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("Konnte Nutzerdaten nicht abrufen.")
              .setNegativeButton("Nochmal", null)
              .create()
              .show();
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }


    };

    if (key.equals("settings_email")) { 
      // An mySQLDB senden         
      UpdateUserDataRequest updateUserDataRequest = new UpdateUserDataRequest(sessionUsername, sessionPassword, "email", sharedPreferences.getString(key, ""), UpdateUserDataResponseListener);
      RequestQueue queue = Volley.newRequestQueue(mContext);
      queue.add(updateUserDataRequest);

      // Summary sofort erneuern. // Refresh Summaries 

      prefs_email = sharedPreferences.getString(key, "");
      findPreference(key).setSummary(prefs_email);
      findPreference("preferencescreen_userdata").setSummary(prefs_realname + "\n" +
        prefs_email + "\n" +
        prefs_streetname + "\n" +
        prefs_postcode + " " + prefs_city + "\n" +
        prefs_state);

    }

// LOTS OF SIMILAR BUTTONS FOLLOWING HERE...


  }
}

因此,在重新启动用户后,错误只出现一次。 当它崩溃时,每当看起来重置时,应用程序重新启动,他可以随时更改他的任何数据。

我使用mContext变量错了吗? 是否有一些我不清楚可能会导致崩溃的遗留值?

任何提示? = /

1 个答案:

答案 0 :(得分:0)

好的,我明白了。找到一些有类似问题的其他线程。

我的Context mContext = getActivity().getApplicationContext();在OnPreferenceChange方法中被调用。但这似乎很早,因为片段中的onCreate方法还没有被调用,并且我的上下文应该指向没有活动,所以这将返回null。我将 mContext 变量移动到onCreate方法,从onPreferenceChange中删除了它(进行了一些其他调整以及...),现在onPreferenceChange似乎等待onCreate方法并且它完美地工作。

&#13;
&#13;
package com.jamp.jamp;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by Erikken on 05.09.2017.
 */

public class UserProfileSettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener
{
    SessionManager session;
    Context mContext;

    String prefs_realname;
    String prefs_email;
    String prefs_streetname;
    String prefs_postcode;
    String prefs_city;
    String prefs_state;

    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
        final SharedPreferences.Editor editor = prefs.edit();
        prefs.registerOnSharedPreferenceChangeListener(this);
        mContext = getActivity().getApplicationContext();

        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.usersettings);

        session = new SessionManager(getActivity().getApplicationContext());
        session.CheckLogin();

        HashMap<String,String> user = session.getUserDetails();
        final String sessionUsername = user.get(SessionManager.KEY_USERNAME);
        final String sessionPassword = user.get(SessionManager.KEY_PASSWORD);

        // ResponseListener um Request Nutzerdaten auszulesen.
        Response.Listener<String> UserDataResponseListener = new Response.Listener<String>(){
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");

                    // Wenn Datenabfrage erfolgreich, JSONResponse auswerten. // If successful, import data from mysql database
                    if (success) {
                        String responseRealName   = jsonResponse.getString("realname");     if (responseRealName.equals(""))   {responseRealName = getResources().getString(R.string.MissingRealName);}
                        String responseEmail      = jsonResponse.getString("email");        if (responseEmail.equals(""))      {responseEmail= getResources().getString(R.string.MissingEmail);}
                        String responseStreetName = jsonResponse.getString("streetname");   if (responseStreetName.equals("")) {responseStreetName = getResources().getString(R.string.MissingStreetName);}
                        String responsePostcode   = jsonResponse.getString("postcode");     if (responsePostcode.equals(""))   {responsePostcode = getResources().getString(R.string.MissingPostcode);}
                        String responseCity       = jsonResponse.getString("city");         if (responseCity.equals(""))       {responseCity = getResources().getString(R.string.MissingCity);}
                        String responseState      = jsonResponse.getString("state");        if (responseState.equals(""))      {responseState = getResources().getString(R.string.MissingState);}
                        int    responseAge        = jsonResponse.getInt   ("age");
                        int    responseIsPremium  = jsonResponse.getInt   ("isPremium"); // BOOLEAN

                        // Add data to shared prefs
                        editor.putString("realname",responseRealName);
                        editor.putString("email",responseEmail);
                        editor.putString("streetname",responseStreetName);
                        editor.putString("postcode",responsePostcode);
                        editor.putString("city",responseCity);
                        editor.putString("state",responseState);
                        editor.commit();

                        prefs_realname = prefs.getString("realname","0");
                        prefs_email = prefs.getString("email","0");
                        prefs_streetname = prefs.getString("streetname","0");
                        prefs_postcode = prefs.getString("postcode","0");
                        prefs_city = prefs.getString("city","0");
                        prefs_state = prefs.getString("state","0");

                        Preference prefUserData = (Preference) findPreference("preferencescreen_userdata");
                        prefUserData.setTitle(sessionUsername);
                        prefUserData.setSummary(prefs_realname+"\n"
                                                +prefs_email+"\n"
                                                +prefs_streetname+"\n"
                                                +prefs_postcode + " " + prefs_city +"\n"
                                                +prefs_state);

                        findPreference("settings_username").setTitle(sessionUsername);
                        findPreference("settings_realname").setSummary(prefs_realname);
                        findPreference("settings_email").setSummary(prefs_email);
                        findPreference("settings_streetname").setSummary(prefs_streetname);
                        findPreference("settings_postcode").setSummary(prefs_postcode);
                        findPreference("settings_city").setSummary(prefs_city);
                        findPreference("settings_state").setSummary(prefs_state);


                    }else{
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage("Konnte Nutzerdaten nicht abrufen.")
                                .setNegativeButton("Nochmal",null)
                                .create()
                                .show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }


        };
        // Request an userdatarequest.php senden / Send request to userdatarequest.php
        UserDataRequest userDataRequest = new UserDataRequest(sessionUsername, UserDataResponseListener);
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        queue.add(userDataRequest);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

        session = new SessionManager(mContext);
        HashMap<String,String> user = session.getUserDetails();
        final String sessionUsername = user.get(SessionManager.KEY_USERNAME);
        final String sessionPassword = user.get(SessionManager.KEY_PASSWORD);

        Response.Listener<String> UpdateUserDataResponseListener = new Response.Listener<String>(){

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");

                    if (success){
                        Toast.makeText(mContext,"Change Successful",Toast.LENGTH_LONG).show();
                    }else{
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage("Konnte Nutzerdaten nicht abrufen.")
                                .setNegativeButton("Nochmal",null)
                                .create()
                                .show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


        };

        if (key.equals("settings_email")){ // Adressenprüfung mussnoch implementiert werden.
            // An mySQLDB senden
                                                                                                  //CELLNAME                           // CELLVALUE
                     UpdateUserDataRequest updateUserDataRequest = new UpdateUserDataRequest(sessionUsername, sessionPassword, "email", sharedPreferences.getString(key, ""), UpdateUserDataResponseListener);
                     RequestQueue queue = Volley.newRequestQueue(mContext);
                     queue.add(updateUserDataRequest);
                     // Summary sofort erneuern. // Refresh Summaries instantly
                     prefs_email = sharedPreferences.getString(key, "");
                     findPreference(key).setSummary(prefs_email);
                     findPreference("preferencescreen_userdata").setSummary(prefs_realname + "\n"
                             + prefs_email + "\n"
                             + prefs_streetname + "\n"
                             + prefs_postcode + " " + prefs_city + "\n"
                             + prefs_state);

        }

        if (key.equals("settings_streetname")){
            UpdateUserDataRequest updateUserDataRequest = new UpdateUserDataRequest(sessionUsername,sessionPassword,"streetname",sharedPreferences.getString(key,""), UpdateUserDataResponseListener);
            RequestQueue queue = Volley.newRequestQueue(mContext);
            queue.add(updateUserDataRequest);
            // Summary sofort erneuern. // Refresh Summaries instantly
            prefs_streetname = sharedPreferences.getString(key,"");
            findPreference(key).setSummary(prefs_streetname);
            findPreference("preferencescreen_userdata").setSummary(prefs_realname+"\n"
                    +prefs_email+"\n"
                    +prefs_streetname+"\n"
                    +prefs_postcode + " " + prefs_city +"\n"
                    +prefs_state);
        }

        if (key.equals("settings_realname")){
            UpdateUserDataRequest updateUserDataRequest = new UpdateUserDataRequest(sessionUsername,sessionPassword,"realname",sharedPreferences.getString(key,""), UpdateUserDataResponseListener);
            RequestQueue queue = Volley.newRequestQueue(mContext);
            queue.add(updateUserDataRequest);
            // Summary sofort erneuern. // Refresh Summaries instantly
            prefs_realname = sharedPreferences.getString(key,"");
            findPreference(key).setSummary(prefs_realname);
            findPreference("preferencescreen_userdata").setSummary(prefs_realname+"\n"
                    +prefs_email+"\n"
                    +prefs_streetname+"\n"
                    +prefs_postcode + " " + prefs_city +"\n"
                    +prefs_state);
        }

        if (key.equals("settings_postcode")){
            UpdateUserDataRequest updateUserDataRequest = new UpdateUserDataRequest(sessionUsername,sessionPassword,"postcode",sharedPreferences.getString(key,""), UpdateUserDataResponseListener);
            RequestQueue queue = Volley.newRequestQueue(mContext);
            queue.add(updateUserDataRequest);
            // Summary sofort erneuern. // Refresh Summaries instantly
            prefs_postcode = sharedPreferences.getString(key,"");
            findPreference(key).setSummary(prefs_postcode);
            findPreference("preferencescreen_userdata").setSummary(prefs_realname+"\n"
                    +prefs_email+"\n"
                    +prefs_streetname+"\n"
                    +prefs_postcode + " " + prefs_city +"\n"
                    +prefs_state);
        }

        if (key.equals("settings_city")) {
            UpdateUserDataRequest updateUserDataRequest = new UpdateUserDataRequest(sessionUsername,sessionPassword,"city",sharedPreferences.getString(key,""), UpdateUserDataResponseListener);
            RequestQueue queue = Volley.newRequestQueue(mContext);
            queue.add(updateUserDataRequest);
            // Summary sofort erneuern. // Refresh Summaries instantly
            prefs_city = sharedPreferences.getString(key,"");
            findPreference(key).setSummary(prefs_city);
            findPreference("preferencescreen_userdata").setSummary(prefs_realname+"\n"
                    +prefs_email+"\n"
                    +prefs_streetname+"\n"
                    +prefs_postcode + " " + prefs_city +"\n"
                    +prefs_state);
        }
        if (key.equals("settings_state")) {
            UpdateUserDataRequest updateUserDataRequest = new UpdateUserDataRequest(sessionUsername,sessionPassword,"state",sharedPreferences.getString(key,""), UpdateUserDataResponseListener);
            RequestQueue queue = Volley.newRequestQueue(mContext);
            queue.add(updateUserDataRequest);
            // Summary sofort erneuern. // Refresh Summaries instantly
            prefs_state = sharedPreferences.getString(key,"");
            findPreference(key).setSummary(prefs_state);
            findPreference("preferencescreen_userdata").setSummary(prefs_realname+"\n"
                    +prefs_email+"\n"
                    +prefs_streetname+"\n"
                    +prefs_postcode + " " + prefs_city +"\n"
                    +prefs_state);
        }
    }
}
&#13;
&#13;
&#13;