使用doInBackground的结果来设置textView

时间:2017-04-20 13:21:03

标签: java android android-asynctask

我是Android新手,我尝试使用php脚本与访问简单数据库的本地主机进行通信。 我在doInBackground()方法中定义了一个任务,该方法从存储在localhost上的数据库中获取一个值(我不知道该部分是否有效)。 我想使用doInBackground方法返回的结果在活动的textview中设置文本。

public class BackgroundWorker extends AsyncTask<String,Void,String> {

    Context context;


    BackgroundWorker(Context ctx)
    {
        context = ctx;
    }

    @Override
    protected String doInBackground(String... params) {
        String group = params[0];
        String child = params[1];
        String address = "http://10.0.2.2/conn.php";

        URL url = null;
        try {
            url = new URL(address);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("group", "UTF-8") + "=" + URLEncoder.encode(group, "UTF-8") + "&"
                    + URLEncoder.encode("child", "UTF-8") + "=" + URLEncoder.encode(child, "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result = "";
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {

        super.onPostExecute(s);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

活动类:

public class viewTT extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_tt);


        Button btnNextScreen = (Button) findViewById(R.id.button);
        TextView txtName = (TextView) findViewById(R.id.textView);
        TextView txtName2 = (TextView) findViewById(R.id.textView2);

        Intent i = getIntent();
        // Receiving the Data
        String group= i.getStringExtra("group");
        String child = i.getStringExtra("child");
        txtName.setText(group+" "+child);

        BackgroundWorker backgroundWorker = new BackgroundWorker(this);
         backgroundWorker.execute(group,child);



        btnNextScreen.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View arg0)
                    {
                //Starting a new Intent
                          Intent nextScreen = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(nextScreen);
                    }
         });
    }
}

我想设置txtName2。

3 个答案:

答案 0 :(得分:2)

您可以使用界面将数据返回到您的活动

<强>接口

    public interface AsyncResponse {
    public void onFinish(Object output);
}

SomeAsyncTask类

public class SomeAsyncTask extends AsyncTask<String, String, String> {
private AsyncResponse asyncResponse;

public SomeAsyncTask(AsyncResponse asyncResponse) {
    this.asyncResponse = asyncResponse;

}

@Override
protected String doInBackground(String... params) {

   //Do something 
    .....
   //Finally return something

   return "returnSomeString";
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    asyncResponse.onFinish(s);
}}

在您要设置视图的活动中,调用SomeAsyncTask类,如下所示

    SomeAsyncTask someAsyncTask=new SomeAsyncTask(new AsyncResponse() {
        @Override
        public void onFinish(Object output) {
            String result= (String) output;
            //Finally set your views
        }
    });
    someAsyncTask.execute();
}

答案 1 :(得分:0)

定义一个接口来获取backgroundworker的结果并使worker构造函数接受第二个参数,即interface.call上的接口对象在post上执行并将你的结果作为参数。比使用它:

BackgroundWorker backgroundWorker = new BackgroundWorker(this, new bgWorkerListener() {
            @Override
            public void onResult(String s) {
                txtname2.settext(s);
            }
        });
        backgroundWorker.execute(group, child);

答案 2 :(得分:-1)

这是主线程中的字符串

protected void onPostExecute(String s) {
    // s is your string 
    super.onPostExecute(s);
}
在您的BackgroundWorker类中

添加此代码...

  private String textFortxtName2;

public String getTextFortxtName2() {
    return textFortxtName2;
}

public void setTextFortxtName2(String textFortxtName2) {
    this.textFortxtName2 = textFortxtName2;
}

然后添加此

protected void onPostExecute(String s) {
// s is your string 
textFortxtName2 = s;
super.onPostExecute(s);

}

现在你可以获得主要活动的文本,

...
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(group,child);
txtName2.setText(backgroundWorker.getTextFortxtName2());

这就是全部:) 如果有任何问题或包请请注意