我想在数据库连接失败时更改布局。
我在考虑执行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 :(得分:0)
您应该以这种方式更新您的用户界面:
Runnable r = new Runnable() {
public void run() {
// here update UI methods
}
};
runOnUiThread(r);
答案 1 :(得分:0)
如果要使用AsynkTask更新视图,则应该在方法onPostExecute()中进行,因为方法doInBackGround performed in other thread