Where to create Android Spinner in Fragment? - java

My question is rather simple: how can one use(populate) Spinners in Fragments? Or better said, what is wrong with my code below? Adding Spinner as I did is as simple as it gets, but after trying in all the different ways, nothing worked. What is FragmentPagerAdapter has to do with Spinner? If I add the Spinner from a method declared somewhere else, the spinner is populated with no problems(for example if populating the spinner from a button).
Thanks in advance
public class MainActivity extends FragmentActivity {
/**
* 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;
public List<String> fragments = new Vector<String>();
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
private MySQLite database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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); // pager
mViewPager.setAdapter(mSectionsPagerAdapter);
// We initialise the database
database = new MySQLite(this);
Spinner spin = (Spinner)findViewById(R.id.spinner1);
List<String> toSpin = new ArrayList<String>();
toSpin.add("ONE");
toSpin.add("TWO");
toSpin.add("THREE");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,toSpin);
spin.setAdapter(adapter);
}
#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;
}
/**
* 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);
fragments.add(ConnectionFragment.class.getName());
fragments.add(DataFragment.class.getName());
}
#Override
public Fragment getItem(int position) {
// we need to instantiate the list of fragments
return Fragment.instantiate(getBaseContext(),
fragments.get(position));
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#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);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class ConnectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public ConnectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View connectionView = inflater.inflate(
R.layout.fragment_main_dummy, container, false);
return connectionView;
}
}
public static class DataFragment extends Fragment {
public DataFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dataView = inflater.inflate(R.layout.fragment_linear,
container, false);
return dataView;
}
}
Logcat:
11-16 18:26:13.092: E/AndroidRuntime(16442): FATAL EXCEPTION: main
11-16 18:26:13.092: E/AndroidRuntime(16442): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iwallet/com.example.iwallet.MainActivity}: java.lang.NullPointerException
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2096)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.access$600(ActivityThread.java:138)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1207)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.os.Handler.dispatchMessage(Handler.java:99)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.os.Looper.loop(Looper.java:213)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.main(ActivityThread.java:4787)
11-16 18:26:13.092: E/AndroidRuntime(16442): at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:26:13.092: E/AndroidRuntime(16442): at java.lang.reflect.Method.invoke(Method.java:511)
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
11-16 18:26:13.092: E/AndroidRuntime(16442): at dalvik.system.NativeStart.main(Native Method)
11-16 18:26:13.092: E/AndroidRuntime(16442): Caused by: java.lang.NullPointerException
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.example.iwallet.MainActivity.onCreate(MainActivity.java:65)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.Activity.performCreate(Activity.java:5008)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2035)
11-16 18:26:13.092: E/AndroidRuntime(16442): ... 11 more

If you want to make your Spinner in your Fragment, maybe you must to declare in these Fragment in onCreatedView(). Not in onCreate() of your FragmentActivity.
And you can do it like this: Error populating spinner in a fragment

Related

setAdapter() crashes app

When I call .notifyDataSetChanged() in my constructor after I set my ArrayList my app still crashes, the same as when I call it before I call .setAdapter, it's been bothering me for hours, would love any kind of help, thanks!
public class CustomSwipeAdapter extends PagerAdapter {
private ArrayList<String> image_resources = new ArrayList<>();
private Context mContext;
private LayoutInflater mLayoutInflater;
private ImageLoader mImageLoader;
public CustomSwipeAdapter(Context context, ArrayList<String> images){
this.mContext = context;
this.image_resources = images;
}
#Override
public int getCount() {
return image_resources.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View item_view = mLayoutInflater.inflate(R.layout.swipe_layout, container, false);
final ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);
if (image_resources.get(position) != null || !image_resources.get(position).isEmpty()) {
mImageLoader.get(image_resources.get(position), new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
imageView.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
imageView.setBackgroundColor(Color.CYAN);
}
});
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
super.destroyItem(container, position, object);
}
}
Where I set my Adapter (in my Activity's onCreate()), it's most basic activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
}
Stack Trace:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 4 Pager id: sobmad.com.gamingreminder:id/view_pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class sobmad.com.gamingreminder.GamePage.CustomSwipeAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:967)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
at android.view.View.measure(View.java:15848)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChange() //Add this line in your activity

Issue with fragment OptionsMenu when recall fragment?

MainActivity
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, new LayOutOne()).commit();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.settings:
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new PrefFragment())
.addToBackStack(null)
.commit();
break;
}
return super.onOptionsItemSelected(item);
}
PrefFragmentList extends PreferenceFragment
public class PrefFragmentList extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
PrefFragment extends Fragment
public class PrefFragment extends Fragment {
private View v;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v = inflater.inflate(R.layout.layout_settings, null);
setHasOptionsMenu(true);
return v;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
menu.findItem(R.id.settings).setVisible(true).setEnabled(false).setChecked(true).setChecked(true);
super.onCreateOptionsMenu(menu, inflater);
}
PROBLEM:
MainActivity call PrefFragment from OptionMenu , when i go back to MainActivity and re-call PrefFragment, the application crash.
LOGCAT:
11-27 12:12:50.857 1387-1387/xx.xxx.myapplication D/dalvikvm: GC_FOR_ALLOC freed 228K, 3% free 9211K/9476K, paused 25ms, total 25ms
11-27 12:13:02.584 1387-1387/xx.xxxx.myapplication D/AndroidRuntime: Shutting down VM
11-27 12:13:02.584 1387-1387/xx.xxxx.myapplication W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4178b700)
11-27 12:13:02.592 1387-1387/xx.xxxx.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
android.view.InflateException: Binary XML file line #6: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
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 xx.xxx.myapplication.PrefActivity.onCreateView(PrefActivity.java:23)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f0e0052, tag null, or parent id 0xffffffff with another fragment for xx.xxxxx.myapplication.PrefFragment
at android.app.Activity.onCreateView(Activity.java:4751)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:34)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
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 xxx.xxxx.myapplication.PrefFragment.onCreateView(PrefFragment.java:23) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248) 
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613) 
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
at android.os.Handler.handleCallback(Handler.java:730) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
I try replace in OnCreateView:
final View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
with:
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.layout_settings, container, false);
} catch (InflateException e) {
}
return rootView;
Work fine and resolve this error:
LOGCAT
From the logcat: Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f0e0052, tag null, or parent id 0xffffffff with another fragment for xx.xxxxx.myapplication.PrefFragment

imported project Resources$NotFoundException

I worked at school on a programm, but when I try to start it on my pc at home I get this error (I copied the project on a usb):
02-08 14:41:57.212 1672-1672/sia.school.sia14_15 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{sia.school.sia14_15/sia.school.sia14_15.SIA_tabbedActivity}: android.content.res.Resources$NotFoundException: String array resource ID #0x7f050003
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String array resource ID #0x7f050003
at android.content.res.Resources.getStringArray(Resources.java:450)
at sia.homag.sia14_15.SIA_tabbedActivity.onCreate(SIA_tabbedActivity.java:51)
R file:
public final class R {
public static final class anim {
public static final int abc_fade_in=0x7f040000;
public static final int abc_fade_out=0x7f040001;
public static final int abc_slide_in_bottom=0x7f040002;
public static final int abc_slide_in_top=0x7f040003;
public static final int abc_slide_out_bottom=0x7f040004;
public static final int abc_slide_out_top=0x7f040005;
}
public static final class array {
public static final int a_9083646153=0x7f050002;
public static final int agregat_xy=0x7f050000;
public static final int b_9083646153=0x7f050003; //yes, the names do have some meaning
}
/*...*/
SIA_tabbedAvtivity:
public class SIA_tabbedActivity extends ActionBarActivity
{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link 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;
private String[] strArray;
private String scanResult; // Speichert das Ergebnis des Barcodescanns
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/*Error -> */ strArray = getResources().getStringArray(R.array.b_9083646153);
setContentView(R.layout.activity_sia_tabbed);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
} /*...*/
It worked fine at school. I already tried to clean and rebuild the project and deleted the R file to regenerate it but nothing worked. And yes, there is a string array in a .xml with the correct name.

How to avoid NullPointerException when re-back to FragmentActivity?

My STACK_TRACE when I came back to FragmentActivity from another activity.
I searched lot for how to solve this, and I found a clue that I need to save state of fragment.
But in that clue article said, when I use FragmentPagerAdapter, I do not need to save state.
So, I confussed. Am I use FragmentPagerAdapter correctly?
Please Help me...
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test20140320/com.example.test20140320.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.access$700(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5493)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.test20140320.MainActivity_Fragment_Tab_02.<init>(MainActivity_Fragment_Tab_02.java:98)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.support.v4.app.Fragment.instantiate(Fragment.java:402)
at android.support.v4.app.FragmentState.instantiate(Fragment.java:97)
at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1801)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:213)
at com.example.test20140320.MainActivity.onCreate(MainActivity.java:47)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
... 11 more
java.lang.NullPointerException
at com.example.test20140320.MainActivity_Fragment_Tab_02.<init>(MainActivity_Fragment_Tab_02.java:98)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.support.v4.app.Fragment.instantiate(Fragment.java:402)
at android.support.v4.app.FragmentState.instantiate(Fragment.java:97)
at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1801)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:213)
at com.example.test20140320.MainActivity.onCreate(MainActivity.java:47)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.access$700(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5493)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
at dalvik.system.NativeStart.main(Native Method)
at com.example.test20140320.MainActivity_Fragment_Tab_02.<init>(MainActivity_Fragment_Tab_02.java:98)
My code:
public MainActivity_Fragment_Tab_02()
{
super();
mContext = getActivity().getApplicationContext(); //This is line 98
tab2 = this;
}
I think the cause is at savedInstanceState, but don't know how, and how, and how....
Below is what i use FragmentPagerAdapter.
I think this is the most doubtful part.
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);
switch(position)
{
case 0:
Fragment fragment_tab1 = new MainActivity_Fragment_Tab_02(getApplicationContext());
fragment_tab1.setRetainInstance(true);
return fragment_tab1;
case 1:
Fragment fragment_tab2 = new MainActivity_Fragment_Tab_01(getApplicationContext());
fragment_tab2.setRetainInstance(true);
return fragment_tab2;
case 2:
Fragment fragment_tab3 = new MainActivity_Fragment_Tab_03(getApplicationContext());
fragment_tab3.setRetainInstance(true);
return fragment_tab3;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#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);
}
return null;
}
}
Is this code leaky??
Am I use FragmentPagerAdapter correctly? OTL....
How can I fix it....?
Please Help me!
P.S. First create fragmentActivity is successful.
Move
mContext = getActivity().getApplicationContext();
to onAttached or onActivityCreated
The problem with your code is that your activity is crashing some where else and hence you are not able to get activity reference in your fragment class. Go through the stack trace, the entire log, somewhere prior to the log that you have posted here, will be some other exception that is causing the activity to stop.
In order to use activity reference in the fragment class create on mActivity variable in your fragment and before using it check for NP if(mActivity!=null). Initialize mActivity in onAttached method of fragment class
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
mActivity = activity;
}

How to use android navigation spinner

I'm new to android, and I'm pretty bad at it. So bear with me and please be very clear and basic with your answers.
I'm trying to make a navigation spinner in android. I made it using the tutorial but I can't figure out how to modify the pages that they direct the user to. For now I'm trying to get them all to lead to the same page that just has a basic "Hello." The app keeps crashing though.
public class MainActivity extends ActionBarActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(actionBar.getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3), }), this);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getSupportActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
.getSelectedNavigationIndex());
}
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;
}
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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onNavigationItemSelected(int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
Intent intent = new Intent (this, Fibonacci.class);
startActivity(intent);
return true;
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
And:
public class Fibonacci extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the message from the intent
Intent intent = getIntent();
String message = "Hello";
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
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;
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static int fibonacciNum (int position) {
int num = 1;
if (position <= 2) {
return 1;
}
else {
num = fibonacciNum(position-1) + fibonacciNum(position-2);
return num;
}
}
}
Logcat:
07-15 10:08:13.850: E/AndroidRuntime(921): FATAL EXCEPTION: main
07-15 10:08:13.850: E/AndroidRuntime(921): Process: com.zarwanhashem.sequences, PID: 921
07-15 10:08:13.850: E/AndroidRuntime(921): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.zarwanhashem.sequences/com.zarwanhashem.sequences.Fibonacci}; have you declared this activity in your AndroidManifest.xml?
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Activity.startActivityForResult(Activity.java:3424)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Activity.startActivityForResult(Activity.java:3385)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:839)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Activity.startActivity(Activity.java:3627)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Activity.startActivity(Activity.java:3595)
07-15 10:08:13.850: E/AndroidRuntime(921): at com.zarwanhashem.sequences.MainActivity.onNavigationItemSelected(MainActivity.java:91)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.support.v7.app.ActionBarImplICS$OnNavigationListenerWrapper.onNavigationItemSelected(ActionBarImplICS.java:355)
07-15 10:08:13.850: E/AndroidRuntime(921): at com.android.internal.widget.ActionBarView$1.onItemSelected(ActionBarView.java:145)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.widget.AdapterView.access$200(AdapterView.java:48)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.os.Handler.handleCallback(Handler.java:733)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.os.Handler.dispatchMessage(Handler.java:95)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.os.Looper.loop(Looper.java:136)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-15 10:08:13.850: E/AndroidRuntime(921): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 10:08:13.850: E/AndroidRuntime(921): at java.lang.reflect.Method.invoke(Method.java:515)
07-15 10:08:13.850: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-15 10:08:13.850: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-15 10:08:13.850: E/AndroidRuntime(921): at dalvik.system.NativeStart.main(Native Method)
Manifest:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.zarwanhashem.sequences.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
android.content.ActivityNotFoundException: Unable to find explicit
activity class
{com.zarwanhashem.sequences/com.zarwanhashem.sequences.Fibonacci};
have you declared this activity in your AndroidManifest.xml?
Every activity that you intend to call in your application must be declared in the AndroidManifest file. The minimum necessary would be:
<activity android:name=".Fibonacci" />

Categories