无法将片段转换为 rss reader 中的 android.app.Activity
Fragment cannot be cast to android.app.Activity in rss reader
我按照 this 教程创建了一个 rss reader(不幸的是,它是西班牙语)。但是,由于我的 rss 必须在片段中,我将 MainActivity 转换为片段:
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.my.app.MainActivity_tabs;
import com.my.app.Modelo.FeedDatabase;
import com.my.app.Modelo.ScriptDatabase;
import com.my.app.R;
import com.my.app.RssParse.Rss;
import com.my.app.Web.VolleySingleton;
import com.my.app.Web.XmlRequest;
/**
* Creado por Hermosa Programación
*
* Actividad principal que representa el Home de la aplicación
*/
public class News extends Fragment {
private static final String TAG = MainActivity_tabs.class.getSimpleName();
public static final String URL_FEED = "www.forbes.com/fdc/rss.html";
private ListView listView;
private FeedAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_tab2, container, false);
// Obtener la lista
listView = (ListView) getActivity().findViewById(R.id.lista);
ConnectivityManager connMgr = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
VolleySingleton.getInstance(getActivity()).addToRequestQueue(
new XmlRequest<>(
URL_FEED,
Rss.class,
null,
new Response.Listener<Rss>() {
@Override
public void onResponse(Rss response) {
// Caching
FeedDatabase.getInstance(getActivity()).
sincronizarEntradas(response.getChannel().getItems());
// Carga inicial de datos...
new LoadData().execute();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error Volley: " + error.getMessage());
}
}
)
);
} else {
Log.i(TAG, "La conexión a internet no está disponible");
adapter = new FeedAdapter(
getActivity(),
FeedDatabase.getInstance(getActivity()).obtenerEntradas(),
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(adapter);
}
// Regisgrar escucha de la lista
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor) adapter.getItem(position);
// Obtene url de la entrada seleccionada
String url = c.getString(c.getColumnIndex(ScriptDatabase.ColumnEntradas.URL));
// Nuevo intent explícito
Intent i = new Intent(getActivity(), DetailActivity.class);
// Setear url
i.putExtra("url-extra", url);
// Iniciar actividad
startActivity(i);
}
});
return rootView;
}
public class LoadData extends AsyncTask<Void, Void, Cursor> {
@Override
protected Cursor doInBackground(Void... params) {
// Carga inicial de registros
return FeedDatabase.getInstance(getActivity()).obtenerEntradas();
}
@Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
// Crear el adaptador
adapter = new FeedAdapter(
getActivity(),
cursor,
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// Relacionar la lista con el adaptador
listView.setAdapter(adapter);
}
}
}
但是当我 运行 应用程序时,出现以下错误,我无法弄清楚为什么会发生这种情况,有什么想法吗?
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.my.app/com.my.app.UI.News}: java.lang.ClassCastException: com.my.app.UI.News cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2319)
at android.app.ActivityThread.access00(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1232)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5253)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:939)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.my.app.UI.News cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1064)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2319)
at android.app.ActivityThread.access00(ActivityThread.java:135)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1232)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5253)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:939)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
at dalvik.system.NativeStart.main(Native Method)
您之前启动 News
的意图是一个 activity 现在正试图启动 News
这是一个片段(可能是因为清单中有 News
作为您的默认启动器 Activity)。您的片段需要保存在 activity 中。
请参阅教程 here,了解如何将片段添加到 activity。
我按照 this 教程创建了一个 rss reader(不幸的是,它是西班牙语)。但是,由于我的 rss 必须在片段中,我将 MainActivity 转换为片段:
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.my.app.MainActivity_tabs;
import com.my.app.Modelo.FeedDatabase;
import com.my.app.Modelo.ScriptDatabase;
import com.my.app.R;
import com.my.app.RssParse.Rss;
import com.my.app.Web.VolleySingleton;
import com.my.app.Web.XmlRequest;
/**
* Creado por Hermosa Programación
*
* Actividad principal que representa el Home de la aplicación
*/
public class News extends Fragment {
private static final String TAG = MainActivity_tabs.class.getSimpleName();
public static final String URL_FEED = "www.forbes.com/fdc/rss.html";
private ListView listView;
private FeedAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_tab2, container, false);
// Obtener la lista
listView = (ListView) getActivity().findViewById(R.id.lista);
ConnectivityManager connMgr = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
VolleySingleton.getInstance(getActivity()).addToRequestQueue(
new XmlRequest<>(
URL_FEED,
Rss.class,
null,
new Response.Listener<Rss>() {
@Override
public void onResponse(Rss response) {
// Caching
FeedDatabase.getInstance(getActivity()).
sincronizarEntradas(response.getChannel().getItems());
// Carga inicial de datos...
new LoadData().execute();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error Volley: " + error.getMessage());
}
}
)
);
} else {
Log.i(TAG, "La conexión a internet no está disponible");
adapter = new FeedAdapter(
getActivity(),
FeedDatabase.getInstance(getActivity()).obtenerEntradas(),
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(adapter);
}
// Regisgrar escucha de la lista
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor) adapter.getItem(position);
// Obtene url de la entrada seleccionada
String url = c.getString(c.getColumnIndex(ScriptDatabase.ColumnEntradas.URL));
// Nuevo intent explícito
Intent i = new Intent(getActivity(), DetailActivity.class);
// Setear url
i.putExtra("url-extra", url);
// Iniciar actividad
startActivity(i);
}
});
return rootView;
}
public class LoadData extends AsyncTask<Void, Void, Cursor> {
@Override
protected Cursor doInBackground(Void... params) {
// Carga inicial de registros
return FeedDatabase.getInstance(getActivity()).obtenerEntradas();
}
@Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
// Crear el adaptador
adapter = new FeedAdapter(
getActivity(),
cursor,
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// Relacionar la lista con el adaptador
listView.setAdapter(adapter);
}
}
}
但是当我 运行 应用程序时,出现以下错误,我无法弄清楚为什么会发生这种情况,有什么想法吗?
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.my.app/com.my.app.UI.News}: java.lang.ClassCastException: com.my.app.UI.News cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2319)
at android.app.ActivityThread.access00(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1232)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5253)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:939)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.my.app.UI.News cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1064)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2319)
at android.app.ActivityThread.access00(ActivityThread.java:135)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1232)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5253)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:939)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
at dalvik.system.NativeStart.main(Native Method)
您之前启动 News
的意图是一个 activity 现在正试图启动 News
这是一个片段(可能是因为清单中有 News
作为您的默认启动器 Activity)。您的片段需要保存在 activity 中。
请参阅教程 here,了解如何将片段添加到 activity。