OnListItemClick NullpointerException - java

Hello I am currently getting error on some of my apps on android market :
This is the stacktrace :
java.lang.NullPointerException
at ****.****.MainActivity.onListItemClick(MainActivity.java:110)
at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
at android.widget.AdapterView.performItemClick(AdapterView.java:284)
at android.widget.ListView.performItemClick(ListView.java:3513)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:870)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
at dalvik.system.NativeStart.main(Native Method)
The code part where it goes wrong :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
mMediaPlayer.stop();
Sound s = (Sound) l.getItemAtPosition(position);
mMediaPlayer = MediaPlayer.create(this, s.getSoundResourceId());
mMediaPlayer.start();
}
Mostly of the time it's working (playing sounds) but sometimes it gives a nullpointerexception and I don't know why maybe something with the MediaPlayer or super.onListItemClick() ?
Thanks in advance

Probably s is null? Can you reproduce/debug?
could you provide the code of getItemAtPosition(position) of your list adapter implementation. and may wrap
if (s != null) {
mMediaPlayer = MediaPlayer.create(this, s.getSoundResourceId());
mMediaPlayer.start();
}
edit. hmm i was on the wrong line. you should wrap starting the media player with a null check because if you read the doc:
Returns
a MediaPlayer object, or null if creation failed
And then try to find out why creation fails.

Related

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 = ....

RejectedExecutionException when loading bitmaps for ListView with asyncTask

I'm trying to create a ListView with bitmaps that are generated on demand. I'm using https://github.com/chrisbanes/Android-BitmapCache to cache the bitmaps
I'm using a SimpleAdapter, with this :
setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object object,String string) {
if( string.startsWith("ClassName:") ){
final ImageView yourImageView=(ImageView) view;
AsyncTask<String, Void, Bitmap> imageLoadAsyncTask = new AsyncTask<String, Void, Bitmap>() {
String cname;
#Override
protected Bitmap doInBackground(String... classnames) {
cname=classnames[0];
return db.getCharIcon(classnames[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
yourImageView.setImageBitmap(bitmap);
}
};
imageLoadAsyncTask.execute(string.substring(TextUtils.getTrimmedLength("ClassName:")));
return true;
}
return false;
}
}
the getCharIcon function is here :
Bitmap getCharIcon(String classname){
Bitmap modBmp;
CacheableBitmapDrawable cacheBmp=mCache.get(classname);
if(cacheBmp==null)
{
modBmp=createCharIcon(classname);
mCache.put(classname,modBmp);
}
else
{
modBmp=cacheBmp.getBitmap();
}
return modBmp;
}
where createCharIcon generates the bitmap this way (I have yet to implement the final version that selects the good portion of the image):
Bitmap createCharIcon(String classname)
{
Bitmap modBmp = Bitmap.createBitmap(srcBmp,0,0,60,60);
return modBmp;
}
Sadly I am getting this error :
07-02 14:13:04.248 11592-11592/com.lectem.gecharacters E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1876)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:774)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1295)
at android.os.AsyncTask.execute(AsyncTask.java:394)
at com.lectem.gecharacters.CharFragment$1.setViewValue(CharFragment.java:110)
at android.widget.SimpleAdapter.bindView(SimpleAdapter.java:168)
at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:126)
at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
at android.widget.AbsListView.obtainView(AbsListView.java:1294)
at android.widget.ListView.makeAndAddView(ListView.java:1730)
at android.widget.ListView.fillDown(ListView.java:655)
at android.widget.ListView.fillSpecific(ListView.java:1287)
at android.widget.ListView.layoutChildren(ListView.java:1573)
at android.widget.AbsListView.onLayout(AbsListView.java:1147)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1252)
at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1241)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1047)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1252)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1128)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1045)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
I get this error when I scroll the list back too fast, so I suppose it is linked with the number of asyncTasks I can use...
I'm really not sure if this is how I should do it or not, but the library bitmapLruCache needs to be ran on something else than the main thread.
Usually, that error means that you are trying to use too many AsyncTasks at once. In an AdapterView, this can occur if you are forking an AsyncTask for every item (e.g., every row in a ListView) without taking into account row recycling, and the user flings the list.
Quoting the library's documentation:
If you wish for the library and recycling feature to work, you MUST use the bundled CacheableImageView wherever possible.
Since you appear to be using this in an AdapterView, please make sure that you are using CacheableImageView.

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

get selected object from listview

I will find a way to get a selected item in my list view and then to cast in my object type, but i get an error i think is to big to see whats is wrong. Can you help me ?
My code :
mListMenu = (ListView) findViewById(R.id.listView_tracks);
mListMenu.setAdapter(new TracksListAdapter(this, TrackManager.getAllTrackFromTel(new DataBaseHelper(this))));
mListMenu.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View arg1,
int position, long arg3) {
Track selectedItem = (Track) adapter.getAdapter().getItem(position);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putLong("trackselected",selectedItem.getTrackid());
intent.putExtras(bundle);
//Envoi du resultat Ă  l'origine
setResult(RESULT_OK, intent);
finish();
}
});
I get this error :
FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.Integer
at com.milesbox.sport.tracker.ListTracksActivity$1.onItemClick(ListTracksActivity.java:44)
at android.widget.AdapterView.performItemClick(AdapterView.java:284)
at android.widget.ListView.performItemClick(ListView.java:3746)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:1980)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3691)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
at dalvik.system.NativeStart.main(Native Method)
Thank you FD_, when i say it was too big to see what is wrong, this is my method(getItem) that return an item that was wrong (copy paste too quick).

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