我想访问一个 postgresql 数据库,但是我遇到了AsyncTask
和doInBackground
命令的问题。我不知道为什么我不能在onPostExecute
. 谁能解释我有什么问题?这是我的代码:
package com.example.armyhealthcare;
import java.sql.*;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
public class MainActivity extends Activity {
private static final String url = "jdbc:postgresql://elmer-02.db.elephantsql.com.5432/xyz";
private static final String user = "user";
private static final String pass = "pass";
private TextView firstname, lastname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstname = (TextView) findViewById(R.id.textfname);
lastname = (TextView) findViewById(R.id.textlname);
Button buttonload = (Button) findViewById(R.id.buttonload);
buttonload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new mytask().execute();
}
});
}
@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
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class mytask extends AsyncTask<Void, Void, Void>{
private String finame="";
private String laname="";
@Override
protected Void doInBackground(Void... arg0){
try{
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
Statement st = con.createStatement();
final ResultSet rs = st.executeQuery("select * from book");
rs.next();
finame= rs.getString(1);
laname= "Show Me";
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result){
firstname.setText("finame");
lastname.setText(laname);
super.onPostExecute(result);
}
}
}