我想在數據庫連接不成功時更改佈局。如何使用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。
調用'setContentView'在初審後通常是一個糟糕的主意。使用片段代替 –
如果您的應用程序崩潰,請[編輯]您的問題,包括logcat –
請提供代碼 –