无法将'android.app.activity'投射到'come.Home Fragment'

问题描述 投票:0回答:2

请帮忙,

我只想将listview从JSON添加到片段,但是我在这一行上收到错误:

((HomeFragment) activity).parseJsonResponse(result);

显示错误:

不可逆的类型;无法将android.app.activity强制转换为com.HomeFragment

get JSON from URL task.Java

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

@SuppressWarnings("ConstantConditions")
public class GetJsonFromUrlTask extends AsyncTask<Void, Void, String>{

    private Activity activity;
    private String url;
    private ProgressDialog dialog;
    private final static String TAG = GetJsonFromUrlTask.class.getSimpleName();

    public GetJsonFromUrlTask(Activity activity, String url) {
        super();
        this.activity = activity;
        this.url = url;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progress dialog
        dialog = new ProgressDialog(activity);
        // Set progress dialog title
        dialog.setTitle("Getting JSON DATA");
        // Set progress dialog message
        dialog.setMessage("Loading...");
        dialog.setIndeterminate(false);
        // Show progress dialog
        dialog.show();
    }

    @Override
    protected String doInBackground(Void... params) {

        // call load JSON from url method
        return loadJSON(this.url).toString();
    }

    @Override
    protected void onPostExecute(String result) {
        ((HomeFragment) activity).parseJsonResponse(result);
        Log.i(TAG, result);
    }

    public JSONObject loadJSON(String url) {
        // Creating JSON Parser instance
        JSONGetter jParser = new JSONGetter();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        return json;
    }

    private class JSONGetter {

        private InputStream is = null;
        private JSONObject jObj = null;
        private String json = "";

        // constructor
        public JSONGetter() {

        }

        public JSONObject getJSONFromUrl(String url) {

            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),
                        8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            // return JSON String
            return jObj;

        }
    }
}

home fragment.Java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class HomeFragment extends Fragment {

    private ListView listview;
    private ArrayList<Book> books;
    private ArrayAdapter<Book> adapter;

    private final static String TAG = HomeFragment.class.getSimpleName();
    private final static String url = "http://www.json-generator.com/api/json/get/ccLAsEcOSq?indent=2";

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        listview = view.findViewById(R.id.listview);
        setListViewAdapter();
        getDataFromInternet();
        return view;
    }

    private void getDataFromInternet() {
        new GetJsonFromUrlTask(getActivity(), url).execute();
    }

    private void setListViewAdapter() {
        books = new ArrayList<Book>();
        adapter = new CustomListViewAdapter(getActivity(), R.layout.item_listview, books);
        listview.setAdapter(adapter);
    }

    //parse response data after asynctask finished
    public void parseJsonResponse (String result) {
        Log.i(TAG, result);
        try {
            JSONObject json = new JSONObject(result);
            JSONArray jArray = new JSONArray(json.getString("book_array"));
            for (int i = 0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                Book book = new Book();
                book.setName(jObject.getString("book_title"));
                book.setImageUrl(jObject.getString("image"));
                book.setAuthorName(jObject.getString("author"));
                books.add(book);
            }

            adapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
android android-studio android-activity casting android-fragmentactivity
2个回答
0
投票

尝试发送Fragment not Activity。

不是getActivity()发送thisgetActivity()以片段形式提供活动。

 new GetJsonFromUrlTask(this, url).execute();

然后

 private Fragment fragment;
 public GetJsonFromUrlTask(Fragment fragment, String url) {
        super();
        this.fragment = fragment;
        this.url = url;
    }

然后

 @Override
    protected void onPostExecute(String result) {
        ((HomeFragment) fragment).parseJsonResponse(result);
        Log.i(TAG, result);
    }

0
投票

抱歉无法转换HomeFragment和Activity,因为HomeFragment不对象上下文。当HomeFragment附加时,Param活动是Activity的实例。您尝试:param片段或接口回调成功时

© www.soinside.com 2019 - 2024. All rights reserved.