Calling getActivity() inside a Fragment returns null - java

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.

Related

My AsyncTask in another class is causing NullPointerException when it is called in this class

I am quite new to android development and I am facing a NullPointerException when I am trying to call an AsyncTask which is an inner class in another class.
I believe it is the way I am instantiating it but this is what I have:
// This onClick is in my adapter class - which is a separate Java File and class
#Override
public void onClick(View v) {
UploadRes uploadRes = new UploadRes();
UploadRes.UploadResConfirm uploadResConfirm = uploadRes.new UploadResConfirm(v.getContext());
uploadResConfirm.execute(fileName, filePath);
}
public class UploadResConfirm extends AsyncTask<String, String, String> {
Dialog dialog;
Context context;
public UploadResConfirm(Context context){
this.context = context;
}
#Override
protected void onPreExecute(){
dialog = new Dialog(UploadRes.this);
dialog.setTitle("Currently uploading");
dialog.show();
}
I believe it has got something to do with the dialog box itself being instantiated in the AsyncTask class.
The error stack trace on Logcat - its the Dialog, I think its in the wrong place...
java.lang.NullPointerException
at codeman.androapp.UploadRes$UploadResConfirm.onPreExecute(UploadRes.java:246)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
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)
Some help if any would be much obliged.
Instead of dialog = new Dialog(UploadRes.this);
Try
dialog = new Dialog(context);
your are passing a wrong context to create dialog.

Layout inflater is null

Can someone help me?
I don't know why have I javaNullExepction in LayoutInflater.Here is my code :
This code is in fragment :
ServiceManager.getInstance().getCampaign( new Callback <Campaign>() {
#Override
public void success(Campaign campaign, Response response) {
campaigns = campaign;
adapter = new RecyclerCampaignAdapter(getActivity(), campaign);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).marginProvider(adapter).showLastDivider().build());
adapter.notifyDataSetChanged();
if (progressBar.isShown()) {
progressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(getActivity(), "Failed" + retrofitError, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
here is code in my adapter :
public RecyclerCampaignAdapter (Activity activity, Campaign campaignList) {
this.activity = activity;
this.campaignList = campaignList;
this.inflater= LayoutInflater.from(activity);
}
I think getActivity() == null I don't know how can I fix it.
java.lang.NullPointerException
at android.view.LayoutInflater.from(LayoutInflater.java:212)
at tr.org.yyd.yeryuzudoktorlari.adapter.RecyclerCampaignAdapter.(RecyclerCampaignAdapter.java:38)
at tr.org.yyd.yeryuzudoktorlari.fragment.CampaignFragment$1.success(CampaignFragment.java:69)
at tr.org.yyd.yeryuzudoktorlari.fragment.CampaignFragment$1.success(CampaignFragment.java:65)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5756)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
EDIT:
I use replace method on frgment transaction when user clicks on an item from menu.So CampaignFragment works okey when the user clicks in first time but it crashes when user clicks again while it is still on.
If I change into another fragment and come back to CampaginFragment there is no crash.
The answer just that.I don't know how that fix it but it worked.It's just a control.
if (getActivity() != null) {
adapter = ....

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;
}

Unable to start activity ComponentInfo{..} : java.lang.NullPointerException via Crashlytics. Cannot reproduce

For ~20% of my user-base, they are getting a Unable to start activity ComponentInfo{..} : java.lang.NullPointerExceptionFATAL Exception. I monitor the exceptions remotely via Crashlytics, so I have the stacktrace. The only problem is, there is no line number.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.falk.fietsroutes.app/com.falk.fietsroutes.app.HomeActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2340)
at android.app.ActivityThread.access$800(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by: java.lang.NullPointerException
at com.falk.fietsroutes.app.SearchResultsFragment.onCreateView()
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1044)
at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1853)
at android.app.Activity.performCreate(Activity.java:5392)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2246)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2340)
at android.app.ActivityThread.access$800(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(NativeStart.java)
I've read many reports from people with the same error, which all came down to something in their code being null (ofcourse, because it's a nullpointer). But I can't track it down because I cannot reproduce it (I only have one device which seems to work fine), and the stack trace doesn't help.
At first sight I couldn't find anything that could be null in SearchResultsFragment.onCreateView() (because that is where the NPE gets thrown right?)
If any of you could point me in the right direction or know how I could get the line number where the exception, it would be appreciated!
Here is the code of SearchResultsFragment.onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Set orientation
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
// Get the rootview in the fragment
View rootView = inflater.inflate(R.layout.fragment_search_results, container, false);
// Get settings instance
mSettings = Settings.getInstance();
// Init the mRoutes arraylist
mRoutes = new ArrayList<Route>();
// Get the gridview and set the adapters (animation adapter and the gridview adapter)
GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
SearchResultCardsAdapter searchAdapter = new SearchResultCardsAdapter(getActivity(), inflater);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(searchAdapter);
swingBottomInAnimationAdapter.setAbsListView(gridView);
swingBottomInAnimationAdapter.setInitialDelayMillis(300);
mAdapter = swingBottomInAnimationAdapter;
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("Grid item click", "Clicked!");
Route route = mRoutes.get(i);
Intent routeDetailIntent = new Intent(getActivity(), RouteDetailActivity.class);
routeDetailIntent.putExtra("routeId", route.id);
// Analytics
Tracker t = ((AppDelegate) getActivity().getApplication()).getTracker(
AppDelegate.TrackerName.APP_TRACKER);
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory("Routes")
.setAction("View")
.setLabel(Integer.toString(route.id))
.build());
startActivity(routeDetailIntent);
}
});
gridView.setAdapter(mAdapter);
// Set the infinite scroll listener
gridView.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to your AdapterView
loadMoreRoutes(page, totalItemsCount);
// or customLoadMoreDataFromApi(totalItemsCount);
}
});
// Show the progressbar
mProgressBar = (SmoothProgressBar)rootView.findViewById(R.id.search_results_progressbar);
mProgressBar.progressiveStart();
// Inflate the layout for this fragment
return rootView;
}
Maybe others will benefit from my mistake. The problem was that I used pro-guard and Android Studio to sign my Android App, and I had to keep-attributes some properties so Crashlytics could read the line number and class name.
-keepattributes SourceFile,LineNumberTable
Via

Why does this cause a NullPointerException?

I have a program which is as follows, Can anyone tell me what is the reason for getting an NPE.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondClass x = new secondClass();
x.sText("Test Spring");
}
}
public class secondClass extends MainActivity {
public void sText(String s) {
TextView text = (TextView) findViewById(R.id.text);
text.setText(s);
}
}
Mainfest
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
...
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/text"
/>
</RelativeLayout>
LogCat
08-16 01:31:11.320 15032-15032/? E/Trace: error opening trace file: No such file or directory (2)
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: App crashed! Process: com.example.myapplication
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: App crashed! Package: com.example.myapplication v1 (1.0)
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: Application Label: My Application
08-16 01:31:11.420 15032-15032/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.access$600(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:110)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java)
at com.example.myapplication.secondClass.sText(secondClass.java:13)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:14)
at android.app.Activity.performCreate(Activity.java)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
To my understanding, this should instantiate and initialize a secondClass object then call its sText() method. The sText method should then store a reference in TextView. Next it calls the setText() method on TextView, which changes the text in the TextView to what was passed into sText().
The logcat says it throws a NullPointerException but I'm not entirely sure why. If this is a rookie mistake, it's because I am a rookie. Thank you.
You need to Override onCreate in your secondActivity and have setContentView(R.layout.mylayout). Then you can initialize your textview.
Also you need to start an Activity using intent
Intent intent = new Intent(MainActivtiy.this,SecondActivity.class);
startActivity(intent);
Remember to make an entry for the activity (SecondActivtiy) in manifest file
If you need to pass the string to second activity use intent.putExtra
Intent intent = new Intent(MainActivtiy.this,SecondActivity.class);
intent.putExtra("key",mystring);
startActivity(intent);
Then in secondActivity
TextView tv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mysecondlayout);
tv = (TextView) findViewByid(R.id.textView1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
tv.setText(value);
//get the value based on the key
}
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String, android.os.Bundle)
You can findViewById of the current view herarchy set to the activity.
Also you need to startActivity using intent rather doing this econdClass x = new secondClass()

Categories