1

使用的教程链接:http ://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

问题是:我的应用程序有一个有效的登录和注册活动。但是,我想在用户单击登录/注册按钮以显示一些信息后提示一个警报对话框。

我按照上面的教程链接创建了 AlertDialogManager.java。这是我的登录按钮代码:

try{                                                
            int success = json.getInt(TAG_SUCCESS);
            //String message = json.getString(TAG_MESSAGE);
            //Log.v("SignUp", "Checkpoint 3");


            if (success == 1) {
                session.createLoginSession(email);

                Intent i = new Intent(getApplicationContext(), Home.class);
                startActivity (i);

                finish();
            }else{
                //failed to login                   
            }
        } catch (JSONException e){
            e.printStackTrace();
        }

当应用程序无法登录用户时,我尝试在该部分中添加 alertdialog 代码。我的 alertdialog 代码:

alert.showAlertDialog(Login.this,"Login failed", "Bla bla bla", false);

每当我尝试单击登录按钮时,整个应用程序都会崩溃并显示下面的 logcat:

05-15 10:08:55.641: W/dalvikvm(2338): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
05-15 10:08:55.701: E/AndroidRuntime(2338): FATAL EXCEPTION: AsyncTask #1
05-15 10:08:55.701: E/AndroidRuntime(2338): java.lang.RuntimeException: An error occured while executing doInBackground()
05-15 10:08:55.701: E/AndroidRuntime(2338):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-15 10:08:55.701: E/AndroidRuntime(2338): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我对 Android 编程还是很陌生><所以有人可以帮帮我吗?谢谢!告诉我你们还需要什么,我会把它贴在这里。

整个代码如下: public class Login extends Activity {

private ProgressDialog pDialog;

//Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();

//Session manager
SessionManager session;

JSONParser jsonParser = new JSONParser();
EditText C_Email;
EditText C_Password;

public static final String DOMAIN = "192.168.0.112"; //Home
//public static final String DOMAIN = "172.18.74.146";
//URL to login
private static String url_login = "http://" + DOMAIN + "/iChop/login.php";

//JSON Node names
private static final String TAG_SUCCESS = "success";
//private static final String TAG_MESSAGE = "message";

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

    //Session manager
    session = new SessionManager(getApplicationContext());

    //Edit Text
    C_Email = (EditText) findViewById(R.id.C_Email);
    C_Password = (EditText) findViewById(R.id.C_Password);

    Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();

    //Login button
    Button Login = (Button) findViewById(R.id.Login);

    //Button click event
    Login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // creating new customer in background
            new CustomerLogin().execute();
        }
    });

}


class CustomerLogin extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Logging you in!");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... args){
        String email = C_Email.getText().toString();
        String password = C_Password.getText().toString();

        //Building parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));

        /**
        Log.d("C_Email", email);
        Log.d("C_Password", password);
        **/

        //getting JSON object
        JSONObject json = jsonParser.makeHttpRequest(url_login, "POST", params);
        Log.v("SignUp", "Checkpoint 1");

        //check log cat for response
        Log.d("Create Response", json.toString());
        Log.v("SignUp", "Checkpoint 2");

        //check for success tag
        try{                                                
            int success = json.getInt(TAG_SUCCESS);
            //String message = json.getString(TAG_MESSAGE);
            //Log.v("SignUp", "Checkpoint 3");


            if (success == 1) {
                session.createLoginSession(email);

                Intent i = new Intent(getApplicationContext(), Home.class);
                startActivity (i);

                finish();
            }else{
                //failed to login

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

        return null;
    }

    protected void onPostExecute(String file_url){
        pDialog.dismiss();
    }
}

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

public void SignUp (View view) {
    Intent signup = new Intent (this, SignUp.class);
    startActivity(signup);
}
}
4

3 回答 3

1

看来您正在调用 Intent 和警报对话框doInBackground,您可能需要调用 Intent 或警报对话框OnPostExceute

尝试在您的 OnPostExecute 中执行此操作

if (success == 1) {
                session.createLoginSession(email);

                Intent i = new Intent(getApplicationContext(), Home.class);
                startActivity (i);

                finish();
            }else{
                alert.showAlertDialog(Login.this,"Login failed", "Bla bla bla", false);

            }

让我知道它是否有效。

于 2013-05-15T10:57:22.147 回答
0

这看起来像您从不是 UI 线程的线程(例如 AsyncTask)创建此对话框。对话框必须从 UI 线程显示。如果登录成功与否,让您的 AsyncTask 向其启动的 Activity 报告,然后显示您的 Dialog :)

编辑:您 AsyncTask 当前返回 aString但始终null如此,因此您显然不返回任何内容。让您 AsyncTask 返回一个“成功”的布尔值(无论登录是否成功)。更改CustomerLogin extends AsyncTask<String, String, String>CustomerLogin extends AsyncTask<String, String, Boolean>并返回登录成功的布尔值(而不是null String您现在所做的)。然后,您可以使用此 booleanonPostExecute再次在 UI 线程上运行,您可以从那里创建对话框。

于 2013-05-15T10:37:47.897 回答
0

使用此代码button.setOnClickListener()

Runnable runnable = new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() { // This thread runs in the UI
                    @Override
                    public void run() {
                         // Update the UI, call your asynctask
                    }
                });
            }
        };
        new Thread(runnable).start();
    }
于 2013-05-15T10:44:58.513 回答