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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果我有一个扩展的单独的类,如何从onPostExecute()获取值 类?相关的知识,希望对你有一定的参考价值。

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

college bulletin list fragment.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<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中没有显示字符串响应,为什么会这样?有什么可能的解决方案?

答案

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

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.
   }

}
另一答案

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

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

以上是关于如果我有一个扩展的单独的类,如何从onPostExecute()获取值 类?的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI - 如何从单独的类触发警报

从具有串联元素的类扩展

AsyncTask 作为一个单独的类

如何从 Android 4.3 中的类(此类扩展 LinearLayout)启动 Activity?

如何让 TypeScript 对扩展从“节点模块”导入的类感到满意?

如何使用新的导航架构组件从扩展 BroadcastReceiver 的类导航到片段