Fragment activity not inflating - java

For my master detail flow app I'm trying to inflate my Continents list view on my tablet but it won't do so and I end up with these errors in my log cat. Does anyone know what I'm doing wrong?
Continents List xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_marginLeft="16dp"
android:layout_marginRight="16dp" android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal" android:orientation="horizontal"
android:showDividers="middle" tools:context=".ItemListActivity">
<fragment android:id="#+id/continents_list" android:name="com.apptacularapps.md.ContinentsListFragment"
android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"
tools:layout="#android:layout/list_content" />
<FrameLayout android:id="#+id/item_detail_container" android:layout_width="0dp"
android:layout_height="match_parent" android:layout_weight="3" />
</LinearLayout>
ContinentsListActivity.java
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
public class ContinentsListActivity extends ActionBarActivity
implements ContinentsListFragment.Callbacks {
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_continents_list);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.continents_list_contaniner, new ContinentsListFragment());
ft.commit();
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
((ContinentsListFragment) getSupportFragmentManager()
.findFragmentById(R.id.continents_list))
.setActivateOnItemClick(true);
}
}
#Override
public void onItemSelected(String id) {
if("1".equals(id)){
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.continents_list, fragment)
.commit();
} else {
Intent detailIntent = new Intent(this, ContinentsListActivity.class);
startActivity(detailIntent);
}
}
}
}
ContinentsListFragment.java
package com.apptacularapps.md;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ContinentsListFragment extends ListFragment {
private static final String STATE_ACTIVATED_POSITION = "activated_position";
private Callbacks mCallbacks = sContinentsCallbacks;
private int mActivatedPosition = ListView.INVALID_POSITION;
public interface Callbacks {
public void onItemSelected(String id);
}
private static Callbacks sContinentsCallbacks = new Callbacks() {
#Override
public void onItemSelected(String id) {
}
};
public ContinentsListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: replace with a real list adapter.
setListAdapter(new ArrayAdapter<ContinentsContent.ContinentsItem>(
getActivity(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
ContinentsContent.ITEMS));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
#Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the Continents implementation.
mCallbacks = sContinentsCallbacks;
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
mCallbacks.onItemSelected(ContinentsContent.ITEMS.get(position).id);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
public void setActivateOnItemClick(boolean activateOnItemClick) {
getListView().setChoiceMode(activateOnItemClick
? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
}
Logcat
05-20 20:29:42.523 32338-32338/com.apptacularapps.md E/libprocessgroup﹕ failed to make and chown /acct/uid_10056: Read-only file system
05-20 20:29:42.531 32338-32338/com.apptacularapps.md W/Zygote﹕ createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
05-20 20:29:42.532 32338-32338/com.apptacularapps.md I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-20 20:29:43.002 32338-32352/com.apptacularapps.md I/art﹕ Background sticky concurrent mark sweep GC freed 3104(261KB) AllocSpace objects, 0(0B) LOS objects, 26% free, 829KB/1135KB, paused 11.699ms total 50.909ms
05-20 20:29:43.006 32338-32359/com.apptacularapps.md D/OpenGLRenderer﹕ Render dirty regions requested: true
05-20 20:29:43.034 32338-32338/com.apptacularapps.md D/﹕ HostConnection::get() New Host Connection established 0xa693a490, tid 32338
05-20 20:29:43.070 32338-32338/com.apptacularapps.md D/Atlas﹕ Validating map...
05-20 20:29:43.227 32338-32359/com.apptacularapps.md D/﹕ HostConnection::get() New Host Connection established 0xa693a8a0, tid 32359
05-20 20:29:43.246 32338-32359/com.apptacularapps.md I/OpenGLRenderer﹕ Initialized EGL, version 1.4
05-20 20:29:43.376 32338-32359/com.apptacularapps.md D/OpenGLRenderer﹕ Enabling debug mode 0
05-20 20:29:43.397 32338-32359/com.apptacularapps.md W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-20 20:29:43.397 32338-32359/com.apptacularapps.md W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa696eba0, error=EGL_SUCCESS
05-20 20:29:46.874 32338-32338/com.apptacularapps.md D/AndroidRuntime﹕ Shutting down VM
05-20 20:29:46.875 32338-32338/com.apptacularapps.md E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.apptacularapps.md, PID: 32338
java.lang.IllegalStateException: Activity must implement fragment's callbacks.
at com.apptacularapps.md.ContinentsListFragment.onAttach(ContinentsListFragment.java:89)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:907)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

your implementation of onAttach, says
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
To fix you have to add implements Callbacks to the Activity hosting the Fragment.
Edit:
in the xml of your activity, replace
<fragment android:id="#+id/continents_list" android:name="com.apptacularapps.md.ContinentsListFragment"
android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"
tools:layout="#android:layout/list_content" />
with
<FrameLayout android:id="#+id/continents_list_contaniner"
android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/>
and onCreate() of the Activity, after setContentView do:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.continents_list_contaniner, new ContinentsListFragment());
ft.commit();
Edit2:
in your Activity replace
import android.app.FragmentManager;
import android.app.FragmentTransaction;
with
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction

Related

Android application crashes at setContentView at OnCreate only on low android API

My application works at API 24 and above but crashes at API 19.
the problem seem to be at setContentView line in the OnCreate method.
I tried to change all API 21+ features at android XML file but it didn't help.
Also tried to put multidex and it didn't work.
I added here
the setContentView method:
package com.idan.idanzimbler.epiclogin.view;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.idan.idanzimbler.epiclogin.R;
import com.idan.idanzimbler.epiclogin.controller.FillSeriesListFromFireBaseBySearchTask;
import com.idan.idanzimbler.epiclogin.controller.FillSeriesListFromFireBaseBySuggestionsTask;
import com.idan.idanzimbler.epiclogin.controller.FillSeriesListFromFireBaseTask;
import com.idan.idanzimbler.epiclogin.controller.TvSeriesFavoriteList;
import com.idan.idanzimbler.epiclogin.controller.TvSeriesHomeList;
import com.idan.idanzimbler.epiclogin.controller.UsersBookmarks;
import com.idan.idanzimbler.epiclogin.modle.TvSeries;
import com.google.firebase.auth.FirebaseAuth;
import com.squareup.picasso.Picasso;
import java.util.Locale;
public class HomeActivity extends AppCompatActivity implements AbsListView.OnScrollListener {
public static final String INTENT_FLAG = "flag";
public static final int FIRST_ENTER = 1;
//public static final int REBUILD = 2;
public static final int RECOMMENDATION_ENTER = 2;
ExpandableListView list;
EditText searchEt;
ProgressBar progressBar;
HomeActivity context;
ImageView questionmarkHomeBtn;
boolean isInSearchMode;
boolean isInRecommendationMode;
TextView homeToolbarTitleTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
loadLocale();
Toolbar toolbar = findViewById(R.id.homeToolbar);
toolbar.setTitle("");
homeToolbarTitleTV = findViewById(R.id.home_titleTV);
setSupportActionBar(toolbar);
context = this;
isInSearchMode = false;
isInRecommendationMode = false;
progressBar = findViewById(R.id.home_progressbar);
questionmarkHomeBtn = findViewById(R.id.home_questionmark_btn);
list = findViewById(R.id.home_series_list);
searchEt = findViewById(R.id.home_search_et);
progressBar.setVisibility(View.VISIBLE);
TvSeriesHomeList.getInstance().clear();
TvSeriesFavoriteList.getInstance().clear();
TvSeriesFavoriteList.getInstance().initializeSeriesList();
UsersBookmarks.getInstance().initializeBookmarks();
Bundle b = getIntent().getExtras();
int flag = 1;
if (b != null) flag = b.getInt(INTENT_FLAG);
if (flag == FIRST_ENTER) {
new FillSeriesListFromFireBaseTask(this, list).execute();
} else if (flag == RECOMMENDATION_ENTER) {
progressBar.setVisibility(View.VISIBLE);
isInRecommendationMode = true;
homeToolbarTitleTV.setText(getString(R.string.recommendation));
new FillSeriesListFromFireBaseBySuggestionsTask(context, list).execute();
}
list.setOnScrollListener(this);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TvSeriesFavoriteList favorites = TvSeriesFavoriteList.getInstance();
TvSeries series = TvSeriesHomeList.getInstance().getSeries().get(position);
if (favorites.contains(series.getId())) {
favorites.remove(series.getId());
ImageView star = view.findViewById(R.id.series_list_fav_iv);
Picasso.get().load(R.drawable.emptystar).fit().into(star);
Toast.makeText(getApplicationContext(), "Removed from favorites", Toast.LENGTH_SHORT).show();
} else if (favorites.canAdd(series)) {
favorites.add(series);
ImageView star = view.findViewById(R.id.series_list_fav_iv);
Picasso.get().load(R.drawable.filledstar).fit().into(star);
Toast.makeText(getApplicationContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Maximum of 5 series can be added to favorites", Toast.LENGTH_SHORT).show();
}
return true;
}
});
searchEt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String searchString = s.toString().trim();
if (searchString.isEmpty()) {
isInSearchMode = false;
TvSeriesHomeList.getInstance().clear();
new FillSeriesListFromFireBaseTask(context, list).execute();
} else {
isInSearchMode = true;
new FillSeriesListFromFireBaseBySearchTask(context, list, searchString).execute();
}
}
});
questionmarkHomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setCancelable(true);
builder.setTitle(getString(R.string.how_to_use));
builder.setMessage(getString(R.string.home_fav_bookmark_explain));
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
});
}
#Override
protected void onResume() {
super.onResume();
loadLocale();
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!isInSearchMode && !isInRecommendationMode) {
switch (view.getId()) {
case R.id.home_series_list:
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if (TvSeriesHomeList.getInstance().getPreLast() != lastItem) {
TvSeriesHomeList.getInstance().incrementPage();
new FillSeriesListFromFireBaseTask(this, list).execute();
TvSeriesHomeList.getInstance().setPreLast(lastItem);
}
}
}
}
}
public ProgressBar getProgressBar() {
return progressBar;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.profilemenu:
startActivity(new Intent(this, ProfileActivity.class));
break;
case R.id.favoritesmenu:
startActivity(new Intent(this, FavoritesActivity.class));
break;
case R.id.aboutmenu:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.signoutmenu:
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.recommendationmenu:
TvSeriesHomeList.getInstance().clear();
progressBar.setVisibility(View.VISIBLE);
isInRecommendationMode = true;
new FillSeriesListFromFireBaseBySuggestionsTask(context, list).execute();
homeToolbarTitleTV.setText(getString(R.string.recommendation));
break;
case R.id.homemenu:
if (isInRecommendationMode) {
isInRecommendationMode = false;
TvSeriesHomeList.getInstance().clear();
new FillSeriesListFromFireBaseTask(this, list).execute();
}
homeToolbarTitleTV.setText(getString(R.string.home));
break;
case R.id.rateusmenu:
try{
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.idan.idanzimbler.epiclogin")));
}catch (ActivityNotFoundException e){
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.idan.idanzimbler.epiclogin")));
}
}
return true;
}
#Override
public void onBackPressed() {
if (!searchEt.getText().toString().isEmpty()) {
searchEt.setText("");
} else if (isInRecommendationMode) {
isInRecommendationMode = false;
TvSeriesHomeList.getInstance().clear();
new FillSeriesListFromFireBaseTask(this, list).execute();
}else {
super.onBackPressed();
}
}
public void setLocale(String lang) {
Locale locale = new Locale(lang,"US");
if(lang.equals("he")){
locale = new Locale(lang,"IL");
}
else if(lang.equals("ar")){
locale = new Locale(lang,"JO");
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
SharedPreferences.Editor editor = getSharedPreferences("Settings" ,MODE_PRIVATE).edit();
editor.putString("My_Lang",lang);
editor.apply();
}
public void loadLocale(){
SharedPreferences prefs = getSharedPreferences("Settings",Activity.MODE_PRIVATE);
String language = prefs.getString("My_Lang", "");
setLocale(language);
}
}
The XML file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.HomeActivity">
<EditText
android:id="#+id/home_search_et"
android:layout_width="301dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="14dp"
android:layout_weight="1"
android:ems="10"
android:hint="#string/enter_tv_series_name"
android:inputType="textPersonName"
app:backgroundTint="#color/common_google_signin_btn_text_dark_focused"
app:layout_constraintBottom_toTopOf="#+id/home_series_list"
app:layout_constraintEnd_toStartOf="#+id/home_questionmark_btn"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout"
/>
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
app:layout_constraintBottom_toTopOf="#+id/home_search_et"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.v7.widget.Toolbar
android:id="#+id/homeToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:contentInsetStart="0dp"
android:contentInsetLeft="0dp"
android:contentInsetEnd="0dp"
android:contentInsetRight="0dp"
android:elevation="2dp"
android:gravity="end"
app:contentInsetEnd="0dp"
app:contentInsetLeft="0dp"
app:contentInsetRight="0dp"
app:contentInsetStart="0dp"
app:popupTheme="#style/AppTheme.PopupOverlay"
tools:targetApi="lollipop">
<TextView
android:id="#+id/home_titleTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/home"
android:textColor="#color/common_google_signin_btn_text_dark_default"
android:textSize="25sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<ExpandableListView
android:id="#+id/home_series_list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="4dp"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/home_search_et" />
<ProgressBar
android:id="#+id/home_progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:indeterminateDrawable="#drawable/blackprogressbar"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="#+id/home_series_list"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/home_questionmark_btn"
android:layout_width="34dp"
android:layout_height="24dp"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="#+id/home_search_et"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/home_search_et"
app:srcCompat="#drawable/questionmarklogo"
android:contentDescription="TODO" />
</android.support.constraint.ConstraintLayout>
the Run:
V/FA: Activity paused, time: 2504321
V/FA: onActivityCreated
D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=11068, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-8684354233398184439}]
W/dalvikvm: JNI WARNING: NewStringUTF input is not valid Modified UTF-8: illegal start byte 0xf0
string: 'en_Latn_US_�_US'
in Llibcore/icu/ICU;.addLikelySubtags:(Ljava/lang/String;)Ljava/lang/String; (NewStringUTF)
I/dalvikvm: "main" prio=5 tid=1 NATIVE
| group="main" sCount=0 dsCount=0 obj=0xa4d56bd8 self=0xb7e34eb0
| sysTid=3387 nice=0 sched=0/0 cgrp=apps handle=-1216573376
| state=R schedstat=( 1431490769 212065377 2672 ) utm=91 stm=51 core=1
I/dalvikvm: #00 pc 000bd936 /system/lib/libdvm.so (dvmDumpNativeStack(DebugOutputTarget const*, int)+86)
#01 pc 00098513 /system/lib/libdvm.so (dvmDumpThreadEx(DebugOutputTarget const*, Thread*, bool)+1155)
#02 pc 00098806 /system/lib/libdvm.so (dvmDumpThread(Thread*, bool)+86)
#03 pc 0004d3ff /system/lib/libdvm.so (ScopedCheck::checkUtfString(char const*, bool)+271)
#04 pc 0004e2ad /system/lib/libdvm.so (ScopedCheck::check(bool, char const*, ...)+1437)
#05 pc 00052927 /system/lib/libdvm.so
#06 pc 000204be /system/lib/libjavacore.so
#07 pc 0002a4ab /system/lib/libdvm.so (dvmPlatformInvoke+79)
at libcore.icu.ICU.addLikelySubtags(Native Method)
I/dalvikvm: at android.text.TextUtils.getLayoutDirectionFromLocale(TextUtils.java:1740)
at android.content.res.Configuration.setLayoutDirection(Configuration.java:1295)
at android.content.res.Configuration.updateFrom(Configuration.java:820)
at android.content.res.Resources.updateConfiguration(Resources.java:1557)
at android.content.res.Resources.updateConfiguration(Resources.java:1511)
at android.support.v7.widget.ResourcesWrapper.updateConfiguration(ResourcesWrapper.java:232)
at android.content.res.Resources.<init>(Resources.java:202)
at android.content.res.Resources.<init>(Resources.java:179)
at android.support.v7.widget.ResourcesWrapper.<init>(ResourcesWrapper.java:48)
at android.support.v7.widget.TintResources.<init>(TintResources.java:35)
at android.support.v7.widget.TintContextWrapper.<init>(TintContextWrapper.java:101)
at android.support.v7.widget.TintContextWrapper.wrap(TintContextWrapper.java:69)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:69)
at android.support.v7.widget.AppCompatEditText.<init>(AppCompatEditText.java:65)
at android.support.v7.app.AppCompatViewInflater.createEditText(AppCompatViewInflater.java:192)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:114)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.idan.idanzimbler.epiclogin.view.HomeActivity.onCreate(HomeActivity.java:58)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
E/dalvikvm: VM aborting
A/libc: Fatal signal 6 (SIGABRT) at 0x00000d3b (code=-6), thread 3387 (mbler.
Application terminated.
The stacktrace seems to indicate an issue reading the current Resources Configuration (whether your Locale is RTL or not).
Looking at the activity code, you are modifying the Locale used by your application instead of using the phone Locale which would explain the issue. Your Activity will actually go through onCreate twice. The first time is probably inflating your XML view without any trouble but once you set the new Configuration (by calling loadLocale()), the Activity will be destroyed and re-created, which will execute onCreate() a second time with your new Configuration. This is when your application is crashing.
In my opinion, the problem is most likely in the setLocale() method, the change of Configuration is not done correctly and new APIs are able to use a default value whereas older APIs simply crash.
Even though I wouldn't recommend modifying the Locale in the app, here is more information on modifying it in an Android application:
https://proandroiddev.com/change-language-programmatically-at-runtime-on-android-5e6bc15c758
There is different methods to use depending on the version of the APIs you support.
The method he is using to change the configuration looks like:
private static Context updateResources(Context context, Locale locale) {
Locale.setDefault(locale);
Resources res = context.getResources();
Configuration config = new Configuration(res.getConfiguration());
if (Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale);
context = context.createConfigurationContext(config);
} else {
config.locale = locale;
res.updateConfiguration(config, res.getDisplayMetrics());
}
return context;
}

Does scrollview work in fragments?

I have an employeeList fragment which upon access crashes the app. There are no squiggly lines in code, neither any alarms in the stack trace. I have a hunch that scrollView might be causing this. Here's the code
ManageFragment.java
package com.teslaqubitsins.fasih.teslahcm;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.openOrCreateDatabase;
public class ManageFragment extends Fragment {
EmployeeDatasource mEmployeeDatasource;
View rootView;
public ManageFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
rootView = inflater.inflate(R.layout.fragment_manage, container, false);
mEmployeeDatasource = new EmployeeDatasource(getActivity());
final ArrayList<Employee> employeeArrayList = mEmployeeDatasource.getList();
ListView mListView = (ListView) getActivity().findViewById(R.id.employeeList_listView);
EmployeeAdapter mEmployeeAdapter = new EmployeeAdapter(this.getActivity(), R.layout.row_employee_list, employeeArrayList);
mListView.setAdapter(mEmployeeAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
EmployeeDetailFragment detailedemployee = new EmployeeDetailFragment();
Employee item = employeeArrayList.get(i);
EmployeeDetailFragment.mEmployee = item;
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, detailedemployee);
ft.addToBackStack(null);
ft.commit();
}
});
return rootView;
}
}
fragment_manage.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.teslaqubitsins.fasih.teslahcm.ManageFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/employeeList_listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</FrameLayout>
row_employee_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="2dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="vertical">
<ImageView
android:id="#+id/row_employee_imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="#drawable/ic_stub" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="3"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/row_employee_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Employee Name"
android:textSize="20sp" />
<TextView
android:id="#+id/row_employee_salary"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:maxLines="1"
android:text="120 PKR" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
Please someone help me sort out the issue.
LOGS
04-24 15:17:31.223 1314: 1314 E/ ] Couldn't opendir /data/app/vmdl1759858640.tmp: No such file or
directory 04-24 15:17:32.773 2184-2184/com.google.android.googlequicksearchbox:search W/LocationOracle: Starting background requests 04-24 15:17:33.123 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:33.124 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:35.478 2048-2960/com.google.android.gms.persistent I/GCoreUlr: Starting service, intent=Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) }, extras=Bundle[{receiverAction=android.intent.action.BOOT_COMPLETED}] 04-24 15:17:36.013 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater received intent Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) } with receiverAction android.intent.action.BOOT_COMPLETED 04-24 15:17:36.533 2048-2990/com.google.android.gms.persistent I/GCoreUlr: Starting service, intent=Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) }, extras=Bundle[{receiverAction=com.google.android.location.internal.server.ACTION_RESTARTED}] 04-24 15:17:36.575 2048-2365/com.google.android.gms.persistent I/GCoreUlr: Starting service, intent=Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) }, extras=Bundle[{receiverAction=com.google.android.location.reporting.PHENOTYPE_FLAGS_CHANGED}] 04-24 15:17:37.325 3106-3106/? W/dex2oat: /system/bin/dex2oat
--runtime-arg -classpath --runtime-arg & --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2,-lock_add,-popcnt
--runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/user/0/com.google.android.gms/app_fb/f.apk --oat-fd=51 --oat-location=/data/user/0/com.google.android.gms/app_fb/f.dex --compiler-filter=speed 04-24 15:17:37.325 3106-3106/? I/dex2oat: /system/bin/dex2oat
--dex-file=/data/user/0/com.google.android.gms/app_fb/f.apk --oat-fd=51 --oat-location=/data/user/0/com.google.android.gms/app_fb/f.dex --compiler-filter=speed 04-24 15:17:37.780 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:37.780 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:37.920 2048-2986/com.google.android.gms.persistent I/GCoreUlr: GMS FLP location and AR updates requested: {"description":"stationary","newRequest":true,"samplePeriodMs":2160000,"sampleReason":"stationary","sampleSource":"internal","timestampMs":1493029056848} 04-24 15:17:38.057 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater received intent Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) } with receiverAction com.google.android.location.internal.server.ACTION_RESTARTED 04-24 15:17:38.064 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater:com.google.android.location.internal.server.ACTION_RESTARTED: Ensuring that reporting is active for [account#7#] 04-24 15:17:38.069 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater received intent Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) } with receiverAction com.google.android.location.reporting.PHENOTYPE_FLAGS_CHANGED 04-24 15:17:38.103 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater:com.google.android.location.reporting.PHENOTYPE_FLAGS_CHANGED: Ensuring that reporting is active for [account#7#] 04-24 15:17:38.430 2048-2048/com.google.android.gms.persistent E/ActivityThread: Service com.google.android.location.places.service.PlaceDetectionAsyncService has leaked IntentReceiver amth#cd0bee8 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service com.google.android.location.places.service.PlaceDetectionAsyncService has leaked IntentReceiver amth#cd0bee8 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1159)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:946)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1302)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1282)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at amrb.run(:com.google.android.gms:4414)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61) 04-24 15:17:38.545 2048-2048/com.google.android.gms.persistent E/ActivityThread: Service com.google.android.location.places.service.PlaceDetectionAsyncService has leaked IntentReceiver amth#b6a0290 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service com.google.android.location.places.service.PlaceDetectionAsyncService has leaked IntentReceiver amth#b6a0290 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1159)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:946)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1302)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1282)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at amrb.run(:com.google.android.gms:4414)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61) 04-24 15:17:42.411 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:42.411 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation()
MainActivity.java
package com.teslaqubitsins.fasih.teslahcm;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
private static final String TAG = MainActivity.class.getSimpleName();
private BottomNavigationView bottomNavigation;
private Fragment fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
bottomNavigation = (BottomNavigationView)findViewById(R.id.navigation1);
bottomNavigation.inflateMenu(R.menu.menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.bb_menu_home:
fragment = new HomeFragment();
break;
case R.id.bb_menu_contact:
fragment = new ContactFragment();
break;
case R.id.bb_menu_manage:
fragment = new ManageFragment();
break;
case R.id.bb_menu_queries:
fragment = new QueriesFragment();
break;
case R.id.bb_menu_careers:
fragment = new CareersFragment();
break;
default:
fragment = new HomeFragment();
}
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, fragment).commit();
return true;
}
});
}
}
Replace:
FragmentTransaction ft = getFragmentManager().beginTransaction();
With:
FragmentTransaction ft = getChildFragmentManager().beginTransaction();

Calling fragment layout in an Activity

I am trying to call a fragment that acts as a side bar menu but when I try to run my app it says application has stopped. I have been trying all the ways I found on the internet. This is what I made so far.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.user.sample.MainActivity">
<TextView
android:onClick="menuHeader"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="☰"
android:layout_alignParentTop="true"
android:background="#931d21"
android:gravity="center_vertical"
android:paddingLeft="10dp" />
<fragment
android:name="com.example.user.sample.MenuFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment_container" />
</LinearLayout
MainActivity.java
package com.example.user.sample;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
public class MainActivity extends FragmentActivity {
private MenuFragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void menuHeader(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment = new MenuFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
MenuFragment.java
package com.example.user.sample;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {#link OnListFragmentInteractionListener}
* interface.
*/
public class MenuFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public MenuFragment() {
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static MenuFragment newInstance(int columnCount) {
MenuFragment fragment = new MenuFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
// void onListFragmentInteraction(DummyItem item);
}
}
LOGCAT
02-10 10:11:19.236 3643-3643/com.example.user.sample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.sample, PID: 3643
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.sample/com.example.user.sample.MainActivity}: android.view.InflateException: Binary XML file line #23: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3190)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.view.InflateException: Binary XML file line #23: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:450)
at android.app.Activity.setContentView(Activity.java:2366)
at com.example.user.sample.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300) 
at android.app.ActivityThread.access$1000(ActivityThread.java:211) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6946) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
Caused by: java.lang.RuntimeException: com.example.user.sample.MainActivity#197f8eef must implement OnListFragmentInteractionListener
at com.example.user.sample.MenuFragment.onAttach(MenuFragment.java:75)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1231)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1472)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1691)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3413)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:511) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:415) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:366) 
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:450) 
at android.app.Activity.setContentView(Activity.java:2366) 
at com.example.user.sample.MainActivity.onCreate(MainActivity.java:16) 
at android.app.Activity.performCreate(Activity.java:6575) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300) 
at android.app.ActivityThread.access$1000(ActivityThread.java:211) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6946) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
The fragment will show when the ☰ is clicked. But the app crashes because of the existence of fragment inside the acitvity layout.
I already have a layout for the fragment and I didn't make any changes to it so I don't know if I need to post it here. Thanks
Your error is this
.RuntimeException: com.example.user.sample.MainActivity#197f8eef must implement OnListFragmentInteractionListener
So your activity needs to implement OnListFragmentInteractionListener.
So add
public class MainActivity extends FragmentActivity implements
OnListFragmentInteractionListener{
....

Android crash during fragment replace action

I am writing a simple app to learn Java, specifically how to manage fragment transactions.
The app has one MainActivity and three fragments (FragmentDefault, added to the MainActivity by default; and Fragments one and two, which can be added on a button click in MainActivity).
My app can handle on fragment transaction, but crashes during the second, regardless of the order of the transactions.
The MainActivity.java file is as follows:
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
transaction.replace(R.id.fragment_container, frag1);
transaction.commit();
transaction.addToBackStack(null);
}
public void openFrag2(View view) {
transaction.replace(R.id.fragment_container, frag2);
transaction.commit();
transaction.addToBackStack(null);
}
}
with .XML file:
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
transaction.replace(R.id.fragment_container, frag1);
transaction.commit();
transaction.addToBackStack(null);
}
public void openFrag2(View view) {
transaction.replace(R.id.fragment_container, frag2);
transaction.commit();
transaction.addToBackStack(null);
}
}
My three fragment files are essentially identical with java files:
package com.example.connor.fragmenttestapp;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
}
and .XML files:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.connor.fragmenttestapp.Fragment1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/frag1_text"
android:id="#+id/textView" />
</FrameLayout>
The logcat file for this error shows :
02-01 21:01:51.608 15413-15413/com.example.connor.fragmenttestapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.connor.fragmenttestapp, PID: 15413
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10896)
at android.view.View$PerformClick.run(View.java:22546)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5702) 
at android.widget.TextView.performClick(TextView.java:10896) 
at android.view.View$PerformClick.run(View.java:22546) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: java.lang.IllegalStateException: commit already called
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:630)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:603)
at com.example.connor.fragmenttestapp.MainActivity.openFrag2(MainActivity.java:37)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5702) 
at android.widget.TextView.performClick(TextView.java:10896) 
at android.view.View$PerformClick.run(View.java:22546) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
What is causing this error and how can I fix the code to avoid it?
You need to begin a transaction each time instead of creating only one.
You can have a single FragmentManager, but must beginTransition every time.
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = = getSupportFragmentManager();
if (savedInstanceState == null) {
fm.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
fm.beginTransition().replace(R.id.fragment_container, frag1)
.addToBackStack(null).commit();
}
public void openFrag2(View view) {
fm.beginTransition().replace(R.id.fragment_container, frag2);
.addToBackStack(null).commit();
}
}
You can use this two functions
public void openNoHistoryFragment(Fragment fragment) {
FragmentTransaction ft = getActivity().getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.container,
fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commitAllowingStateLoss();
}
public void openFragment(Fragment fragment) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
// transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
create this each time when your want to make transaction.
transaction = getSupportFragmentManager().beginTransaction();

Android spinner onselecteditem spinner is null?

below find all my code and xml. My problem is that the spinner (in code spinner1) is null for some reason I can't determine and I get no errors other than the app failing to run. Any help would be appreciated!
activity_main.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".MainActivity" />
MainActivity.java:
package com.example.passwordplayground;
import java.util.Locale;
import com.example.MyApplication.EncryptionSpinner;
import com.example.MyApplication.MyApplication;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Spinner spinner1 = (Spinner) findViewById(R.id.encryptionSpin);
if (spinner1 == null)
System.out.println("Spinner1 is null");
else
System.out.println("Funcion is null");
spinner1.setOnItemSelectedListener(new EncryptionSpinner());
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return ("Practicality").toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if (getArguments().getInt(ARG_SECTION_NUMBER)==1) {
rootView = inflater.inflate(R.layout.encryption,container, false);
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==2) {
rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText("I'm second!");
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==3) {
//dummyTextView.setText("I'm third");
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==4) {
//dummyTextView.setText("I'm fourth and last!");
}
return rootView;
}
}
}
encryption.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$Encryption" >
<Spinner
android1:id="#+id/encryptionSpin"
android1:layout_width="fill_parent"
android1:layout_height="wrap_content"
android1:layout_alignParentTop="true"
android1:layout_centerHorizontal="true"
android1:layout_marginTop="14dp"
android1:background="#color/orange"
android1:entries="#array/cryptArray" />
</RelativeLayout>
EncryptionSpinner.java:
package com.example.MyApplication;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class EncryptionSpinner implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Toast toast = Toast.makeText(MyApplication.getAppContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG);
toast.show();
System.out.println(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
Logcat Error:
04-09 01:16:28.637: I/System.out(1440): Spinner1 is null
04-09 01:16:28.657: D/AndroidRuntime(1440): Shutting down VM
04-09 01:16:28.657: W/dalvikvm(1440): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
04-09 01:16:28.692: E/AndroidRuntime(1440): FATAL EXCEPTION: main
04-09 01:16:28.692: E/AndroidRuntime(1440): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.passwordplayground/com.example.passwordplayground.MainActivity}: java.lang.NullPointerException
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.os.Handler.dispatchMessage(Handler.java:99)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.os.Looper.loop(Looper.java:137)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-09 01:16:28.692: E/AndroidRuntime(1440): at java.lang.reflect.Method.invokeNative(Native Method)
04-09 01:16:28.692: E/AndroidRuntime(1440): at java.lang.reflect.Method.invoke(Method.java:525)
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-09 01:16:28.692: E/AndroidRuntime(1440): at dalvik.system.NativeStart.main(Native Method)
04-09 01:16:28.692: E/AndroidRuntime(1440): Caused by: java.lang.NullPointerException
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.example.passwordplayground.MainActivity.onCreate(MainActivity.java:65)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.Activity.performCreate(Activity.java:5133)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-09 01:16:28.692: E/AndroidRuntime(1440): ... 11 more
Layouts' Gui:
if you want to user spinner from activity_main then you have to put it in that file because right now its not their and it is in encryption.xml file.
make activity_main.xml like below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$Encryption" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black"
tools:context=".MainActivity" />
<Spinner
android1:id="#+id/encryptionSpin"
android1:layout_width="fill_parent"
android1:layout_height="wrap_content"
android1:layout_alignParentTop="true"
android1:layout_centerHorizontal="true"
android1:layout_marginTop="14dp"
android1:background="#color/orange"
android1:entries="#array/cryptArray" />
</RelativeLayout>
You have inflated the layout activity_main in your activity and you are trying to access the Spinner which is not in your activity_main layout.
In that point you are getting error. As the Spinner does not resides in your activity_main layout.
So will have to initialize your Spinner in DummySectionFragment onCreateView method as below:
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if (getArguments().getInt(ARG_SECTION_NUMBER)==1) {
rootView = inflater.inflate(R.layout.encryption,container, false);
Spinner spinner1 = (Spinner)rootView.findViewById(R.id.encryptionSpin);
}
you see there is null pointer exception.
means you have no control on the components you are using.
this could be caused due to two reason
1. two components have same ids.
2. wrong defined layout.
in your case you are using layout
R.layout.activity_main
while your layout name is
R.layout.encryption
change the name of layout and you are ready to go.
You putting ViewPager in activity_mail layout and Spinner in encryption.xml if u setting content view as any one of xml. so any one ll identify another one will not be identify. It will throw the null pointer exception.
R.layout.activity_main having ViewPager
R.layout.encryption having Spinner
if u set setcontentView(R.layout.activity_main) then findViewById(R.id.encryptionSpin); line will throw null pointer.
if u set setcontentView(R.layout.encryption) then mViewPager = (ViewPager) findViewById(R.id.pager); line will throw null pointer.

Categories

Resources