![](/img/trans.png)
[英]kotlin / java sharedPreferences meaning in android studio
[英]SharedPreferences Java Android Studio
我試圖在他們登錄/注冊時創建一個用戶會話,以便他們在關閉應用程序后自動進入應用程序。
我不斷收到此錯誤:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context
android.content.Context.getApplicationContext()' on a null object reference
at com.example.myapplication.BackgroundWorker.<init>(BackgroundWorker.java:32)
at com.example.myapplication.LoginActivity.OnLogin(LoginActivity.java:73)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener
我正在關注這個答案https://stackoverflow.com/a/11027631/14270746
我已經在 php 和 Java 中創建了登錄/注冊腳本,所以我試圖在我已經創建的代碼中實現這些東西。 我在我的 BackgroundWorker.Java 類中執行此操作。 我嘗試在我的 LoginActivity 中執行此操作,但遇到了同樣的錯誤。 有人能幫我嗎 ?
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx) {
context = ctx;
}
private SharedPreferences sharedpreferences;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
@Override
protected String doInBackground(String... params) {
String type = params [0];
String login_url = "http://192.168.1.37/byebye/login_handler.php";
String register_url = "http://192.168.1.37/byebye/register_handler.php";
if (type.equals("login")) {
try {
String username = params [1];
String pw = params [2];
editor.putString("username", String.valueOf(username));
editor.apply();
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"
+URLEncoder.encode("pw", "UTF-8")+"="+URLEncoder.encode(pw, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (type.equals("register")) {
try {
String name = params [1];
String username = params [2];
String email = params [3];
String pw = params [4];
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(name, "UTF-8")+"&"
+URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"
+ URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(email, "UTF-8")+"&"
+ URLEncoder.encode("pw", "UTF-8")+"="+URLEncoder.encode(pw, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Status");
}
@Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
Intent intent = new Intent(context.getApplicationContext(), ProfileActivity.class);
context.startActivity(intent);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
這是第一個錯誤行(BackgroundWorker.java:32):
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
這是第二個:
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
我的猜測是變量沒有保存到 sharedpref。
內聯變量初始值設定項在構造函數體運行之前被調用。 因此,當您嘗試初始化preferences
, context
的值仍然為 null,因為尚未調用構造函數。 將初始化程序放在文件中的構造函數之后並不重要,它仍然首先被調用。 您應該在構造函數內部初始化它。
此外,不要只保留對SharedPreferences.Editor
的引用。 需要時在本地創建它。
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
SharedPreferences preferences;
AlertDialog alertDialog;
BackgroundWorker(Context ctx) {
context = ctx;
preferences = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
}
@Override
protected String doInBackground(String... params) {
SharedPreferences.Editor editor = preferences.edit();
String type = params [0];
String login_url = "http://192.168.1.37/byebye/login_handler.php";
String register_url = "http://192.168.1.37/byebye/register_handler.php";
// ...
}
// ...
}
您應該在您的活動類中初始化您的SharedPreference
。 因為 AsyncTask 在后台工作。 因此,當您的應用程序關閉時,AsyncTask 仍然存在,但您的應用程序不在前台。 這就是getApplicationContext()
提供 null 的原因。 因此,為了防止此錯誤,請在活動onCreate()
方法中初始化SharedPreference
然后使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.