1

我已经为我的 android 应用程序编写了一个登录功能,我想让它在 API 17 上运行,现在它在主线程异常上给出了一个网络,我知道你不能在主线程上进行网络操作,我玩过试图把线程放进去,但它似乎没有去。所以我现在正在尝试异步任务

任何帮助建议都会很棒

  package khs.studentsupport;

import java.util.HashMap;

import khs.supportapp.library.DatabaseHandler;
import khs.supportapp.library.UserFunctions;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class New_Login  extends Activity{


    // Progress Dialog
            private ProgressDialog pDialog;


            public String storedEmail="";
            public String stroedPW = "";

             boolean GCMFlag=false; 
             // Shared Preferences
            SharedPreferences pref;

            // Editor for Shared preferences
            Editor editor;

            // Context
            Context _context;

            // Shared pref mode
            int PRIVATE_MODE = 0;

            // Sharedpref file name
            private static final String PREF_NAME = "AndroidHivePref";

            // All Shared Preferences Keys
            private static final String IS_LOGIN = "IsLoggedIn";

            // User name (make variable public to access from outside)
            public static final String KEY_NAME = "name";

            // Email address (make variable public to access from outside)
            public static final String KEY_EMAIL = "email";

            // Constructor
            public void SessionManager(Context context){
                this._context = context;
                pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
                editor = pref.edit();
            }

            /**
             * Create login session
             * */
            public void createLoginSession(String name, String email){
                // Storing login value as TRUE
                editor.putBoolean(IS_LOGIN, true);

                // Storing name in pref
                editor.putString(KEY_NAME, name);

                // Storing email in pref
                editor.putString(KEY_EMAIL, email);

                // commit changes
                editor.commit();
            }   



            // Internet detector
            ConnectionDetector cd;


            AlertDialogManager alert = new AlertDialogManager();
            Button btnLogin;
            Button btnLinkToRegister;
            EditText inputEmail;
            EditText inputPassword;

            TextView loginErrorMsg;

            // JSON Response node names
            private static String KEY_SUCCESS = "success";
            //private static String KEY_ERROR = "error";
            //private static String KEY_ERROR_MSG = "error_msg";
            private static String KEY_UID = "uid";

            private static String KEY_STUDENT_ID = "studentUser";



            private static String KEY_CREATED_AT = "created_at";


             public HashMap<String, String> getUserDetails(){
                    HashMap<String, String> user = new HashMap<String, String>();
                    // user name
                    user.put(KEY_NAME, pref.getString(KEY_NAME, null));
                    //ID of student
                    user.put(KEY_STUDENT_ID, pref.getString(KEY_STUDENT_ID, null));


                    // user email id
                    user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

                    // return user
                    return user;
                }

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.login);




            }

            // Response from  Activity
            @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                // if result code 100
                if (resultCode == 100) {
                    // if result code 100 is received 
                    // means user edited/deleted product
                    // reload this screen again
                    Intent intent = getIntent();
                    finish();
                    startActivity(intent);
                }

            }

            /**
             * Background Async Task to Load all product by making HTTP Request
             * */
            class LoadAlldetails extends AsyncTask<String, String, String> {

                /**
                 * Before starting background thread Show Progress Dialog
                 * */
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(New_Login.this);
                    pDialog.setMessage("Logging you in. Please wait...");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
                }

                /**
                 * getting user details from url
                 * */
                protected String doInBackground(String... args) {

                    cd = new ConnectionDetector(getApplicationContext());

                    String storedEmail = Appconfig.stored_user_name.toString();
                    String stroedPW = Appconfig.stored_password.toString(); 
                    // Check if Internet present
                    if (!cd.isConnectingToInternet())
                    {

                        if((inputEmail.toString()==storedEmail)&&(inputPassword.toString()==stroedPW))
                        {
                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);

                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(dashboard);
                        }


                    }

                    // Importing all assets like buttons, text fields
                  inputEmail = (EditText) findViewById(R.id.loginEmail);
                  inputPassword = (EditText) findViewById(R.id.loginPassword);

                  //Auto fill for login only if the user has logged in before 
                    if((Appconfig.stored_user_name.length()>0)&&(Appconfig.stored_password.length()>0))
                    {
                        inputEmail.setText(Appconfig.stored_user_name.toString());
                        inputPassword.setText(Appconfig.stored_password.toString());



                    }


                    // Importing all assets like buttons, text fields

                    btnLogin = (Button) findViewById(R.id.btnLogin);
                    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
                    loginErrorMsg = (TextView) findViewById(R.id.login_error);


                    // Login button Click Event
                    btnLogin.setOnClickListener(new View.OnClickListener() {

                        public void onClick(View view) {

                            new LoadAlldetails().execute();

                            String email = inputEmail.getText().toString();

                            String password = inputPassword.getText().toString();
                            UserFunctions userFunction = new UserFunctions();
                            Log.d("Button", "Login");
                            JSONObject json = userFunction.loginUser(email, password);





                            //Check to see if user has put in details 
                            if ((email.matches("")||(password.matches(""))))
                            {
                            loginErrorMsg.setText("Please enter your details ");
                            }

                            else
                            {    //Checks to see if first time in the app
                                // launces gcm activity
                                 if (Appconfig.GCMactivity == false) {
                                     Intent intent = new Intent();
                                     intent.setClass(getApplicationContext(),RegisterForGCMActivity.class);
                                     startActivity(intent);
                                     //set to true so GCm register wont show again
                                     Appconfig.GCMactivity=true;



                                     }
                                 else{
                            // check for login response
                            try {
                                if (json.getString(KEY_SUCCESS) != null) {
                                    loginErrorMsg.setText("");
                                    String res = json.getString(KEY_SUCCESS); 
                                    if(Integer.parseInt(res) == 1){
                                        // user successfully logged in
                                        // Store user details in SQLite Database
                                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                                        JSONObject json_user = json.getJSONObject("user");
                                        Appconfig.stored_user_name=json_user.getString(KEY_EMAIL);
                                        Appconfig.stored_password = password;




                                        if(Appconfig.email_is_set==false)
                                        {
                                            Appconfig.student_ID =  json_user.getString(KEY_STUDENT_ID);
                                        }
                                        Appconfig.email_is_set=true;

                                        // Clear all previous data in database
                                        userFunction.logoutUser(getApplicationContext());
                                        db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        


                                        // Launch Dashboard Screen
                                        Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);

                                        // Close all views before launching Dashboard
                                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        startActivity(dashboard);

                                        // Close Login Screen
                                        finish();


                                    }else{
                                        // Error in login
                                        loginErrorMsg.setText("Incorrect username/password");
                                    }
                                }




                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        }}});
                       GCMFlag = true;


                    // Link to Register Screen
                    btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

                        public void onClick(View view) {
                            Intent i = new Intent(getApplicationContext(),
                                    RegisterActivity.class);
                            startActivity(i);
                            finish();
                        }
                    });
                    return null;
                }

                public boolean isLoggedIn(){
                    return pref.getBoolean(IS_LOGIN, false);
                }
            }



                /**
                 * After completing background task Dismiss the progress dialog
                 * **/
                protected void onPostExecute(String file_url) {
                    // dismiss the dialog after getting user details
                    pDialog.dismiss();
                    // updating UI from Background Thread
                    runOnUiThread(new Runnable() {
                        public void run() {

                        }
                    });

                }

            }
4

1 回答 1

1

到目前为止我看到很多,所以我会让你知道这些,但知道可能还有更多。

首先,您startActivity从后台调用,Thread因此您需要添加一个ContextActivity因为它是你可以使用的内部类

New_Login.this.startActivity(dashboard);

但是,您应该返回数据onPostExecute()Activity从那里开始。

我看到的另一件事是,您正在尝试从不可以Views的背景进行更新。Thread您不应该尝试在doInBackground().

您正在尝试String错误地比较 s

if((inputEmail.toString()==storedEmail)&&(inputPassword.toString()==stroedPW))

它应该是

if((inputEmail.toString().equals(storedEmail))&&(inputPassword.toString().equals(stroedPW)))

看起来您正在声明您View的 s ,AsyncTask但这应该在您的Activity(很可能在onCreate()or中完成) onResume()

getApplicationContext()除非绝对必要,否则不要使用。在onClick()您可以使用v.getContext()的内部和在您的内部Activity但在您可以使用的侦听器外部ActivitiyName.this(那里有更多选项,但我暂时保持简单)。

我的建议,AsyncTask去掉你的Activity并正确设置,然后实施你的AsyncTask. 并且一定要仔细阅读文档。

活动文件

AsyncTask 文档

于 2013-10-02T00:08:21.483 回答