Text view not being filled form ASYNC Task

126 Views Asked by At

I have a fragment that grabs info from JSON on the web:

public class RateReviews extends Fragment {

    String beerId = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //set layout here
        View v = inflater.inflate(R.layout.ratereview, container, false);

        ((ActionBarActivity)getActivity()).getSupportActionBar().setTitle("Rate Reviews");


        //get user information
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);
        String styleID = prefs.getString("style", null);


        //async to get data
        //construct url
        String url = "myURL";


        //todo: add code for rating the note with the ratebar


        //async task to get beer taste tag percents
        new getReviewToRateJSON(getActivity()).execute(url);



        // Inflate the layout for this fragment
        return v;

    }



}

The code for the async task is:

public class getReviewToRateJSON extends AsyncTask<String, Void, String> {

    Context c;
    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);



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


            TextView note = (TextView) ((Activity) c).findViewById(R.id.reviewToRate);
            note.setText("test hghhgkghjghjghghgkjgkhgjhgkj");



        }
        catch(Exception e){

        }

        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();
    }

}

My issue is that the text view in my fragment is not being populated. To make sure my JSON string was not empty I hard coded this line:

note.setText("test hghhgkghjghjghghgkjgkhgjhgkj");

But it still shows up as blank in my fragment. My xml for my fragment looks like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e5e5e5"
    android:orientation="vertical"

    android:id="@+id/switchOut">




        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="6dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="4dp"
                android:layout_marginBottom="4dp"
                android:orientation="vertical"
                android:background="@drawable/bg_card">

                <!-- Card Contents go here -->


                <TextView
                    android:id="@+id/reviewToRate"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:textSize="15sp"
                    android:padding="5dip"

                    ></TextView>



            </LinearLayout >

        </FrameLayout>


    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="6dp"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:orientation="vertical"
            android:background="@drawable/bg_card">

            <!-- Card Contents go here -->


            <RatingBar
                android:id="@+id/reviewRatingBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:numStars="5"
                android:stepSize="1.0"
                android:rating="0"


                />



        </LinearLayout >

    </FrameLayout>


</LinearLayout>
1

There are 1 best solutions below

0
On

When doing

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

you are trying to get the view from the activity, which is not present (as the view is in fragment).

What you should do is , pass the View of the fragment as a parameter in the constructor of getReviewToRateJSON and then use this view to get the desired element(In this case your text view).

the code will look similar as:

public class getReviewToRateJSON extends AsyncTask<String, Void, String> {

Context c;
private ProgressDialog Dialog;
View fragmentView

public getReviewToRateJSON(Context context, View fragmentView)
{
    c = context;
    this.fragmentView = fragmentView; 
    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);



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


        //TextView note = (TextView) ((Activity) c).findViewById(R.id.reviewToRate);
        TextView note = (TextView) fragmentView.findViewById(R.id.reviewToRate);
        note.setText("test hghhgkghjghjghghgkjgkhgjhgkj");



    }
    catch(Exception e){
       //BTW this is the reason why your app  is not crashing (EXCETION CATCHES ALL)
    }

    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();
}}