片段中的onPostExecute输出

时间:2019-03-08 12:31:47

标签: java android android-fragments android-asynctask

我有一个工作正常的AsyncTask,用于从服务器获取数据并将其显示在TextView中。但是是否可以将数据输出到位于片段中的TextView中?因此,假设AsyncTask已加载到MainActivity中,并且输出将在一个片段中。

这是我的AsyncTask:

 private static class FtpDownload extends AsyncTask<String, String, String> {

        private WeakReference<GuidanceActivity> activityWeakReference;

        FtpDownload(GuidanceActivity activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

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

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

            GuidanceActivity activity = activityWeakReference.get();
            if (activity == null || activity.isFinishing()) {
                return null;
            }

            try {
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect("", 21);
                System.out.println(ftpClient.getReplyString());

                ftpClient.enterLocalPassiveMode();
                ftpClient.login("anonymous", "");
                ftpClient.changeWorkingDirectory("/");

                InputStream inStream = ftpClient.retrieveFileStream(".html");

                activity.contents = IOUtils.toString(inStream, StandardCharsets.UTF_8);
                System.out.println(activity.contents);

                ftpClient.disconnect();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String output) {

            GuidanceActivity activity = activityWeakReference.get();
            if (activity == null || activity.isFinishing()) {
                return;
            }
            TextView textView = activity.findViewById(R.id.text_view);
            textView.setText(Html.fromHtml(activity.contents));
        }
    }

2 个答案:

答案 0 :(得分:0)

是的,有可能。这是MainActivity进行WiFi扫描的示例,结果显示为片段。我相信您可以理解其逻辑并将其转换为您的项目

MainActivity:

public class MainActivity extends AppCompatActivity implements FragmentDiscoverWiFi.ScanWiFi;

//public variable
FragmentDiscoverWiFi fragmentDiscoverWiFi;

//This will be called from your fragment
@Override
public void onScanWiFi(FragmentDiscoverWiFi fragment) {
        fragmentDiscoverWiFi = fragment;
}

//use something like this when your want to update fragment
fragmentDiscoverWiFi.onScanWiFiComplete();

片段:

public class FragmentDiscoverWiFi extends Fragment {

    private Context mContext;
    public interface ScanWiFi {
        public void onScanWiFi(FragmentDiscoverWiFi fragment);
    }

    public FragmentDiscoverWiFi() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        mContext = context;
        super.onAttach(context);
    }

    public void onScanWiFiComplete() {
        if (!isDetached()) {
            //Access your data from MainActivity like this: 
        Log.d(TAG, "Total APs:" + ((MainActivity) mContext).wifiScanResults.size());
        }
    }

@Override
public void onResume() {
        super.onResume();

        if (!getUserVisibleHint()) {
            return;
        }
    pullToRefreshText = rootView.findViewById(R.id.pullToRefreshText);
        pullToRefresh = rootView.findViewById(R.id.pullToRefresh);
        pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                Log.d(TAG, "refreshing...");
                pullToRefresh.setRefreshing(true);
                ((MainActivity)mContext).onScanWiFi(FragmentDiscoverWiFi.this);
            }
        });
     }
}

答案 1 :(得分:0)

在您的片段中:

public class MyFragment extends Fragment { 
   TextView myTextView;

   @Nullable
   @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     super.onCreateView(inflater, container, savedInstanceState);
     View view = View root = inflater.inflate(R.layout.my_frag_layout, null);
     myTextView = (TextView) view.findViewById(R.id.myTextView);
     //rest of your implementation of onCreateView
     return view;
   }

   //this will be called from activity
   public void updateTextView(String text) { 
       myTextView.setText(text);          
   }

}

您的活动中:

public class MyActivity extends AppCompatActivity { 
   private final String FRAGMENT_TAG = "myFragment";

   private static class FtpDownload extends AsyncTask<String, String, String> {

    //rest of your FtpDownload class

    @Override
    protected void onPostExecute(String output) {

        GuidanceActivity activity = activityWeakReference.get();
        if (activity == null || activity.isFinishing()) {
            return;
        }
        MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG );
        /* or 
        MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment );
        if your fragment is in an xml layout */

        fragment.updateTextView(Html.fromHtml(activity.contents));
    }
  }

}