NullPointer Exception on Onclick of Button in FragmentActivity android - java

I'm Using Fragments in my Android app, I have two class one is FirstClass.java which extends FragmentActivity and SecondClass extends Fragments and has button in its layout file.
So on Click of that button i'm calling "mylistener" function like this
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.64"
android:text="Button"
android:onClick="mylistener"
/>
and FirstClass.java
public class FirstClass extends FragmentActivity {
Button btnSet1;
int mHour = 15;
int mMinute = 15;
/** This handles the message send from TimePickerDialogFragment on setting Time */
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message m){
/** Creating a bundle object to pass currently set Time to the fragment */
Bundle b = m.getData();
/** Getting the Hour of day from bundle */
mHour = b.getInt("set_hour");
/** Getting the Minute of the hour from bundle */
mMinute = b.getInt("set_minute");
/** Displaying a short time message containing time set by Time picker dialog fragment */
Toast.makeText(getBaseContext(), b.getString("set_time"), Toast.LENGTH_SHORT).show();
btnSet1.getText().toString();
btnSet1.setText("set_time");
}
};
public void mylistener(View v){
/** Creating a bundle object to pass currently set time to the fragment */
Bundle b = new Bundle();
/** Adding currently set hour to bundle object */
b.putInt("set_hour", mHour);
/** Adding currently set minute to bundle object */
b.putInt("set_minute", mMinute);
/** Instantiating TimePickerDialogFragment */
TimePickerDialogFragment timePicker = new TimePickerDialogFragment(mHandler);
/** Setting the bundle object on timepicker fragment */
timePicker.setArguments(b);
/** Getting fragment manger for this activity */
FragmentManager fm = getSupportFragmentManager();
/** Starting a fragment transaction */
FragmentTransaction ft = fm.beginTransaction();
/** Adding the fragment object to the fragment transaction */
ft.add(timePicker, "time_picker");
/** Opening the TimePicker fragment */
ft.commit();
};
}
Now i'm able to get Timer Dialog on OnClick of Button, When tried to display that time format in Button getting NullPointer exception, I know this exception is because of button declaration in FirstClass FragmentActivity which is not present here, Please Help me to solve this issue.
03-09 10:40:53.222: E/AndroidRuntime(23637): java.lang.NullPointerException
03-09 10:40:53.222: E/AndroidRuntime(23637): at com.bikepooling.FirstClass$1.handleMessage(FirstClass.java:63)
03-09 10:40:53.222: E/AndroidRuntime(23637): at android.os.Handler.dispatchMessage(Handler.java:110)
03-09 10:40:53.222: E/AndroidRuntime(23637): at android.os.Looper.loop(Looper.java:193)
03-09 10:40:53.222: E/AndroidRuntime(23637): at android.app.ActivityThread.main(ActivityThread.java:5292)
03-09 10:40:53.222: E/AndroidRuntime(23637): at java.lang.reflect.Method.invokeNative(Native Method)
03-09 10:40:53.222: E/AndroidRuntime(23637): at java.lang.reflect.Method.invoke(Method.java:515)
03-09 10:40:53.222: E/AndroidRuntime(23637): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
03-09 10:40:53.222: E/AndroidRuntime(23637): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)

no need of this method,
public void mylistener(View v)
use this one
return new TimePickerDialog(Common.con, mTimeSetListener2, pHour, pMinute, false);
and also initialize the button for ex
btn = view.findviewbyid(...);
i hope will be work fine,

you have not initialised btnSet1
try doing this in onViewCreated:
btnSet1 = view.findViewById(R.id.b1);

Related

App crashes on launch in emulator

I'm new in android development and I'm trying to build a kind of book listing kind of app for a project in my class. The prof's favorite motto is "whatever you don't know google it". That's not bad when you semi-know what to do but since we are learning java along with android development that's not helpful since java can seem a bit alien.
Anyways basing my app in a contact app this is how my MainActivity looks
//MainActivity.java
package com.iekproject.siegfried.libraryapp;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity
implements LibraryFragment.LibraryFragmentListener, DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
//key for storing a book's Uri in a Bundle passed to a fragment
public static final String BOOK_URI = "book_uri";
private LibraryFragment libraryFragment; //displays library aka book list
//displays LibraryFragment when MainActivity first loads
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//if layout contains fragmentContainer, the phone layout is in use. Create and display
//a LibraryFragment
if (savedInstanceState == null && findViewById(R.id.fragmentContainer) != null) {
//create LibraryFragment
libraryFragment = new LibraryFragment();
//add the fragment to the FrameLayout
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentContainer, libraryFragment);
transaction.commit(); //displays LibraryFragment
}
else {
libraryFragment =
(LibraryFragment) getSupportFragmentManager().
findFragmentById(R.id.DetailFragment);
}
}
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
//displays DetailFragment for selected book
#Override
public void onBookSelected(Uri bookUri) {
getSupportFragmentManager().popBackStack();
displayBook(bookUri, R.id.rightPaneContainer);
}
//displays AddEditFragment to add a new book. Possibly what I'll also have to change to make it
//scan/update the book list
#Override
public void onAddBook() {
displayAddEditFragment(R.id.rightPaneContainer, null);
}
//displays a book
private void displayBook(Uri bookUri, int viewID) {
DetailFragment detailFragment = new DetailFragment();
//specify book's Uri as an argument to the DetailFragment
Bundle arguments = new Bundle();
arguments.putParcelable(BOOK_URI, bookUri);
detailFragment.setArguments(arguments);
//use a FragmentTransaction to display the DetailFragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, detailFragment);
transaction.addToBackStack(null);
transaction.commit(); //causes DetailFragment to display
}
//displays fragment for adding new or editing existing book
private void displayAddEditFragment(int viewID, Uri bookUri) {
AddEditFragment addEditFragment = new AddEditFragment();
//if editing existing book, provide bookUri as an argument
if (bookUri != null) {
Bundle arguments = new Bundle();
arguments.putParcelable(BOOK_URI, bookUri);
addEditFragment.setArguments(arguments);
}
//use a FragmentTransaction to display the AddEditFragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, addEditFragment);
transaction.addToBackStack(null);
transaction.commit(); //causes AddEditFragment to display
}
//return to book list when displayed book deleted
#Override
public void onBookDeleted() {
//removes top of back stack
getSupportFragmentManager().popBackStack();
libraryFragment.updateLibrary(); //refresh book list
}
//displays the AddEditFragment to edit an existing book. Maybe it can be used as Move or sth
/*#Override
public void onEditBook(Uri bookUri) {
displayAddEditFragment(R.id.rightPaneContainer, bookUri);
}*/
//update GUI after the new book or updated book saved
#Override
public void onAddEditCompleted(Uri bookUri) {
//removes top of back stack
getSupportFragmentManager().popBackStack();
libraryFragment.updateLibrary(); //refresh book list
if (findViewById(R.id.fragmentContainer) == null){ //tablet
//removes top of back stack
getSupportFragmentManager().popBackStack();
//on tablet, displays the book that was just added or edited
displayBook(bookUri, R.id.rightPaneContainer);
}
}
}
and this is the logcat
04-12 16:14:38.807 5796-5796/? I/art: Not late-enabling -Xcheck:jni (already on)
04-12 16:14:38.808 5796-5796/? W/art: Unexpected CPU variant for X86 using defaults: x86
04-12 16:14:38.926 5796-5796/com.iekproject.siegfried.libraryapp W/System: ClassLoader referenced unknown path: /data/app/com.iekproject.siegfried.libraryapp-1/lib/x86
04-12 16:14:38.945 5796-5796/com.iekproject.siegfried.libraryapp I/InstantRun: starting instant run server: is main process
04-12 16:14:38.991 5796-5796/com.iekproject.siegfried.libraryapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-12 16:14:39.119 5796-5796/com.iekproject.siegfried.libraryapp D/AndroidRuntime: Shutting down VM
04-12 16:14:39.119 5796-5796/com.iekproject.siegfried.libraryapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.iekproject.siegfried.libraryapp, PID: 5796
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.iekproject.siegfried.libraryapp/com.iekproject.siegfried.libraryapp.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:207)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.iekproject.siegfried.libraryapp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
any help is appreciated
You just need to set the content view after setting the toolbar. You can write like this :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.activity_main);
The app is crashing because you are first setting the view and then setting the toolbar.

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.

I can't find this NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have an issue I need help with. I am running into a NullPointerException no matter what I do with this app, and at this point it is seriously holding up this project. I have reviewed the logcat multiple times, made changes and re run the app and every time it turns out a nullpointerexception. For the life of me I can't seem to figure out what is causing it. Can someone point out where it is, and if possible, why it occurred since as far as I can tell I have everything assigned a value.
GameStart.java:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity {
/**
* Necessary activity variables
*/
int clickCount = 0;
TextView storyText;
Button advanceGame;
DecisionFragment decisionFragment;
ControlsFragment controlsFragment;
public View.OnClickListener decisionTime = new View.OnClickListener(){
public void onClick(View v) {
clickCount = clickCount + 1; // Increments clickCount by 1 per click
// /**
// * Will handle checking how far into the story the player is
// * and update components as necessary.
// */
// switch (clickCount) {
// case 1:
// storyText.setText(R.string.story_opening_two);
// break;
//
// case 2:
// FragmentTransaction decisionTime = fragmentManager.beginTransaction();
// // Replace the fragment currently inside of the fragmentContainer
// decisionTime.replace(R.id.fragmentContainer, decisionFragment);
// decisionTime.commit();
// break;
//
// default:
// System.out.println("An error occurred");
// }
// System.out.println(clickCount);
}
};
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
// UI element handles
advanceGame = (Button) findViewById(R.id.advanceButton);
storyText = (TextView) findViewById(R.id.storyText);
decisionFragment = new DecisionFragment();
controlsFragment = new ControlsFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// UI will add the ControlsFragment in it's starting state for that activity.
fragmentTransaction.add(R.id.fragmentContainer, controlsFragment).commit();
// Sets the advanceButton to run decisionTime method
advanceGame.setOnClickListener(decisionTime);
}
}
LogCat:
12-07 13:16:10.142 19915-19915/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.saphiric.simproject, PID: 19915
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:1069)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.saphiric.simproject.GameStart.onCreate(GameStart.java:75)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
            at android.app.ActivityThread.access$800(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5872)
            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:1069)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
            at dalvik.system.NativeStart.main(Native Method)
The null pointer happens at line 75 , i.e.
advanceGame.setOnClickListener(decisionTime);
Here, the only thing that can be null is advanceGame. This means that
advanceGame = (Button) findViewById(R.id.advanceButton);
is not able to find your button from your view. Check the id of the button if its exactly the same as you defined it in your android xml.
I believe that advanceGame is null.
You can't find button by findViewById(R.id.advanceButton);
NPE is at line 75
advanceGame.setOnClickListener(decisionTime);
it is clear from
at com.saphiric.simproject.GameStart.onCreate(GameStart.java:75)
Looks like at
advanceGame = (Button) findViewById(R.id.advanceButton);
view was not found. You can debug that or add check at 75
if(null != advanceGame) advanceGame = (Button) findViewById(R.id.advanceButton);
I think just check #+id of your activity_game_start.xml layout of advanceGame button
it might have different 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;
}

Calling getActivity() inside a Fragment returns null

excuse the trouble I was trying to make a listview for parsing a page for my app, I'll explain: I have a actionbar formed by Fragment.
When instazia the fragment, opening the app the first time "getActivity" does not return null, is the next time, when I start the AsyncTask
In the fragment in which I will stop parsing this error:
java.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:104)
at com.megadown.megacodownloader.ParsingArrayAdapter.<init>(ParsingArrayAdapter.java:30)
at com.megadown.megacodownloader.Tab_Search$ParsingPaginaWeb.onPostExecute(Tab_Search.java:264)
at com.megadown.megacodownloader.Tab_Search$ParsingPaginaWeb.onPostExecute(Tab_Search.java:125)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
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:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
Code Java that refers:
protected void onPostExecute(String result)
{
// dopo che ho eseguito il parsing mostro i dati nella listview
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
If you want I can post the code of the ArrayAdapter.
Thank you in advance
First, make sure myActivity has the correct value:
protected void onPostExecute(String result) {
Activity myActivity = getActivity();
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
Next, point is, you can't be sure that your activity and fragment is still active in onPostExecute().
For example, the user could have pressed 'back' button or rotated the screen, which would re-create the activites and fragments.
So, the good code is:
protected void onPostExecute(String result) {
Activity myActivity = getActivity();
if (myActivity==null) return; // Fragment not active anymore, bail out
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
Fragment's getActivity() will only return expectable value while the associated activity has done onCreate method.

Categories