接口无法强制转换为Activity

时间:2017-01-05 06:09:31

标签: android android-fragments interface classcastexception

我为后台进程创建了一个单独的类。在那,我有两个类和一个接口。我从第一个类中获取字符串数据,然后根据该数据获取另一个类中的数据列表。整个过程工作正常,但现在我想将该列表发送到我的片段,但获得public class PlacesTaskNew extends AsyncTask<String, Void, String> { Context context; public PlacesTaskNew(Context context) { this.context = context; } @Override protected String doInBackground(String... place) { String data = ""; -- -- return data; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); ParserTask parserTask = new ParserTask(context); parserTask.execute(result); } private String downloadUrl(String strUrl) throws IOException { String data = ""; -- -- return data; } public interface PlaceTaskInterface { void onGetPlaces(List<HashMap<String, String>> result, String[] from, int[] to); } private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> { JSONObject jObject; Context mContext; PlaceTaskInterface placeTaskInterface; public ParserTask(Context mContext) { this.mContext = mContext; this.placeTaskInterface = (PlaceTaskInterface) mContext; } @Override protected List<HashMap<String, String>> doInBackground(String... jsonData) { List<HashMap<String, String>> places = null; -- -- return places; } @Override protected void onPostExecute(List<HashMap<String, String>> result) { String[] from = new String[]{"description"}; int[] to = new int[]{android.R.id.text1}; placeTaskInterface.onGetPlaces(result, from, to); } } }

下面是我的代码: -

public class DashboardFragment extends Fragment implements PlaceTaskInterface {

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

        Locality.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                //here is the error
                placesTaskNew = new PlacesTaskNew(getActivity());
                placesTaskNew.execute(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        PlacesTaskNew placesTaskNew = new PlacesTaskNew(getActivity());
        placesTaskNew.execute(charSequence.toString());
    }

    @Override
    public void onGetPlaces(List<HashMap<String, String>> result, String[] from, int[] to) {
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), result, android.R.layout.simple_list_item_1, from, to);
        Locality.setAdapter(adapter);
    }
}

这是我的片段类: -

FATAL EXCEPTION: main
Process: com.theweedconnect.me, PID: 14807
java.lang.ClassCastException: MainActivity cannot be cast to PlaceTaskInterface

以下是logcat错误: -

{{1}}

请帮忙,Thanx:)

2 个答案:

答案 0 :(得分:7)

var map,infoWindow; function getData() { var lat1 = map.getCenter().lat(); var lng1= map.getCenter().lng(); var zoom1 = map.getZoom(); map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(lat1, lng1), zoom: zoom1, mapTypeId: 'roadmap' }); infoWindow = new google.maps.InfoWindow; downloadUrl("http://x.x.x.x/rfplan/getsitedata_1.php?ssa="+$("#ssa option:selected").text() + "&type="+$("#type option:selected").val() + "&make="+$("#make option:selected").val() + "&comm="+$("#comm option:selected").val() + "&sev="+$("#sev option:selected").val() + "&include="+$("#include option:selected").val() + "&can="+$("#cand option:selected").val() + "&ip_vand="+$("#vand option:selected").val(), function(data){ var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { var address = markers[i].getAttribute("info"); var point = new google.maps.LatLng( parseFloat(markers[i].getAttribute("latitude")), parseFloat(markers[i].getAttribute("longitude"))); var html = "<b>" + name + "</b> <br/>" + address; var icon = customIcons[markers[i].getAttribute("color")] || {}; var marker = new google.maps.Marker({ map: map, position: point, icon: icon.icon }); bindInfoWindow(marker, map, infoWindow, html); } }); } function proc(){ } function load() { map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(22, 71), zoom: 7 mapTypeId: 'roadmap', }); infoWindow = new google.maps.InfoWindow; } function bindInfoWindow(marker, map, infoWindow, html) { google.maps.event.addListener(marker, 'click', function() { infoWindow.setContent(html); infoWindow.open(map, marker); }); } function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function() { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } function doNothing() {} 已在PlaceTaskInterface(DashboardFragment)中实施,而不是Fragment方法实现的Activity

getActivity()作为第二个参数传递给this类构造函数以获取接口实例:

PlacesTaskNew

答案 1 :(得分:3)

Thanx to @ρяσѕρєяK,这是我的建议

在两个构造函数中添加PlaceTaskInterface placeTaskInterface

PlacesTaskNew construcor

Context context;
PlaceTaskInterface placeTaskInterface;

public PlacesTaskNew(Context context, PlaceTaskInterface placeTaskInterface) {
    this.context = context;
    this.placeTaskInterface = placeTaskInterface;
}

onPostExecute方法

中写下这些行
@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    ParserTask parserTask = new ParserTask(context, this.placeTaskInterface);
    parserTask.execute(result);
}

ParserTask构造函数

JSONObject jObject;
Context mContext;
PlaceTaskInterface placeTaskInterface;

public ParserTask(Context mContext, PlaceTaskInterface placeTaskInterface) {
    this.mContext = mContext;
    this.placeTaskInterface = placeTaskInterface;
}

最后在你的Fragment中,写下如下

Locality.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        placesTaskNew = new PlacesTaskNew(getActivity(), new PlacesTaskNew.PlaceTaskInterface() {
            @Override
            public void onGetPlaces(List<HashMap<String, String>> result, String[] from, int[] to) {
                SimpleAdapter adapter = new SimpleAdapter(getActivity(), result, android.R.layout.simple_list_item_1, from, to);
                Locality.setAdapter(adapter);
            }
        });
        placesTaskNew.execute(charSequence.toString());
    }

    @Override
    public void afterTextChanged(Editable editable) {
    }
});

问候!