简体   繁体   中英

SharedPreferences Java Android Studio

I am trying to create a user session when they login/register so that they automatically go into the app when after they close it.

I keep on getting this error:

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

I'm following this answer https://stackoverflow.com/a/11027631/14270746

I already created the login/registration script in php and Java so I'm trying to implement this stuff inside of the code I already created. I'm doing this inside of my BackgroundWorker.Java class. I tried to do it inside of my LoginActivity but I was getting the same error. Can someone help me ?

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

}

This is the line of the first error(BackgroundWorker.java:32):

SharedPreferences preferences = 
PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());

And this is the second one:

BackgroundWorker backgroundWorker = new BackgroundWorker(this);

My guess is that the variables isn't saving to the sharedpref.

Inline variable initializers are called before the body of the constructor runs. So when you try to initialize your preferences , the value of context is still null because the constructor has not been called yet. It doesn't matter that you put the initializer after the constructor in your file, it still gets called first. You should initialize it in inside the constructor instead.

Also, do not just keep a reference to a SharedPreferences.Editor lying around. Create it locally when you need it.

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";
        // ...
    }
    
    // ...
}

You should initialize your SharedPreference in your activity class. Because of AsyncTask work in background. So when your app is close AsyncTask still alive but your application, not in the foreground. That's why getApplicationContext() provide null. So for preventing this error initialize SharedPreference in activity onCreate() method then use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM