2012-04-24 25 views
0

我想中斷另一個線程2的線程1,但是當我嘗試使thread1.interrupt();調用時,我得到一個空指針錯誤。我正在一個Android登錄頁面上,當我登錄時,我創建並啓動了一個名爲sessionTimer(它進行會話倒計時2分鐘)的線程。我想要的是,當我按下不同的活動註銷時,我會進入登錄頁面,並且我的sessionTimer線程應該被中斷,以便我可以用最長時間啓動一個新的登錄會話。想要中斷一個線程,但線程爲空

package com.AndroidApp.Login; 

import java.security.GeneralSecurityException; 
import java.security.MessageDigest; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.NodeList; 

import android.app.Activity; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.media.MediaPlayer; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

import com.AndroidApp.R; 
import com.AndroidApp.domain.Utente; 
import com.AndroidApp.pagine.MenuPagina; 


public class LoginActivity extends Activity { 

    final String TAG = "LogIN"; 
    ArrayList<HashMap<String, String>> mylist; 

    private Button bLogin, bExit; 
    private EditText utente, passwd; 
    private MediaPlayer mpButtonClick = null; 
    private SharedPreferences mPreferences; 
    public volatile Thread sessionTimer; 
    public long tId = -1; 

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

     mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE); 

     SharedPreferences.Editor editor = mPreferences.edit(); 
     editor.clear(); 
     editor.commit(); 

     String nome = mPreferences.getString("nome", "Nessuno"); 
     setTitle("Sessione di : " + nome); 
     Log.w("TotThreads", Integer.toString(Thread.activeCount())); 
     /* 
     final SessionTimer st = new SessionTimer(); 
     */ 
     if(MenuPagina.reset){ 

      Log.w("sessionTimer ID", Long.toString(sessionTimer.getId())); 
      if (sessionTimer == null) 
       Log.w("sessionTimer", "sessionTimer is NULL"); 
      sessionTimer.interrupt(); 
      System.out.println("end current session"); 

      //st.stopRequest(); 
     } 

     if (!checkLoginInfo()) { 

      mpButtonClick = MediaPlayer.create(this, R.raw.button); 

      bLogin = (Button)findViewById(R.id.bLogin); 
      bLogin.setOnClickListener(new View.OnClickListener() { 

       public void onClick(View view) { 

        mpButtonClick.start(); 

        Log.v(TAG, "Trying to Login"); 
        utente = (EditText)findViewById(R.id.etUtente); 
        passwd = (EditText)findViewById(R.id.etPassword); 

        String username = utente.getText().toString(); 
        username = ("[email protected]"); 
        String password = md5(passwd.getText().toString()); 
        password = md5("12345"); 

        XMLFunctionsLogin.getInstance().setNewURL("u=" + username + "&p=" + password); 
        String xml = XMLFunctionsLogin.getXML(); 
        Document doc = XMLFunctionsLogin.xmlFromString(xml); 
        int status = XMLFunctionsLogin.errStatus(doc); 

        Log.v("status", Integer.toString(status)); 
        if ((status == 0)) { 
         NodeList nodes = doc.getElementsByTagName("login"); 
         Element e = (Element) nodes.item(0); 
         Utente utente = new Utente(); 
         utente.setIdUtente(XMLFunctionsLogin.getValue(e, "idUtente")); 
         utente.setNome(XMLFunctionsLogin.getValue(e, "nome")); 
         utente.setCognome(XMLFunctionsLogin.getValue(e, "cognome")); 
         Log.v("utente", utente.getCognome().toString()); 

         List<NameValuePair> nvps = new ArrayList<NameValuePair>(2); 
         nvps.add(new BasicNameValuePair("utente", username)); 
         nvps.add(new BasicNameValuePair("password", password)); 
         Log.v(TAG, nvps.get(0).toString()); 
         Log.v(TAG, nvps.get(1).toString()); 

         // Store the username and password in SharedPreferences after the successful login 
         SharedPreferences.Editor editor = mPreferences.edit(); 
         editor.putString("userName", username); 
         editor.putString("password", password); 
         editor.putString("idUtente", utente.getIdUtente()); 
         editor.putString("nome", utente.getNome()); 
         editor.putString("cognome", utente.getCognome()); 
         editor.commit(); 


         Log.v(TAG, "timer"); 
         Log.v("RESET", Boolean.toString(MenuPagina.reset)); 

         /* 
         Thread t = new Thread(st); 
         t.start(); 
         */ 




         sessionTimer = new Thread() { 
          @Override 
          public void run() { 
           long tId = Thread.currentThread().getId(); 
           Log.w("TTthread Id", Long.toString(tId)); 
           for (int i = 30; i >= 0; i -= 1) { 
            if ((i == 0) || (MenuPagina.reset)) { 
             System.out.print("timer finito"); 
             Log.i("Timer", "timer finito"); 
             LoginActivity.this.runOnUiThread(new Runnable() { 
              public void run() { 
               Toast.makeText(LoginActivity.this, "ti si è scaduta la sessione", Toast.LENGTH_LONG).show(); 
              } 
             }); 
             Intent intent = new Intent(getApplicationContext(), LoginActivity.class); 
             intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
             startActivity(intent); 
             //System.exit(0); 
            } try { 
             Thread.sleep(1000); 
             Log.i("Timer", Integer.toString(i)); 
            } catch (InterruptedException e) { 
             Log.i("Catch", "Catchhhhhhhhhhhh"); 
             e.printStackTrace(); 
             Thread.currentThread().interrupt(); 
             return; 

            } 
           } 
          } 

         }; 
         sessionTimer.start(); 


         Log.v(TAG, "Successo2"); 

         Toast.makeText(LoginActivity.this, "LogIn con successo", Toast.LENGTH_SHORT).show(); 
         Intent intent = new Intent(getApplicationContext()/*LoginActivity.this*/, MenuPagina.class); 
         startActivity(intent); 

        } else { 
         final String errorMessage = XMLFunctionsLogin.errStatusDesc(doc); 
         Log.v("fallimento", errorMessage); 
         LoginActivity.this.runOnUiThread(new Runnable() { 
          public void run() { 
           Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_LONG).show(); 
          } 
         }); 

         Intent intent = getIntent(); 
         finish(); 
         startActivity(intent); 
        } 
       } 

      }); 

      bExit = (Button)findViewById(R.id.bExit); 
      bExit.setOnClickListener(new View.OnClickListener() { 

       public void onClick(View view) { 
        mpButtonClick.start(); 
        finish(); 
       } 
      }); 
     } 
    } 

    //Checking whether the username and password has stored already or not 
    private final boolean checkLoginInfo() { 
      boolean username_set = mPreferences.contains("UserName"); 
      boolean password_set = mPreferences.contains("PassWord"); 
      if (username_set || password_set) { 
       return true; 
      } 
      return false; 
    } 

    //md5 for crypting and hash 
    private static String md5(String data) { 
     byte[] bdata = new byte[data.length()]; 
     int i; 
     byte[] hash; 

     for (i = 0; i < data.length(); i++) 
      bdata[i] = (byte) (data.charAt(i) & 0xff); 

     try { 
      MessageDigest md5er = MessageDigest.getInstance("MD5"); 
      hash = md5er.digest(bdata); 
     } catch (GeneralSecurityException e) { 
      throw new RuntimeException(e); 
     } 

     StringBuffer r = new StringBuffer(32); 
     for (i = 0; i < hash.length; i++) { 
      String x = Integer.toHexString(hash[i] & 0xff); 
      if (x.length() < 2) 
       r.append("0"); 
      r.append(x); 
     } 
     return r.toString(); 
    } 
} 

所以會發生什麼是當我退出,我回到登錄頁面,MenuPagina.reset = true我得到一個錯誤說sessionTimer爲空。爲什麼?

我試過也使用一個單獨的類的線程,但我得到相同的空指針錯誤。

回答

0

onCreate正在創建或重新創建,無論哪種方式,這是一個新的對象,你的活動時運行,所以任何局部變量都需要重新初始化,你的情況sessionTimer將是空,直到new Thread() {}電話。

如果您需要堅持引用您的線程,請使用比您的Activity更多的全局對象 - 應用程序,這是維護全局應用程序狀態的基類。您可以隨時致電Context.getApplicationContext()進行訪問。無論如何,請閱讀the docs

+0

@Vladmir我該如何堅持我的線程參考我的上下文?我編輯了我的原始問題,顯示整個LoginActivity。我非常感激我向你展示了我。謝謝 – Pheonix7 2012-04-24 13:33:36

+0

只要擴展'Application'類,比如說你命名爲'MyApplication'就給它添加一個私有字段:'private volatile Thread sessionTimer;',爲這個字段添加getter和setter,然後你可以在你的代碼中的任何地方執行以下操作:((MyApplication)getApplicationContext())。getSessionTimer()' – 2012-04-24 13:41:32

+0

我的類已經擴展了Activity,當我嘗試建議時,我做了這個((LoginActivity)getApplicationContext())。getSessionTimer()。interrupt() ;我得到一個classCastException。 – Pheonix7 2012-04-24 14:02:33