0

Edit: i changed

User user;
UserLocalStore userLocalStore;

to:

User user = new User("","");
UserLocalStore userLocalStore = new UserLocalStore(ctx);

but now i get

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
                                                   at com.serk.comparateurL3F1.UserLocalStore.<init>(UserLocalStore.java:18)
                                                   at com.serk.comparateurL3F1.BackgroundTask.<init>(BackgroundTask.java:43)
                                                   at com.serk.comparateurL3F1.LoginActivity$2.onClick(LoginActivity.java:59)
                                                   at android.view.View.performClick(View.java:5565)
                                                   at android.view.View$PerformClick.run(View.java:22047)
                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                   at android.os.Looper.loop(Looper.java:148)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5849)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:763)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:653)

I'm makink an app with login/register feature and want to save the user information to show them in the navdrawer with the help of sharedpreference but i fail to add it This is the error i get

FATAL EXCEPTION: AsyncTask #1
                                             Process: com.serk.comparateurL3F1, PID: 6471
                                             java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                 at android.os.AsyncTask$3.done(AsyncTask.java:318)
                                                 at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                 at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                 at java.lang.Thread.run(Thread.java:803)
                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.serk.comparateurL3F1.User.setMail(java.lang.String)' on a null object reference
                                                 at com.serk.comparateurL3F1.BackgroundTask.doInBackground(BackgroundTask.java:117)
                                                 at com.serk.comparateurL3F1.BackgroundTask.doInBackground(BackgroundTask.java:34)
                                                 at android.os.AsyncTask$2.call(AsyncTask.java:304)
                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                                                 at java.lang.Thread.run(Thread.java:803) 

the backgroundtask where the login/register happen and where i try to save user data:

public class BackgroundTask extends AsyncTask<String, Void, String> {
    String register = "http://comparateur.16mb.com/register.php";
    String login = "http://comparateur.16mb.com/login.php";
    Context ctx;
    Activity activity;
    AlertDialog.Builder builder;
    ProgressDialog progressDialog;

    User user;
    UserLocalStore userLocalStore;

    public BackgroundTask(Context ctx){
    this.ctx = ctx;
    activity = (Activity)ctx;
    }

    @Override
    protected void onPreExecute() {
        builder = new AlertDialog.Builder(activity);
        progressDialog = new ProgressDialog(ctx);
        progressDialog.setTitle("Wait...");
        progressDialog.setMessage("Connection to server");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String method = params[0];

        if (method.equals("register")){
            try {
                URL url = new URL(register);
                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 mail = params[1];
                String name = params[2];
                String password = params[3];
                String data = URLEncoder.encode("mail", "UTF-8")+"="+URLEncoder.encode(mail, "UTF-8")+"&"+
                        URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(name, "UTF-8")+"&"+
                        URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String line = "";
                while ( (line=bufferedReader.readLine())!=null ){
                    stringBuilder.append(line+"\n");
                }
                httpURLConnection.disconnect();;
                Thread.sleep(5000);
                return  stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("login")){
            try {
                URL url = new URL(login);
                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 mail, password;
                mail = params[1];

                user.setMail(mail);

                password = params[2];
                String data = URLEncoder.encode("mail", "UTF-8")+"="+URLEncoder.encode(mail, "UTF-8")+"&"+
                        URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String line = "";
                while ( (line=bufferedReader.readLine())!=null ){
                    stringBuilder.append(line+"\n");

                }
                httpURLConnection.disconnect();;
                Thread.sleep(5000);
                return  stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String json) {
        try {
            progressDialog.dismiss();
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray =  jsonObject.getJSONArray("server_response");
            JSONObject jo = jsonArray.getJSONObject(0);
            String code = jo.getString("code");
            String message = jo.getString("message");
            if (code.equals("reg_true")){
                showDialog("Register succes", message, code);
            }
            else if (code.equals("reg_false")){
                showDialog("Register fail", message, code);
            }
            else if (code.equals("login_true")){

                user.setName(message);
                userLocalStore.storeUserData(user);

                Intent intent = new Intent(activity, MainActivity.class);
                intent.putExtra("message", message);
                activity.startActivity(intent);

            }
            else if (code.equals("login_false")){
                showDialog("Login fail", message, code);
            }

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

    }

    public void showDialog(String title, String message, String code){
        builder.setTitle(title);
        if (code.equals("reg_true") || code.equals("reg_false")){
            builder.setMessage(message);
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    activity.finish();
                }
            });

        }
        else if (code.equals("login_false")){
            builder.setMessage(message);
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    EditText mail, password;
                    mail = (EditText) activity.findViewById(R.id.lMail);
                    password = (EditText) activity.findViewById(R.id.lPassword);
                    mail.setText("");
                    password.setText("");
                    dialog.dismiss();
                }
            });

        }
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

}

If anything is mising, all the file are in this github: https://github.com/serkserk/ComparateurL3F1

Ggs
  • 81
  • 2
  • 11
  • Your user object is null, not initialised. – Abhishek Batra Mar 28 '16 at 20:18
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it). The initialization of at least both of `user` and `userLocalStore` is missing. – George Mulligan Mar 28 '16 at 20:18
  • @GeorgeMulligan I think i fixed it but i still get it, i dont understand why thought – Ggs Mar 28 '16 at 20:36

1 Answers1

0

You need to initialize the user object. You're getting a NullPointerException at this line

user.setMail(mail);

because user is null.

Dmitri Timofti
  • 2,428
  • 1
  • 22
  • 25
  • I think i fixed it but i still get it, i dont understand why thought – Ggs Mar 28 '16 at 20:37
  • try initializing your userLocalStore object inside the constructor like this: `public BackgroundTask(Context ctx){ this.ctx = ctx; userLocalStore = new UserLocalStore(ctx); activity = (Activity)ctx; }` – Dmitri Timofti Mar 28 '16 at 20:43
  • Thanks it's worked! i was also failing the test on mainactivity because i forget to set the user as logedIn in the SP – Ggs Mar 28 '16 at 21:28