【问题标题】:Load fragment from ASync task从异步任务加载片段
【发布时间】:2015-06-25 22:44:21
【问题描述】:

我有一个异步任务,当加载数据时,它还会为星级栏设置 onClick。

当我用户点击星级评分栏时,我想加载一个新片段。我正在尝试这个:

package com.example.mike.beerportfoliomaterial;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mike on 6/22/15.
 */
public class getReviewToRateJSON extends AsyncTask<String, Void, String> {

    Context c;
    String noteWriter;
    String noteID;
    private ProgressDialog Dialog;

    public getReviewToRateJSON(Context context)
    {
        c = context;
        Dialog = new ProgressDialog(c);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Getting A Taste Note");

        Dialog.setTitle("Loading");
        Dialog.show();
    }

    protected void onPostExecute(String result){
        //decode json here
        try{
            JSONObject jsonObject = new JSONObject(result);

            noteWriter = jsonObject.getString("reviewer");
            String beer = jsonObject.getString("beer");
            noteID = jsonObject.getString("noteID");
            String noteToRead = jsonObject.getString("note");

            TextView note = (TextView) ((Activity) c).findViewById(R.id.reviewToRate);
            note.setText(noteToRead);







        }
        catch(Exception e){

        }


        //todo: url to send rating too

        addListenerOnRatingBar(c);

        Dialog.dismiss();

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

    private void addListenerOnRatingBar(final Context view) {
        RatingBar ratingBar = (RatingBar) ((Activity) view).findViewById(R.id.reviewRatingBar);

        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            public void onRatingChanged(RatingBar ratingBar, float rating,
                                        boolean fromUser) {

                //next async task to update online database
                float stars = ratingBar.getRating();

                String s = Float.toString(stars);
                //get user id
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
                String userName = prefs.getString("userName", null);
                final String userID = prefs.getString("userID", null);

                String url = "myURL;

                //async task to update rating in database
                new AddNoteRate(c).execute(url);



                Fragment Fragment_four;
                FragmentManager man= ((Activity) view).getSupportFragmentManager();
                FragmentTransaction tran = man.beginTransaction();
                Fragment_four = new RateReviews();
                tran.replace(R.id.main, Fragment_four);//tran.
                tran.addToBackStack(null);
                tran.commit();



            }
        });
    }

}

我的大问题是我无法让它在这些行上加载新片段:

Fragment Fragment_four;
                    FragmentManager man= ((Activity) view).getSupportFragmentManager();
                    FragmentTransaction tran = man.beginTransaction();
                    Fragment_four = new RateReviews();
                    tran.replace(R.id.main, Fragment_four);//tran.
                    tran.addToBackStack(null);
                    tran.commit();

我在此行收到“无法解析方法”错误:

FragmentManager man= ((Activity) view).getSupportFragmentManager();

我还尝试将 getSupportFragmentManager 更改为 getFragmentManager,但均未成功。

【问题讨论】:

    标签: android android-fragments android-asynctask


    【解决方案1】:

    Activity 没有 getSupportFragmentManager 函数。 v4 支持库中的 FragmentActivity 类可以。而是将其转换为那个,并确保您的实际 Activity 来自那个而不是来自 Activity。

    旁注 - 无论如何这可能会失败。上下文不一定是活动。事实上,它经常会被包装在 ContextWrapper 或 ContextThemeWrapper 中。无论哪种情况,此代码都会失败。

    【讨论】:

      【解决方案2】:

      你应该在 asynctask 中创建一个 constructor,将 activity 作为参数传递。

      AsyncTask.class

      public class AsyncTaskExample extends AsyncTask<String, Integer, String>
      {
          Activity atv;
          public AsyncTaskExample (Activity atv)
          {
                  this.atv = atv;
          }
          @Override
          protected void onPostExecute(String result)  // contain according to regCheck.php
          {
                  FragmentManager fragmentManager;
                  fragmentManager = atv.getFragmentManager();
                  fragmentManager.beginTransaction()
                              .replace(R.id.main, Fragment_four)
                              .commit();
          }
      }
      

      片段传入

      AsyncTaskExample task = new AsyncTaskExample( getActivity() );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多