2017-06-10 75 views
0

我想在數據庫連接不成功時更改佈局。如何使用AsyncTask更改同一活動的佈局?

我在考慮執行setContentView(R.layout.no_connection); 每當從doInBackground();方法拋出異常,但它不工作,我的應用程序崩潰。

class Connect extends AsyncTask <String, Void, String> { 

     private Exception exception; 

     TextView tv = (TextView) findViewById(R.id.textView); 
     String result = ""; 

     public Connect(TextView tv) { 
      this.tv = tv; 
     } 

     protected String doInBackground(String... urls) { 

      try { 

       // StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
       // StrictMode.setThreadPolicy(policy); 
       final String url = "jdbc:mysql://192.168.1.4:3308/demo"; //192.168.43.137:3308 
       final String user = "Vishal"; //testUser 
       String pass = "password"; //test 

       Class.forName("com.mysql.jdbc.Driver"); 
       Connection conn = DriverManager.getConnection(url, user, pass); //(urls[0], urls[1], urls[2]) 

       Statement st = conn.createStatement(); 
       ResultSet rs = st.executeQuery("SELECT * from user_info"); 
       ResultSetMetaData rand = rs.getMetaData(); 

       while(rs.next()){ 
        result += rs.getInt(1)+" " + rs.getString(2)+" " + rs.getString(3)+"\n " ; 
       } 
       //Toast.makeText(MainActivity.this, "Connection Successful", Toast.LENGTH_LONG).show(); 

       //result = "Database Connection Success\n"; 
       //Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show(); 
       return result; 

      } catch (Exception e) { 
       this.exception = e; 


       //Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show(); 

       return e.toString(); 
      } 
     } 

     protected void onPostExecute(String feed) { 
      // TODO: check this.exception 
      // TODO: do something with the feed 
      if(result == null){ 
       Toast.makeText(MainActivity.this, "Result null", Toast.LENGTH_SHORT).show(); 

      } 
      if(feed == null){ 
       Toast.makeText(MainActivity.this, "feed null", Toast.LENGTH_SHORT).show(); 


      } 
      tv.setText(feed); 

      Toast.makeText(MainActivity.this, "Connection Successful", Toast.LENGTH_LONG).show(); 
     } 


    } 

    ; 

我叫它使用abc = new Connect(tv).execute(url).toString(); 有沒有更好的方式來做到這一點的主UI線程?請建議,我是一個noobie。

+0

調用'setContentView'在初審後通常是一個糟糕的主意。使用片段代替 –

+0

如果您的應用程序崩潰,請[編輯]您的問題,包括logcat –

+0

請提供代碼 –

回答

0

你應該更新你的用戶界面是這樣的:

Runnable r = new Runnable() { 
    public void run() { 
     // here update UI methods 
    } 
}; 
runOnUiThread(r); 
+0

爲什麼? 'onPostExecute' **在UI線程上爲** –

+0

也許提供您的代碼然後 –

+0

這不是我的問題......您應在回答之前評論以上 –

0

如果你想使用AsynkTask更新你的看法,你應該這樣做的方法onPostExecute(),因爲方法doInBackGround performed in other thread

+0

我只想在互聯網連接失敗時更改佈局,我檢查在doInBackground (),應該在哪裏做什麼代碼? –

+0

你如何檢查互聯網連接? – Oleg