2013-04-10 129 views
1

以下是我的LoginActivity的代碼,其中我基本上從AsyncTask從URl 獲得JSON和圖像。奇怪的是,我的onClick()的其他部分總是執行(即吐司顯示)。只有再次單擊該按鈕,它纔會跳轉到下一個活動。按鈕需要點擊兩次異步任務完成加載

public class LoginActivity extends Activity 
{ 

    Button getBunks; 
    CheckBox detailscheck; 
    EditText regText, bdayText; 
    String storedReg, storedBDay; 
    public static final String PREFS_NAME = "MyPrefsFile"; 
    String predataURL; 
    String prephotoURL; 
    public static URL dataUrl; 
    public static String dataUri = "http://ankit.im/websisAPI/parser.php"; 
    ProgressDialog progressDialog; 
    JSONObject temp = null; 
    Bitmap tmpPhoto; 
    boolean doneFlag = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     getBunks = (Button) findViewById(R.id.getBunkButton); 
     detailscheck = (CheckBox) findViewById(R.id.rememberOpts); 
     regText = (EditText) findViewById(R.id.regNo); 
     bdayText = (EditText) findViewById(R.id.bday); 
     detailscheck.setChecked(true); // To avoid Nag 

     try 
     { 
      dataUrl = new URL("http://ankit.im/websisAPI/parser.php"); 
     } catch (MalformedURLException e) 
     { 
      e.printStackTrace(); 
     } 

     // Check if login details are already stored 

     SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); 
     storedReg = prefs.getString("regno", null); 
     storedBDay = prefs.getString("bday", null); 

     // The Following Listeners Check if the user has entered 
     // appropriate Data in the Fields 
     // Check is on enter key press and on Focus Change 

     SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
     final SharedPreferences.Editor editor = settings.edit(); 

     regText.setOnFocusChangeListener(new OnFocusChangeListener() 
     { 

      @Override 
      public void onFocusChange(View v, boolean hasFocus) 
      { 
       if (detailscheck.isChecked()) 
       { 
        if (!hasFocus) 
        { 
         if (regText.getText().toString() != "" || regText.getText() != null) 
         { 
          editor.putString("regno", regText.getText().toString()); 
          editor.commit(); 
          // Toast.makeText(getApplicationContext(), 
          // "Reg No Stored", Toast.LENGTH_SHORT).show(); 
         } 
        } 

       } 
      } 
     }); 

     bdayText.setOnEditorActionListener(new OnEditorActionListener() 
     { 

      @Override 
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
      { 
       if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN 
         && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) 
       { 
        editor.putString("bday", bdayText.getText().toString()); 
        editor.commit(); 
        // Hide Virtual Keyboard 
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(regText.getWindowToken(), 0); 

        return true; 

       } 
       return false; 
      } 
     }); 

     bdayText.setOnFocusChangeListener(new OnFocusChangeListener() 
     { 

      @Override 
      public void onFocusChange(View v, boolean hasFocus) 
      { 
       if (detailscheck.isChecked()) 
       { 
        if (!hasFocus) 
        { 
         if (bdayText.getText().toString() != "" || bdayText.getText().toString() != null) 
         { 
          editor.putString("bday", bdayText.getText().toString()); 
          editor.commit(); 
          // Toast.makeText(getApplicationContext(), 
          // "BDay Stored", Toast.LENGTH_SHORT).show(); 
         } 
        } 

       } 
      } 
     }); 

     // Handle the button click 
     getBunks.setOnClickListener(new OnClickListener() 
     { 

      @Override 
      public void onClick(View v) 
      { 

       new DownloadStudentData().execute(); 

       if (doneFlag == true) 
       { 
        // GlobalVars.showAttendanceData(); 
        Intent actChange = new Intent(v.getContext(), DetailsTabViewActivity.class); 
        startActivity(actChange); 
        finish(); 
       } else if (doneFlag == false) 
       { 
        Toast.makeText(getApplicationContext(), "Error in Downloading, Please Check Details or Try Again", Toast.LENGTH_LONG).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.main, menu); 
     return true; 
    } 

    @Override 
    protected void onStart() 
    { 

     super.onStart(); 
     if (storedReg != null && storedBDay != null) 
     { 
      regText.setText(storedReg); 
      bdayText.setText(storedBDay); 
     } 

    } 

    private class DownloadStudentData extends AsyncTask<Void, Void, Void> 
    { 
     // ProgressDialog progressDialog; 
     final JSONParser jsp = new JSONParser(); 

     @Override 
     protected void onPreExecute() 
     { 
      // super.onPreExecute(); 
      progressDialog = new ProgressDialog(LoginActivity.this); 
      progressDialog.setCancelable(true); 
      progressDialog.setTitle(" Downloading Data "); 
      progressDialog.setMessage("Please Wait, Loading..."); 
      progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
      // progressDialog.setProgress(0); 
      progressDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... voids) 
     { 

      temp = new JSONObject(); 
      temp = jsp.getJSONFromUrl(dataUri); // get the data 
      prephotoURL ="http://218.248.47.9/websis/control/img/P12703.JPGimgId=P12703"; 

      try 
      { 
       InputStream in = new java.net.URL(prephotoURL).openStream(); 
       tmpPhoto = BitmapFactory.decodeStream(in); 
      } catch (Exception e) 
      { 
       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     protected void onPostExecute(Void v) 
     { 

      GlobalVars.setJSON(temp); 
      GlobalVars.setPhotoURL(prephotoURL); 
      GlobalVars.setBitmap(tmpPhoto); 
      doneFlag = true; 

      try 
      { 
       GlobalVars.setPhotoURL(temp.getString("photolink")); 
      } catch (JSONException e) 
      { 
       e.printStackTrace(); 
      } 

      progressDialog.dismiss(); 
     } 
    } 

    @Override 
    protected void onPause() 
    { 
     super.onPause(); 
     if (progressDialog != null) 
      progressDialog.dismiss(); 
    } 
} 

GlobalVars只是一個包含公共靜態變量和方法的全局類。

另外我不確定這是否是在後臺從URL下載圖片的正確方法,任何更好的替代方案將不勝感激(URLImageViewHelper不適合我的需要)。

+0

當你覺得''doneFlag''被分配值爲''True''價值,因爲你觸發的AsyncTask這會改變你的onClick方法? – harism 2013-04-10 19:34:14

回答

4

AsyncTask運行在不同的線程上,並且不會及時完成以更改doneFlag的值。 (這就是爲什麼它是異步的。)

new DownloadStudentData().execute(); // Takes time to complete 

if (doneFlag == true) { ... } // Happens milliseconds later, AsyncTask still running 
else if (doneFlag == false) { ... } 

您需要在onPostExecute()運行任何「完成」代碼。


一對夫婦快速提示:

  • if (doneFlag)if (doneFlag == true)簡寫。
  • 一個布爾值,只能有兩種狀態,你並不需要使用else if(),只需使用else {...}
+0

謝謝,將OnPostExecute方法中的Intent更改完美無缺! – Hav3n 2013-04-11 04:26:24

相關問題