如果我有一个扩展<asynctask>类的单独类,如何从onPostExecute()获取值?

时间:2015-11-18 20:47:10

标签: java android methods android-asynctask

我在获取AsyncTask类的onPostExecute()方法给出的值时遇到了问题,为什么它没有显示到textview?

CollegeBulletinListFragment.java

package com.example.navigationdrawerexample;


import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CollegeBulletinListFragment extends Fragment implements OnClickListener{
    public CollegeBulletinListFragment(){
    }

    TextView kem;
    TextView headlinehead;
    TextView shortdesc;
    TextView headlinesender;
    LinearLayout llist;
    ImageButton img;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_collegebulletinlist, container, false);


        headlinehead = (TextView) rootView.findViewById(R.id.headlinetitle);
        String c = getArguments().getString("passingWord");
        llist = (LinearLayout) rootView.findViewById(R.id.lllist);
        int colval = this.setTextAndColorsToHead(c);
        String firstFlag = "headline";

        String secondFlag = "list";
        Connector connect= new Connector(getActivity().getApplicationContext(),colval,secondFlag);
        connect.execute("");

        String txt = connect.getJSON();
        headlinehead.setText(txt);
        return rootView;
    }


    public int setTextAndColorsToHead(String arg){
        int collegeval = 0;
        if (arg.equals("GN")){
            kem.setText("General News");
        } else if (arg.equals("CCS")){
            kem.setText("College of Computer Studies");
            collegeval = 1;
        } else if (arg.equals("COE")){
            kem.setText("College of Engineering");
            collegeval = 2;
        } else if (arg.equals("COED")){
            kem.setText("College of Education");
            collegeval = 4;
        } else if (arg.equals("CON")){
            kem.setText("College of Nursing");
            collegeval = 3;
        } else if (arg.equals("CBA")){
            kem.setText("College of Business and Accountancy");
            collegeval = 5;
        } else if (arg.equals("CAS")){
            kem.setText("College of Arts and Sciences");
            collegeval = 6;
        } else if (arg.equals("CIHM")){
            kem.setText("College of International and Hospitality Management");
            collegeval = 7;
        } 
        return collegeval;
    }
}

这是扩展Connector的{​​{1}}类,在<AsyncTask>方法上,返回请求的字符串,我将字符串存储在onPostExecute变量中response方法,我为setJSON()创建了getJSON()方法,以便能够在CollegeBulletinListFragment中获取请求的字符串响应。

Connector.java

package com.example.navigationdrawerexample;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Connector extends AsyncTask<String,Void,String>{
    private Context context;
    private int collegeactive;
    private String flag;

    private String response;
    public Connector(Context context,int college, String flag){
        this.context = context;
        this.collegeactive = college;
        this.flag = flag;   
    }


    protected void onPreExecute(){
        //Toast.makeText(context, "Please Wait", Toast.LENGTH_LONG).show();
        //ProgressBar pb = new ProgressBar(this.context);
    }


    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub

        try{
            String link = "";
            if (flag ==  "headline"){
                link = "http://rtu-astronet.com/emag/functions.php?action=printHeadline&coll_id="+collegeactive;
            } else if (flag == "list"){
                link = "http://rtu-astronet.com/emag/functions.php?action=printArticlePerCollege&collegeid="+collegeactive+"&acadornot=1";
            }
            URL url = new URL(link);
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(link));
            HttpResponse response = client.execute(request);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";

            while ((line = in.readLine()) != null) {
                sb.append(line);
                //break;
            }

            in.close();
            return sb.toString();
        } catch(Exception e){
             return new String("Exception: " + e.getMessage());
        }
    }


    @Override
    protected void onPostExecute(String result) {
        result = "{ \n \"Data\": \n " + result + " \n }";
        this.setJSON(result);
    }


    private void setJSON(String result){
        this.response = result;
    }

    public String getJSON(){
        return this.response;
    }

}

但是,textview headlinehead中没有显示字符串响应,为什么会这样?有什么可能的解决方案?

2 个答案:

答案 0 :(得分:2)

你可以实现这个回调监听器。

public class Connector extends AsyncTask<String,Void,String>{
    private OnPostExecuteListener onPostExecuteListener;
     /**
     * The callback interface
     */
    public interface OnPostExecuteListener {
        void onPostExecute(String result);
    }

    public void setOnPostExecuteListener(OnPostExecuteListener listener){
        this.onPostExecuteListener = listener;
    }

    @Override
    protected void onPostExecute(String result) {
       result = "{ \n \"Data\": \n " + result + " \n }";
       if(onPostExecuteListener !=null){
             onPostExecuteListener.onPostExecute(result);
       }
       this.setJSON(result);
    }

}

在你的片段类中

public class CollegeBulletinListFragment extends Fragment implements OnClickListener, Connector.OnPostExecuteListener {

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       Connector connect= new Connector(getActivity().getApplicationContext(),colval,secondFlag);
       connect.setOnPostExecuteListener(this); // set callback listener
       connect.execute("");
   }

   @Override
   public void onPostExecute(String result){
      // do something with onPostExecute result.
   }

}

答案 1 :(得分:0)

您正在调用AsyncTask,它会在一个单独的线程上异步工作,然后希望立即得到答案。

这项工作需要一些时间,所以直到稍后才可用(可能在onCreateView完成之后)。