2013-10-02 140 views
1

我已经为我的android应用程序写了一个日志功能,我想让它在API 17上工作,现在它在主线程异常上给出一个网络,我知道你不能对网络操作主线程中,我尝试将线程放入,但似乎没有去。所以,我现在Android AsyncTask不能正常工作

尝试了的AsyncTask任何帮助建议将是巨大

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

         } 
        }); 

       } 

      } 
+0

什么是您所遇到的问题? – codeMagic

+0

所以当我点击我的登录按钮时没有任何反应 –

+0

我没有看到你在哪里调用任务,所以请指出。我同时在回答中写了一些笔记。 – codeMagic

回答

1

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

首先,您从背景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))) 

它看起来像你宣布你的View在你AsyncTask但这应该在做你的Activity(最有可能在onCreate()onResume()

不要你除非绝对必要,否则请参阅getApplicationContext()。在onClick()的内部,您可以使用v.getContext()以及Activity的内部,但在听众的外部可以使用ActivitiyName.this(这里有更多选项,但现在我会保持这种简单)。

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

Activity Docs

AsyncTask Docs

+0

我会说在onPreExecute中创建一个对话框就好了吗? – cYrixmorten

+0

@cYrixmorten我在哪里说它不好? – codeMagic

+0

'看起来你是在你的AsyncTask中声明你的视图'..当我读到它时,也认为你也指这个。 – cYrixmorten