- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试制作一个用户可以登录并将其用户数据保存到 mysql-db 的应用程序。我正在使用 PreferenceActivity 和 PreferenceFragment 来处理这个问题。通常这工作正常,直到我改变用户......
现在当用户 A 注销和用户 B 登录时发生错误。(共享首选项在注销时使用 clear() 和 commit() 清除..)
应用程序停止
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)
现在这是 fragment 的代码
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 变量错了吗?是否有一些我没有清除的剩余值会导致崩溃?
有什么建议吗? =/
最佳答案
好的,我知道了。发现其他一些有类似问题的线程。
我的 Context mContext = getActivity().getApplicationContext();
在 OnPreferenceChange 方法中调用。但这似乎还早,因为尚未调用 Fragment 中的 onCreate 方法,并且我的上下文应该指向的地方没有 Activity ,因此返回 null。我将 mContext 变量移至 onCreate 方法,将其从 onPreferenceChange 中删除(还进行了一些其他调整..),现在 onPreferenceChange 似乎在等待 onCreate 方法并且它运行良好。
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);
}
}
}
关于java - 使用 PreferenceFragment 时从 Volley 获取空指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130951/
我目前正在测试 Volley 库。但是当请求失败 (404) 时,它不会再次执行,或者至少没有错误。但是缺少数据。如果请求失败,这是重试请求的正确方法吗? 提前致谢 req.setRetryPolic
我是新来从事Volley和缓存工作的:P。尽管我已经看过许多与Volley进行图像缓存有关的文章和帖子,但是我仍然不清楚采用Volley进行图像缓存的最佳/首选方式。像磁盘缓存还是内存? Volley
我想使用 Volley 从我的 Android 应用发送请求。 我已经把它包含在 build.gradle 中了 dependencies { ... compile 'com.andr
我的目标是从另一个类调用 Volley,这是一种非常简洁、模块化的方式,即: VolleyListener newListener = new VolleyListener()
我的代码是: class MyService extends Service{ public void onCreate(){ new ImageLoader(mReque
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 4年前关闭。 Improve thi
我需要帮助来解决 Volley 库错误。我已使用 nodejs api 向服务器发送一些凭据以进行用户注册。在成功的情况下,当我的所有凭据对于创建新用户帐户都是唯一的时,它会向我显示所有响应等的所有内
我正在尝试完善我的应用程序中的错误处理,但我找不到 Volley 触发某些错误的集中位置以及原因。例如,我想知道如果我的请求的状态代码是 500 或更大,它肯定会触发 ServerError,但我似乎
当我在调试器中运行该方法时,数据按预期显示,但是每当我尝试使用它执行任何操作时,parentObject 的值都会返回为 null。 我只是想从服务器获取响应并将其存储为 JSONObject 以便在
我正在使用 Android Volley 缓存请求,这在我使用 GET 时工作正常,但由于某些原因我改用 POST。现在我想用不同的 POST 数据缓存相同的 URL。 请求 1 -> URL1,PO
我的情况是使用 Android-volley至 POST我的 json 对象,我可以成功发布所有内容,我的数据在服务器中可见,但服务器响应为 String不像 json ,这就是出现错误的原因。 co
我正在使用 volley 从 REST api 解析电影详细信息,并将解析的数据保存在名为 detailsMovies 的对象数组列表中。但是我无法在 onResponse 方法之外访问 ArrayL
我想知道如何解决这个问题。已完成代码的研究和替换,但问题仍然存在。 这是我使用 volley 的代码。 private void Regist(){ loading.setVisibility
如何创建一个单独的类,在其中定义所有关于 volley在另一个 Activity 中,我们直接传递 URL、CONTEXT 和 Get Response... 最佳答案 首先在Activity中创建回
我正在使用 volley 库并以 XML 格式获取响应。我想知道我们如何使用/volley 库解析响应。谢谢。 最佳答案 StringRequest req = new StringReque
当我在android studio中搜索 Volley 时,同时获取com.mcxiaoke.volley:library:1.0.19和com.mcxiaoke.volley:library-aar
我是 volley 和 android 的新手,我已经用 gradle 安装了 volley 并做了与官方教程相同的操作。但是没有响应,这意味着 Errorlistener 和 Responselis
当我在 Volley 中发出请求时,我收到 com.android.volley.ServerError 和响应代码 400。 我正在做这样的事情(通用示例代码): final String para
我引用了http://www.androidhive.info/2016/02/android-push-notifications-using-gcm-php-mysql-realtime-chat
当我将以下行添加到依赖项的 build.gradle 行时,Android Studio 显示此错误消息:compile 'com.android.volley:volley:1.0.0' apply
我是一名优秀的程序员,十分优秀!