无法将 'android.app.activty' 转换为 'com.HomeFragment'

cannot cast 'android.app.activty' to 'com.HomeFragment'

请帮忙,

我只想将 JSON 中的列表视图添加到片段中,但我在这一行遇到错误:

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

显示错误:

inconvertible type; cannot cast android.app.activity to com.HomeFragment

GetJsonFromUrlTask.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;

        }
    }
}

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

}

尝试发送片段而不是 Activity。

不是 getActivity() 发送 thisgetActivity() 在片段中提供 activity。

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

抱歉无法转换 HomeFragment,Activity 因为 HomeFragment 不反对上下文。附加 HomeFragment 时,参数 activity 是 Activity 的实例。 您尝试:param fragment 或 Interface callback when success