Android 从异步任务加载片段

Android 从异步任务加载片段,android,android-fragments,android-asynctask,Android,Android Fragments,Android Asynctask,我有一个异步任务,当加载数据时,它也会为星级条设置onClick 当我的用户点击星级评定栏时,我想加载一个新的片段。我正在尝试: package com.example.mike.beerportfoliomaterial; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences

我有一个异步任务,当加载数据时,它也会为星级条设置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();



            }
        });
    }

}
我在此行中遇到无法解决方法错误:

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

我还尝试将getSupportFragmentManager更改为getFragmentManager,但没有成功

活动没有getSupportFragmentManager功能。v4支持库中的FragmentActivity类不支持。相反,把它当作那样,并确保你的实际活动来自于它而不是活动

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

您应该在asynctask中创建一个构造函数,将活动作为参数传递

AsyncTask.class

FragmentManager man= ((Activity) view).getSupportFragmentManager();
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() );