在AsyncTask中使用android sharedpreference

时间:2016-10-08 19:41:10

标签: android android-asynctask sharedpreferences

我一直在使用php和MySQL开发网页多年,但我不熟悉Android项目的开发。我搜索并阅读了我之前发现的有关该主题的所有问题,但没有找到适用于我的项目的答案。目前,当我运行应用程序时,我得到的只是错误而且没有下载。我发布了我的主要活动的完整代码,并询问是否有人可以解释我做错了什么。 UserId的共享偏好中的数据是整数,日期/会话是数字字符串,电子邮件/地址是字符串

package com.example.logintest;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {


String IgidPreference = "IgidPreference";
String UserId = "userId";
String Date = "session";

//OR SHOULD THE DECLEARATION BE??
//public static final String UserId = "userId";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    new VerifyLogin().execute();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, Login.class);
            startActivity(intent);
        }
    });
}

public class VerifyLogin extends AsyncTask<String, Void, String> {

    Context ctx;
    SharedPreferences pref;

    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... arg0) {

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);


        if ((pref.contains(UserId)) && (pref.contains(Date))) {
        }
        String eaddress = arg0[0];
        String today = arg0[1];

        String link;
        String data;
        BufferedReader bufferedReader;
        String result;


        try {
            data = "?Email=" + URLEncoder.encode(eaddress, "UTF-8");
            data += "&Date=" + URLEncoder.encode(today, "UTF-8");
            link = "http://domain.com/verifylogin.php" + data;
            URL url = new URL(link);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            result = bufferedReader.readLine();
            return result;

        } catch (Exception e) {
            return new String("Exception: " + e.getMessage());
        }
    }
    @Override
    protected void onPostExecute(String result) {
        String jsonStr = result;

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                String userId = jsonObj.getString("user_id");
                String session = jsonObj.getString("session");
                String error_type = jsonObj.getString("error");
                String error_msg = jsonObj.getString("error_msg");

                if (error_type.equals("FALSE")) {
                    pref = context.getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putString(UserId, userId);
                    editor.putString(Date, session);
                    editor.apply();

                    Intent intent = new Intent(MainActivity.this, Account.class);
                    startActivity(intent);

                } else if (error_type.equals("TRUE")) {
                    Toast.makeText(context, error_msg, Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(context, error_msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
        }

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:1)

我知道自从发布主题以来已经有一段时间但是我不得不更换电脑,以及Android Studio并制作所有新项目。

以下是我发现处理原始问题的方法。我在代码中添加了注释,以帮助其他想要为下一个项目使用代码的人。

    public class LoginActivity extends Activity { //Standard Activity code

Button BtnLaunchSigninActivity; //Button to click 
private EditText etLoginUserName, etLoginPassword; // data to submit

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);


    etLoginUserName = (EditText) findViewById(R.id.etLoginUserName);
    etLoginPassword = (EditText) findViewById(R.id.etLoginPassword);

    BtnLaunchSigninActivity = (Button) findViewById(R.id.btnLoginSignin);


    BtnLaunchSigninActivity.setOnClickListener(onClickListener);
    }

private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btnLoginSignin) {
                    signin(v);
                }
            }
    };



public void signin(View v) {
    String userName = etLoginUserName.getText().toString();
    String passWord = etLoginPassword.getText().toString();

    Toast.makeText(this, "Signing In...", Toast.LENGTH_SHORT).show();
    new SignIn(this).execute(userName, passWord); // Send data to AsyncTask
}

private class SignIn extends AsyncTask<String, Void, String> {

    private Context context;  // context is for the SignIn()

    SignIn(Context context) {
        this.context = context;
    }

    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... arg0) {
        String userName = arg0[0];
        String passWord = arg0[1];

        String link;
        String data;
        BufferedReader bufferedReader;
        String result;

        try {
            data = "?username=" + URLEncoder.encode(userName, "UTF-8");
            data += "&password=" + URLEncoder.encode(passWord, "UTF-8");

            link = "url/login.php" + data;
            URL url = new URL(link);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();


            bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            result = bufferedReader.readLine();
            return result; // My php returns jsonobjects

        } catch (Exception e) {
            return new String("Exception: " + e.getMessage());
        }
    }


    @Override
    protected void onPostExecute(String result) {

        String jsonStr = result; //turn object into string
        if (jsonStr != null) {
            try {

                JSONObject jsonObj = new JSONObject(jsonStr);
                String status = jsonObj.getString("status");
                String userid = jsonObj.getString("uid");
                String hash = jsonObj.getString("security");

                Log.d("tag", jsonObj.toString(4));

                if (status.equals("Good")) {
                    Toast.makeText(context, "Sign In successful.", Toast.LENGTH_SHORT).show();

//YOU HAVE TO USE JSONSTR TO GET USERID AND SECHASH FOR UPDATING SHARED PREFERENCES
//DUE TO ANY POSSIBLE DELAYS OF PROCESSING doInBackground() SEND JSON TO NEXT ACTIVITY TO SET PREFERENCES
//ADD THE STRING TO THE INTENT BELOW, THEN PROCESS THE DATA FOR SETTING SHAREDPREFERENCES IN THE NEXT ACTIVITY

                    Log.d("UserID",userid);
                    Log.d("SecHash", hash);

                    Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                    Bundle extras = new Bundle();
                    extras.putString("USERID",jsonObj.getString("uid"));
                    extras.putString("SECHASH",jsonObj.getString("security"));
                    extras.putString("USERID","userid");
                    extras.putString("SECHASH","hash");
                    intent.putExtras(extras);
                    startActivity(intent);

                } else if (status.equals("Wrong")) {
                    Toast.makeText(context, "Username/Password is incorrect, could not be verified. Sign In failed.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
        }
    }
}

}

在下一个活动中,从意图中获取额外内容并将其添加到sharedPreferences中。这就是它的全部内容。

感谢大家以前的帮助。我希望这将有助于将来发现同样问题的其他人。

答案 1 :(得分:0)

doInBackground()中,您定义了一个区域设置变量,但使用了成员变量

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}

由于您只在pref分配onPostExecute(),因此您每次都会获得NullPointerExceptions。此外,ctx为空,甚至未声明context。因此,请确保尽早定义pref

public class VerifyLogin extends AsyncTask<String, Void, String> {

    private final SharedPreferences pref;

    VerifyLogin() {
        pref = getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
    }

    [...]
}

但最终你不应该像这样实现它。你会在这里泄露你的活动!