- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试开发一个应用程序,它有一个抽屉导航和一个 fragment 来显示数据。这是我的应用 Activity 堆栈:
->登录(检查是否已登录,它会跳过加载 View 并继续到时间轴)
->时间线
这是我得到错误的方式:
->我启动应用
->它会绕过登录屏幕,因为我已经登录了
->一切正常,然后我从菜单抽屉中单击“注销”或按“后退”按钮
->我回到登录屏幕
->现在,如果我再次按下“登录”并再次启动时间轴 Activity ,我的应用程序就会崩溃...
这是代码。这是日志:
11-15 21:11:52.050 18695-18695/lazarko.pocketformulas E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{lazarko.pocketformulas/lazarko.pocketformulas.Timeline}: android.view.InflateException: Binary XML file line #28: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #28: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:324)
at android.app.Activity.setContentView(Activity.java:1912)
at lazarko.pocketformulas.Timeline.onCreate(Timeline.java:35)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v4.widget.DrawerLayout.isDrawerView(DrawerLayout.java:1097)
at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1306)
at lazarko.pocketformulas.NavigationDrawerFragment.selectItem(NavigationDrawerFragment.java:209)
at lazarko.pocketformulas.NavigationDrawerFragment.onCreate(NavigationDrawerFragment.java:82)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:798)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1015)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1114)
at android.app.Activity.onCreateView(Activity.java:4722)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:324)
at android.app.Activity.setContentView(Activity.java:1912)
at lazarko.pocketformulas.Timeline.onCreate(Timeline.java:35)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
这是我的 Activity 代码:
public class Timeline extends FragmentActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks, SearchView.OnQueryTextListener {
private static NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
public static Context context;
SearchView searchView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
context = getApplicationContext();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
public static Context getContext() {
return context;
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onStart();
FragmentManager fragmentManager = getSupportFragmentManager();
SharedPreferences preferencesFragmentData = getSharedPreferences("fragmentData", 0);
String fragmentID = preferencesFragmentData.getString("currentFragment", "");
if(fragmentID == "FAVORITES_FRAGMENT")
fragmentManager.beginTransaction().replace(R.id.container, new Favorites()).commit();
else if (fragmentID == "TIMELINE_FRAGMENT")
fragmentManager.beginTransaction().replace(R.id.container, new PlaceholderFragment()).commit();
else if (fragmentID == "SETTINGS_FRAGMENT")
fragmentManager.beginTransaction().replace(R.id.container, new Settings()).commit();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
SharedPreferences preferencesFragmentData = getSharedPreferences("fragmentData", 0);
SharedPreferences.Editor editorFragmentData = preferencesFragmentData.edit();
switch(position) {
case 1:
//Timeline clicked
editorFragmentData.putString("currentFragment", "TIMELINE_FRAGMENT");
editorFragmentData.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, new PlaceholderFragment(), "TIMELINE_FRAGMENT")
.commit();
break;
case 2:
//Favorites clicked
editorFragmentData.putString("currentFragment", "FAVORITES_FRAGMENT");
editorFragmentData.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, new Favorites(), "FAVORITES_FRAGMENT")
.commit();
break;
case 3:
//Settings clicked
editorFragmentData.putString("currentFragment", "SETTINGS_FRAGMENT");
editorFragmentData.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, new Settings())
.commit();
break;
case 4:
//Log Out clicked
SharedPreferences loginDataPreferences = getSharedPreferences("loginData", 0);
SharedPreferences.Editor editorLogin = loginDataPreferences.edit();
editorLogin.putBoolean("loggedIn", false);
editorLogin.commit();
Intent intent = new Intent(getApplicationContext(), Login.class);
startActivity(intent);
break;
default:
editorFragmentData.putString("currentFragment", "TIMELINE_FRAGMENT");
editorFragmentData.commit();
fragmentManager.beginTransaction()
.replace(R.id.container, new PlaceholderFragment())
.commit();
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(!mNavigationDrawerFragment.isDrawerOpen()) {
menu.clear();
getMenuInflater().inflate(R.menu.timeline, menu);
//restoreActionBar();
searchView = new SearchView(getActionBar().getThemedContext());
searchView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
searchView.setQueryHint(Html.fromHtml("<font color=#FFFFFF>Search ... </font>"));
searchView.setOnQueryTextListener(this);
searchView.clearFocus();
menu.add("Search").setIcon(R.drawable.ic_action_action_search).setActionView(searchView).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return false;
}
//User searched for a formula and pressed Enter
@Override
public boolean onQueryTextSubmit(String s) {
SharedPreferences preferencesFragmentData = getSharedPreferences("fragmentData", 0);
String currentFragment = preferencesFragmentData.getString("currentFragment", "");
if(currentFragment == "TIMELINE_FRAGMENT"){
//Log.e("TIMELINE", currentFragment + "IN THE IF FRAGMENT");
//Toast.makeText(getContext(), "You searched for: " + s + " in Timeline Fragment!", Toast.LENGTH_SHORT).show();
} else if (currentFragment == "FAVORITES_FRAGMENT"){
//Log.e("TIMELINE", currentFragment + "IN THE IF FRAGMENT");
//Toast.makeText(getContext(), "You searched for: " + s + " in FAVORITES Fragment!", Toast.LENGTH_SHORT).show();
}
//Hide the keyboard
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
invalidateOptionsMenu();
return true;
}
//user started typing, this code block is for Autocomplete or Suggestions based on his current input
@Override
public boolean onQueryTextChange(String s) {
return false;
}
}
这是显示的第一个 fragment :
/**
* Created by lazarnikolov on 11/8/14.
*/
public class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static View rootView;
FavoritesDatabaseAdapter favoritesDB;
SwipeRefreshLayout swipeRefreshLayout = null;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public PlaceholderFragment() {
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_timeline, container, false);
} catch (InflateException e) {
}
favoritesDB = new FavoritesDatabaseAdapter(getActivity().getApplicationContext());
final ContentValues contentValues = new ContentValues();
final LinearLayout llScrollViewContainerItems = (LinearLayout) container.findViewById(R.id.llScrollViewContainerItems);
llScrollViewContainerItems.removeAllViews();
ActionBar actionBar = getActivity().getActionBar();
final Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "ubuntu.ttf");
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.PeterRiver)));
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("Timeline");
swipeRefreshLayout = (SwipeRefreshLayout) container.findViewById(R.id.container);
swipeRefreshLayout.setColorSchemeResources(R.color.Alizarin, R.color.Emerald, R.color.PeterRiver, R.color.Amethyst, R.color.WetAsphalt);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {...}
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = (Fragment) getFragmentManager()
.findFragmentByTag("TIMELINE_FRAGMENT");
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
}
这是我的 activity_timeline.xml 文件,错误发生的地方:
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".Timeline">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<android.support.v4.widget.SwipeRefreshLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/svContainerViews">
<LinearLayout android:id="@+id/llScrollViewContainerItems" android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
</LinearLayout>
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="@+id/navigation_drawer"
android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="lazarko.pocketformulas.NavigationDrawerFragment"
tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
还有我的登录 Activity 类:
/**
* Created by lazarnikolov on 11/8/14.
*/
public class Login extends Activity{
EditText etEmail, etPassword;
Button bLogin, bRegister;
Typeface font;
TextView tvLogIn;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preferences = getSharedPreferences("loginData", 0);
boolean loggedIn = preferences.getBoolean("loggedIn", false);
if(loggedIn) {
Intent intent = new Intent("android.intent.action.TIMELINE");
startActivity(intent);
}
SharedPreferences initialFragmentData = getSharedPreferences("fragmentData", 0);
SharedPreferences.Editor initialEditorFragmentData = initialFragmentData.edit();
initialEditorFragmentData.putString("currentFragment", "TIMELINE_FRAGMENT");
initialEditorFragmentData.commit();
setContentView(R.layout.login);
font = Typeface.createFromAsset(getAssets(), "ubuntu.ttf");
etEmail = (EditText) findViewById(R.id.etEmail);
etEmail.setTypeface(font);
etPassword = (EditText) findViewById(R.id.etPassword);
etPassword.setTypeface(font);
tvLogIn = (TextView) findViewById(R.id.tvRegister);
tvLogIn.setTypeface(font);
bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setTypeface(font);
bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences preferences = getSharedPreferences("loginData", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("loggedIn", true);
editor.commit();
communicate();
Intent intent = new Intent("android.intent.action.TIMELINE");
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setTypeface(font);
bRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("android.intent.action.REGISTER");
startActivity(intent);
}
});
}
// SERVER COMMUNICATION CLASS INITIALIZATION
private void communicate() {
new GetData().execute();
}
// SERVER COMMUNICATION CLASS
private class GetData extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
Looper.prepare();
String data = "";
InputStream inputStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("*******");
String json = "";
JSONObject object = new JSONObject();
object.accumulate("email", etEmail.getText().toString());
object.accumulate("password", etPassword.getText().toString());
json = object.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
inputStream = response.getEntity().getContent();
if(inputStream != null){
Toast.makeText(getApplicationContext(), "Logged in!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Invalid username/password", Toast.LENGTH_SHORT).show();
}
} catch(Exception e) {
Log.e("log_tag", "Error in http connection: " + e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
//Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
@Override onStart(), onRestart(), onResume()...
}
我已经搜索了太久,但仍然找不到解决方案。请看一下,然后将您认为的问题发给我!
非常感谢!
最佳答案
仔细观察/调试lazarko.pocketformulas.NavigationDrawerFragment.java
第209行(属于selectItem()
方法)
根据您的堆栈跟踪,您可能有一个 null
或未正确初始化的对象
更新要了解为什么它有时会发生而有时不会(如果我理解正确的话)的原因还有更多问题要问。
1) 一段时间后开始 Activity 时会发生这种情况吗?如果是这样,则可能与系统已释放资源并重新创建您的 Activity 有关
2) 如果不是 - 你必须一步步寻找原因。
追踪对象被清零的地方。可能是:
-- 关于重新创建父对象(当你没有正确初始化它时)
-- 在它的类中(只要 ctrl+f 所有出现)
——在同类之外。跟踪此对象 private
并声明 setter 方法
关于安卓.view.InflateException : Binary XML file line #28: Error inflating class fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26950576/
我有一个像这样的 fragment 栈 F1 -> F2 -> F3 -> F4 -> F5 现在我需要删除 F2、F3、F4 fragment 。 我需要如果我从 F5 fragment 按下后退按
我需要帮助来理解以下场景的工作原理以及如何实现结果。 我有一个名为 ShoppingCart 的类。它有一个名为 addItemsToShoppingCartFromPreviousOrder 的方法
我有一个包含 ViewPager 的 fragment 。这个 ViewPager 显然是由其他 Fragments 填充的。 我的问题是,ViewPager 中的 Fragment 是否有任何方法(
所以我正在实现一个 FragmentActivity 并尝试添加一个 fragment ,但是我遇到了多个问题。我以前做过这个,实际上我使用的代码与上一个项目(它工作的地方)相同,但由于某种原因它在这
Closed. This question needs details or clarity。它当前不接受答案。
我想将 Android X fragment (androidx.fragment.app.Fragment) 转换为 Android native fragment (android.app.Fra
假设我有一个包含 10 列文本类型 (20) 的 SQLite 表。 ListFragment 将从数据库中提取 4 列并使用 SimpleCursorAdapter 显示在列表中。 选择后,List
我有一个对话框 fragment ,我为延迟初始化创建了一个类。当我显示对话框时,它显示正常。但是,当我关闭对话框时,它崩溃的原因是: fragment 与 fragment 管理器无关。 我也尝试过
我想在 View 分页器更改为 fragment 时刷新该 fragment 。 package com.mcivisoft.rcbeam; import android.os.Bundle; imp
我有一个名为的 Activity MainActivity 我在容器 R.id.mainContainer 中添加了 fragment “BenefitFragment”。 在 BenefitFrag
所以我有这个 ClientListView,效果很好,可以显示客户,我可以单击一个客户并在右侧获取他们的详细信息(在我的第二个 fragment 中)。由此处的布局定义: 这很好用,但后来我
我试过这段代码,但点击第一个 fragment 中的按钮并没有改变第二个 fragment 中的字符串值。 这是第一个 fragment 的 kotlin 文件。它有两个按钮,点击它们可以更改字符串值
我有以下情况:我打开 fragment A 和目标,通过按钮的单击事件转到 fragment B。当我在 fragment B 中并点击后退按钮(为了返回 fragment A) 我想将一些参数传递给
我制作了一个 NavigationDrawer fragment ,其中包含 Home、Settings、Feedback 等项目。 home 项在点击 home 时应该打开,home 是在应用程序启
我正在一个接一个地替换 2 个 fragment ,两个 fragment 都有不同的选项菜单。当我替换第二个 fragment 时,它也显示第一个 fragment 的菜单。 setHasOptio
我有问题: android.app.Fragment$InstantiationException: Unable to instantiate fragment ${packageName}.${a
我正在研究 fragment 转换。当我用第二个 fragment 替换第一个 fragment 时,它出现在第一个 fragment 的下方。我希望它移动到第一个 fragment 之上。我该怎么做
我在抽屉导航里总共有 12 个 fragment 。每个 fragment 都有 volley 方法。每个 fragment 都显示自己的 Volley 响应,除了 position = 1 和 po
我在我的 Activity 中使用了两个 fragment 。最初我将向 Activity 添加一个 fragment 。然后在第一个 fragment 中使用监听器我想用第二个 fragment 替
我正在实现一个“fragments-101”程序,当相应的按钮被点击时我会替换一个 fragment 。然而,下面的事情发生了: 为什么会这样?为什么初始 fragment 没有被完全替换?MainA
我是一名优秀的程序员,十分优秀!