java - Android AsyncTask 无法运行

标签 java android multithreading asynchronous android-asynctask

我已经为我的 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() {

                        }
                    });

                }

            }

最佳答案

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

首先,您从后台Thread 调用startActivity,因此您需要向它添加一个Context。由于它是 Activity 的内部类,您可以使用

New_Login.this.startActivity(dashboard);

但是,您应该将数据返回到 onPostExecute() 并从那里启动 Activity

我看到的另一件事是您正在尝试从后台 Thread 更新 Views,这是不行的。您不应尝试在 doInBackground() 中更新它们。

您正在尝试错误地比较 String

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

应该是

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

看起来您是在 AsyncTask 中声明您的 View 但这应该在您的 Activity 中完成(最有可能在 onCreate()onResume()

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

我的建议是,去除您的 AsyncTask 并正确设置您的 Activity,然后实现您的 AsyncTask。并且一定要仔细阅读文档。

Activity Docs

AsyncTask Docs

关于java - Android AsyncTask 无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19127970/

相关文章:

java - 是否可以在java中将 secret 存储在堆栈上?

java - 执行多个 if else 语句的更有效方法

java - 错误 : Gradle: execution failed for task ':app:preDexDebug'

java - Java静态初始化器线程安全吗?

java - Spring 启动 : how to use multiple yml files

java - Twistd - Telnet - Python 服务器,Java 客户端,客户端在连接关闭之前永远不会接收字符串,此时所有字符串连接在一起并一起发送

java - 签名 android 应用程序抛出 IOException : Redundant length bytes found

android - 如何以编程方式检查手机是否支持 wifi?

c# - C#线程dataGridView和加载

c - POSIX 线程和信号掩码