尝试实现共享首选项时出错

时间:2016-03-28 20:12:44

标签: android sharedpreferences

编辑:我改变了

User user;
UserLocalStore userLocalStore;

为:

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

但现在我

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)

我正在使用登录/注册功能来管理应用程序并希望保存用户信息,以便在共享首选项的帮助下在导航器中显示它们但我无法添加它 这是我得到的错误

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) 

登录/注册发生的后台任务以及我尝试保存用户数据的位置:

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

    }

}

如果有任何事情发生,所有文件都在这个github中:https://github.com/serkserk/ComparateurL3F1

1 个答案:

答案 0 :(得分:0)

您需要初始化user对象。 你在这一行获得NullPointerException

user.setMail(mail);

因为用户是null