简体   繁体   中英

How to Set textview in doINBackground android

I want to access a postgresql database, but I have a problem with AsyncTask and doInBackground commands. I don't know why I can't update my textview at onPostExecute . Can anyone explain me what is the problem? Here is my code:

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

    }

}

To set text in doInBackground you can use this.

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

Try this:

Updating TextView from Async Task which use custom program dialog

You can use runOnUiThead() or set text in onPostExexute()

Example :

runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            tvText.setText("ABC");
                        }
                    });

Edited : Good Way :

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){
            super.onPostExecute(result);
            firstname.setText(finame);
            lastname.setText(laname);
        }

    }

Bad Way :

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";

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        firstname.setText(finame);
                        lastname.setText(laname);
                    }
                });

            }
            catch(Exception e){
                e.printStackTrace();

            }
            return null;

        }

        @Override
        protected void onPostExecute(Void result){
            super.onPostExecute(result);
        }

    }

set first name and last name like this

Pass the result or object from String doInBackground() to onPostExecute(String result)

Please follow the example.

From the doInBackground() method:

protected String doInBackground(Void... arg0){

         //Your code here
         return rs.getString(1);;
}

From the onPostExecute() method:

@Override
protected void onPostExecute(String result){
     super.onPostExecute(result);
     firstname.setText(result);
     lastname.setText("Show Me");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM