从ASync任务

时间:2015-06-25 22:44:22

标签: 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;
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,neith工作。

2 个答案:

答案 0 :(得分:0)

Activity没有getSupportFragmentManager函数。 v4支持库中的FragmentActivity类可以。相反地​​将其转换为,并确保您的实际活动源自而不是来自活动。

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

答案 1 :(得分:0)

您应该在asynctask中创建构造函数,并将 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() );