Filling a Spinner from DataBase android - java

I'm working on a project in which i have to get some informations from the server save them in database using ormlite and after i want to display those informations on a spinner,
So to get the informations from the database to the spinner i called this method:
public Dao<ServiceProviderCompanies, Integer> getTowServiceProviderCompaniesDao() {
if (null == towServiceProviderCompaniesDao) {
try {
towServiceProviderCompaniesDao = getDao(ServiceProviderCompanies.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return towServiceProviderCompaniesDao;
}
i called it in my activity in like this:
String[] ServicePCompanies;
try {List<ServiceProviderCompanies> mSerProCom=towManager.getTowServiceProviderCompaniesDao().queryForAll();
ServicePCompanies=new String[mSerProCom.size()];
for(int i=1;i<mSerProCom.size();i++){
ServicePCompanies[i]=mSerProCom.get(i)._serviceRequesterServiceProviderCompany;
}
//CompaniesForSpinner=towManager.getTowServiceProviderCompaniesDao().queryForAll().toString();
} catch (SQLException e) {
e.printStackTrace();
}
and i filled my spinner using these lines of code
Spinner entrAssistanceList=(Spinner)findViewById(R.id.SpNomEntrAssis);
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item,ServicePCompanies);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
entrAssistanceList.setAdapter(spinnerArrayAdapter);
when i do so i get this error:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:194)
at android.widget.Spinner.onMeasure(Spinner.java:454)
at android.view.View.measure(View.java:15811)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4952)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1427)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:714)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:604)
at android.view.View.measure(View.java:15811)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4952)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1427)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:714)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:604)
at android.view.View.measure(View.java:15811)
at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1228)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:326)
at android.widget.ScrollView.onMeasure(ScrollView.java:321)
at android.view.View.measure(View.java:15811)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4952)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1427)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:714)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:604)
at android.view.View.measure(View.java:15811)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:15811)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4952)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:326)
at android.view.View.measure(View.java:15811)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4952)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1427)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:714)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:604)
at android.view.View.measure(View.java:15811)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4952)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:326)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2209)
at android.view.View.measure(View.java:15811)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2232)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1310)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1505)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1200)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4962)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5449)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
knowing that i tryed to fill the Spinner with an Array that i created manually:
ServicePCompaniesArray=new String[]{"Entreprise1","Entreprise2","Entreprise3"};
and i don't get the error so i think that the problem is when i get the informations from the database, knwoing that i debugged it and the String Array that i'm giving to the adapter is filled with the information that i get from the database, so really i don't know where the NullPointerException comes from
Thank you guys,

you don't have to put your data in this array
String[] ServicePCompanies;
just use the list you get from the database
List<ServiceProviderCompanies> mSerProCom=towManager.getTowServiceProviderCompaniesDao().queryForAll();
don't forget to override toString() method in your object (ServiceProviderCompanies)

At first print your array to Log to make sure sure about your array then do that. If the array contains null then it will give you NullPointerException.So first check the array.Better you can put a if statement to check if the array is empty or not?
Thanks..
EDIT
please replace:
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item,ServicePCompanies);
with this:
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, ServicePCompanies);
hope it will work..

Related

java.lang.VerifyError while instantiating a fragment

In android versions earlier than Lollipop, I keep getting the VerifyError while trying to instantiate a fragment, leading to an app crash. Can someone explain to me the cause of this error?
12-19 17:46:52.510 28238-28238/com.greeblu.tootl2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.greeblu.tootl2, PID: 28238
java.lang.VerifyError: com/greeblu/tootl2/fragment/ProfileGridFragment
at com.greeblu.tootl2.activity.ProfileActivity.launchGridFragment(ProfileActivity.java:289)
at com.greeblu.tootl2.fragment.ProfileOverlayFragment$3.onClick(ProfileOverlayFragment.java:123)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18439)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
at dalvik.system.NativeStart.main(Native Method)
This is how I'm calling the fragment for older android versions:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.profileContainer, new ProfileGridFragment(),fragmentTag); //Replaces the Fragment C previously in the right_container with a new Fragment B
ft.commit();
Edit:
The code for the onClick call is as follows. It is called from another fragment in the same activity
picContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((ProfileActivity) getActivity()).launchGridFragment(overlayDp, "all");
}
});
I've encountered this exact error because I had a try-catch block with exception class that is unavailable on old android versions. The block wasn't even in the constructor, it was in one of the onClick methods so the code wasn't even executed, but nevertheless app was always crashing with VerifyError as soon as I was trying to create the fragment.
Solver it by changing clause block with instanceof check:
Crashing:
try {
...
} catch (FileUriExposedException e) {
...
}
Works ok:
try {
...
} catch (Exception e) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && e instanceof FileUriExposedException) {
...
}
}
Are you using the support Fragment class from android.support.v4.app.Fragment? If so you need to be calling
getSupportFragmentManager()
instead of
getFragmentManager()
Note that the Fragment class from android.app.Fragment is now deprecated.

Android ArrayList Index Out Of Bounds

I'm fairly new to Android and am having an issue with fetching data from my database. I have an activity class which calls the database helper to get a list of questions according to a particular category. The database should then put all of the questions into an ArrayList and return them. The error seems to be occurring when I try and get the first question in the list of questions using:
Question question = questions.get(0);
Here is the relevant method in the activity class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atomic_structure_questions);
DatabaseHelper database = new DatabaseHelper(getApplicationContext());
List<Question> questions = database.getQuestions(1);
Question question = questions.get(0);
TextView questionText = (TextView) findViewById(R.id.QuestionText);
questionText.setText(question.getText());
}
Database Helper:
// Get All The Question From Database For A Specific Category And Put Them Into A List Of Question
public List<Question> getQuestions(int category) {
List<Question> questions = new ArrayList<Question>();
String selectQuery = "SELECT * FROM " + TABLE_QUESTION +
" WHERE " + KEY_CATEGORY_ID + " = '" + category + "'";
Log.e(LOG, selectQuery);
database = this.getReadableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
// Loops Through The Database To Get All Question Matching Category
do {
Question question = new Question();
question.setId(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_ID)));
question.setNumber(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_NUMBER)));
question.setText(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_TEXT)));
question.setMarks(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_MARKS)));
question.setAnswer(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_ANSWER)));
question.setMC1(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC1)));
question.setMC2(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC2)));
question.setMC3(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC3)));
question.setMC4(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC4)));
// Add The Question To The List Of Question
questions.add(question);
} while (cursor.moveToNext());
}
return questions;
}
Finally, here is the logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.revision.aschemistry/com.revision.aschemistry.AtomicStructureQuestions}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.revision.aschemistry.AtomicStructureQuestions.onCreate(AtomicStructureQuestions.java:26)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
            at android.app.ActivityThread.access$600(ActivityThread.java:123)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4424)
            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:787)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
            at dalvik.system.NativeStart.main(Native Method)
Any help is much appreciated, thanks in advance.
It seems your ArrayList Question is Empty. So just check size before getting data from it.
List<Question> questions = database.getQuestions(1);
if(!questions.isEmpty())
{
Question question = questions.get(0);
}else
{
Log.e("LOG","questions is Empty")
}
Also check Cursor size in your getQuestions() method from DatabaseHelper class.
Obviously you can use:
if(!questions.isEmpty())
To avoid the the ArrayIndexOutOfBounds Exception. But I guess that dosen't Solve our problem dose it?
I hope our solution here is to read the data properly and then retrieve the data using the get() method of Arraylist.
There needs to be a check before reading the data. Please check if the data are feed properly first and then go for getting them. I would like to suggest some posts you can follow to get idea about Databases.
http://www.vogella.com/tutorials/AndroidSQLite/article.html
http://infobloggall.com/2014/05/06/sqlite-database-example
Also the developer site.

ListViewAnimation insert() NullPointerException on notifyDataSetChanged()

I'm using the ListViewAnimation library and been trying to do the add-item animation for my ListView.
In order to implement such animation, their documentation says that I should do this:
To use this functionality, simply let your adapter implement Insertable, and call one of the insert methods on the DynamicListView:
MyInsertableAdapter myAdapter = new MyInsertableAdapter(); // MyInsertableAdapter implements Insertable
mDynamicListView.setAdapter(myAdapter);
mDynamicListView.insert(0, myItem); // myItem is of the type the adapter represents.
So here's what I did:
I had my Listview be a DynamicListView(I'm using ButterKnife) and set it to use my adapter
#InjectView(R.id.flow_list)
DynamicListView mFlowList;
mFlowListAdapter = new FlowListAdapter(getActivity(), mItems);
mFlowList.setAdapter(mFlowListAdapter);
Made my adapter implement the 'Insertable' interface and overridden its abstract method:
#Override
public void add(int i, #NonNull Object o) {
Item newItem = (Item)o;
mList.add(Item);
notifyDataSetChanged();
}
Call insert() on my ListView
#OnClick(R.id.done)
void addItem() {
...
mFlowList.insert(0,item);
}
But when I ran my app and clicked that done button that triggers the insert() of my ListView I got a NullPointerException saying:
09-15 11:51:41.046 14660-14660/com.jezer.MyApp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.nhaarman.listviewanimations.itemmanipulation.animateaddition.AnimateAdditionAdapter$HeightUpdater.onAnimationUpdate(AnimateAdditionAdapter.java:352)
at com.nineoldandroids.animation.ValueAnimator.animateValue(ValueAnimator.java:1178)
at com.nineoldandroids.animation.ValueAnimator.animationFrame(ValueAnimator.java:1139)
at com.nineoldandroids.animation.ValueAnimator.setCurrentPlayTime(ValueAnimator.java:545)
at com.nineoldandroids.animation.ValueAnimator.start(ValueAnimator.java:928)
at com.nineoldandroids.animation.ValueAnimator.start(ValueAnimator.java:951)
at com.nineoldandroids.animation.AnimatorSet.start(AnimatorSet.java:502)
at com.nineoldandroids.animation.AnimatorSet.start(AnimatorSet.java:502)
at com.nhaarman.listviewanimations.itemmanipulation.animateaddition.AnimateAdditionAdapter.getView(AnimateAdditionAdapter.java:318)
at android.widget.AbsListView.obtainView(AbsListView.java:2232)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1253)
at android.widget.ListView.onMeasure(ListView.java:1162)
at android.view.View.measure(View.java:15775)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15775)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15775)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4942)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2193)
at android.view.View.measure(View.java:15775)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2212)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1291)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1486)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1181)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4942)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
I'm not getting this exception when I commented out the notifyDataSetChanged() on the add() method. However that's the only way I know to refresh my listview and hopefully see an addition animation to it.
Are you perhaps doing this:
convertView = inflater.inflate(R.layout.cell, null);
Instead of this? convertView = inflater.inflate(R.layout.page_cell, parent, false);

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

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