gpt4 book ai didi

java - 如何在doINBackground android中设置textview

转载 作者:行者123 更新时间:2023-12-02 03:14:23 25 4
gpt4 key购买 nike

我想要访问 postgresql 数据库,但我在使用 AsyncTaskdoInBackground 命令时遇到问题。我不知道为什么我无法在 onPostExecute 更新我的 TextView 。谁能解释一下有什么问题吗?这是我的代码:

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);
}

}

}

最佳答案

要在 doInBackground 中设置文本,您可以使用它。

runOnUiThread(new Runnable() {
@Override
public void run() {
txtView.setText("Message");
}
});

试试这个:

Updating TextView from Async Task which use custom program dialog

关于java - 如何在doINBackground android中设置textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40545442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com