I am using com.weiwangcn.betterspinner, but instead of declare it in XML file, I create it programmatically. Below is my code, short and simple.
final MaterialBetterSpinner spinnerSoftener = new MaterialBetterSpinner(getActivity());
spinnerSoftener.setId((View.generateViewId()));
spinnerSoftener.setHint("Softener");
spinnerSoftener.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
List<Mill_Softener_Type> softenerList = presenter.getSoftener();
if(softenerList.size() == 0)
{
spinnerSoftener.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, new ArrayList<>()));
spinnerSoftener.setEnabled(false);
}
else
{
System.out.println("softener size: " + softenerList.size());
spinnerSoftener.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, softenerList));
spinnerSoftener.setEnabled(true);
}
container.addView(spinnerSoftener);
The problem is when I click on the spinner, it will throw a NullPointerException. Below is the error code:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337)
at android.widget.AdapterView.checkFocus(AdapterView.java:732)
at android.widget.AdapterView$AdapterDataSetObserver.onInvalidated(AdapterView.java:855)
at android.widget.AbsListView$AdapterDataSetObserver.onInvalidated(AbsListView.java:6187)
at android.database.DataSetObservable.notifyInvalidated(DataSetObservable.java:50)
at android.widget.BaseAdapter.notifyDataSetInvalidated(BaseAdapter.java:59)
at android.widget.ArrayAdapter$ArrayFilter.publishResults(ArrayAdapter.java:546)
at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
softenerList isn't null, I can print out its size from else part. I don't know what is the problem, any idea?
List<Mill_Softener_Type> softenerList = new ArrayList<>();
softenerList = presenter.getSoftener();
here presenter.getSoftener(); return null values, so you have to check first if it is giving null values reference.
List<Mill_Softener_Type> softenerList = presenter.getSoftener();
if (softenerList != null){
if(softenerList.size() == 0) {
// your code
} else {
// your code
}
container.addView(spinnerSoftener);
}
Generally, I don't see why you can't use XML here, but the list is not null, since you say you can print the size and the stacktrace says otherwise.
Regardless, I would re-write that without the new ArrayList<> because if you have an empty list, you'll have an empty adapter. No need to treat it any differently.
final Context context = getActivity();
final MaterialBetterSpinner spinnerSoftener = new MaterialBetterSpinner(context);
spinnerSoftener.setId((View.generateViewId()));
spinnerSoftener.setHint("Softener");
spinnerSoftener.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
List<Mill_Softener_Type> softenerList = presenter.getSoftener();
if(softenerList != null)
{
int size = softenerList.size();
System.out.println("softener size: " + size);
spinnerSoftener.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, softenerList));
spinnerSoftener.setEnabled(size > 0);
}
container.addView(spinnerSoftener);
And if you still get exceptions, then they are likely caused elsewhere in the code, whether that is in yours or in the library you are using.
Related
I have used this code with json object. Now I'm with sqlite, and it has NPE error.
Cursor newRes = myDb.getAllData();
while (newRes.moveToNext()) {
Product product = new Product(Integer.parseInt(newRes.getString(0).toString()), Integer.parseInt(newRes.getString(1).toString()), newRes.getString(2).toString(),
newRes.getString(3).toString(), newRes.getString(4).toString(), newRes.getString(5).toString(), Double.parseDouble(newRes.getString(6).toString()), newRes.getString(7).toString());
productTransList.add(product);
}
adapter = new ProductAdapter(mCtx, productTransList);
transRecyclerView.setAdapter(adapter);
EDIT
07-13 09:05:29.763 13314-13351/com.example.arlene.capsmobile E/libdataflow_monitor: open error=Operation not permitted
07-13 09:05:31.542 13314-13314/com.example.arlene.capsmobile E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.arlene.capsmobile, PID: 13314
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.example.arlene.capsmobile.translistTab.loadTransList(translistTab.java:135)
at com.example.arlene.capsmobile.translistTab.onCreate(translistTab.java:72)
Error at the line of productTransList.add(product);
Initialize the productTransList first and then add objects to the list.
productTransList = new ArrayList<>();
This will fix the issue.
In your SQLiteHelper Class you need to initialize the List:
public List<Product> getAllProducts() {
try {
List<Product > listProducts = new ArrayList<>();
String selectQuery = "SELECT * FROM " + dbSchema.table_name;
SQLiteDatabase mDb = this.getWritableDatabase();
Cursor cursor = mDb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Product product = new
Product(Integer.parseInt(cursor.getString(0).toString()),
Integer.parseInt(cursor.getString(1).toString()),
cursor.getString(2).toString(),
cursor.getString(3).toString(),
cursor.getString(4).toString(),
cursor.getString(5).toString(),
Double.parseDouble(cursor.getString(6).toString()),
cursor.getString(7).toString());
listProducts.add(mRecord);
} while (cursor.moveToNext());
}
return listProducts;
} catch (Exception ex) {
return null;
}
}
Here is a reference for SQLite:
SQLite Demo
From your activity, use the helper method getAllProducts asynchronously and pass an empty list to it as an input param.
First Initialize a ArrayList
productTransList = new ArrayList<>();
Cursor newRes = myDb.getAllData();
while (newRes.moveToNext()) {
Product product = new Product(Integer.parseInt(newRes.getString(0).toString()), Integer.parseInt(newRes.getString(1).toString()), newRes.getString(2).toString(),
newRes.getString(3).toString(), newRes.getString(4).toString(), newRes.getString(5).toString(), Double.parseDouble(newRes.getString(6).toString()), newRes.getString(7).toString());
productTransList.add(product);
}
adapter = new ProductAdapter(mCtx, productTransList);
transRecyclerView.setAdapter(adapter);
Hope this may help you
My listview have 19 rows and i need to get all edittext data from listview and store into arraylist.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int itemCount = mListView.getCount();
Log.d("count", ""+itemCount);
final ArrayList<String> collection = new ArrayList<>();
for(int i=0; i<itemCount; i++){
view1 = mListView.getChildAt(i);
Log.d("Position: ", ""+view1);
EditText tt = (EditText)view1.findViewById(R.id.etqty);
value = tt.getText().toString();
collection.add(value);
}
//int position = contractstoreAdapter.getItem();
Log.d("number", String.valueOf(collection));
}
});
Here is my error.
09-07 08:09:05.526 8669-8669/com.example.chintatt.cbi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chintatt.cbi, PID: 8669
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.chintatt.cbi.Fragment_orderstock$1.onClick(Fragment_orderstock.java:107)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
ListView doesn't always contain the data, cause a child view is created every time it comes into display
You must have used some adapter to store the data right? Try to get all the info from there. Not from the ListView but from the adapter in which the data contains.
Hope this will help You
If u can tell how u are storing the data in Adapter it would help me further to tell your answer precisely
for (int i = 0; i <= mListView.getLastVisiblePosition() - mListView.getFirstVisiblePosition(); i++)
I believe this should be the loop that you need to implement.
EditText tt = (EditText)view1
Use above line
EditText tt = (EditText)view1.findViewById(R.id.etqty);
Why are you calling findViewById(), whether you get edittext in your view itself
I have data inside a table. when I set adapter from it, the app crashes, but if I load the info from server then everything is ok. I get NullPointerException on setting the listview's adapter. even though, I do exactly same things as when table is empty.
// check if database is empty
cursor = sh.getReadableDatabase().rawQuery(
"SELECT * FROM " + PetopenTable.TABLE_NAME, null);
if (cursor.getCount() < 1) {
//cursor is empty
tableHasData = false;
} else {
tableHasData = true;
}
if (tableHasData) {
// we have data in database, show it, then get info
// from server and reload the UI
Log.d("Cursor", "PetOpenFragment; cursor is not empty");
prepareListFromCursor(cursor);
// initialize the list
lview3 = (ListView) getActivity().findViewById(R.id.listView1);
adapter = new ListViewCustomAdapter(getActivity(), itemList);
// here adapter is not null
if (adapter != null) {
Log.d("Adapter in Petopen", "is not null");
lview3.setAdapter(adapter); // line 94
} else {
Log.d("ADapter in petopen", "is null");
}
// do not show the loading message as we can fill it instantly from database
// now get data from server to update
new getPetopenUsers().execute((Void) null);
} else {
// show loading and load from server, database is empty
Log.d("Cursor", "PetOpenFragment; cursor is empty");
new getPetopenUsers().execute((Void) null);
mDialog.setMessage("Loading...");
mDialog.setCancelable(false);
mDialog.show();
}
...
// inside prepareListFromCursor I initialize the itemlist
itemList = new ArrayList<Object>();
...
//when i get data from server, i initialize same as when there is data in table
lview3 = (ListView) getActivity().findViewById(R.id.listView1);
adapter = new ListViewCustomAdapter(getActivity(), itemList);
lview3.setAdapter(adapter);
Logcat error:
ATAL EXCEPTION: main
java.lang.NullPointerException
at com.petcial.petopen.fragments.petOpenFragment.onCreateView(petOpenFragment.java:94)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.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:126)
at dalvik.system.NativeStart.main(Native Method)
Update
Here is how i fill the itemList, i call this method after i parse the info from table
private void AddObjectToList(String image, String name, String status,
String distance, String location, String[] petImage,
String[] petName) {
// TODO Auto-generated method stub
bean = new ItemBean();
bean.setProfileImage(image);
bean.setName(name);
bean.setStatus(status);
bean.setDistance(distance);
bean.setLocation(location);
bean.setPetImage(petImage);
bean.setPetName(petName);
itemList.add(bean);
}
Finally I tried putting the whole thing which loads data from database inside an AsyncTask, and it worked. In case someone faced same problem here is how you have to do it:
Create an AsyncTask, which is called from onCreate or onViewCreated(as in my case, I fragment)
In the doInBackground method I did not have anything, instead in the onPostExecute method, i call all the methods that processes all the data from cursor and initializes the list and adapter.
If someone has a better solution on how to make this inside an AsyncTask, please answer to this post.
Basically this is not a problem in itself, my code works so far.
What I have is a App, that lets a user log in and depending on his ID in the db, he gets displayed his saved notes. For this view I have this part of code:
title = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
MyDbHandler dbh = new MyDbHandler(this);
for(int i = 0; i < 999; i++) {
content = dbh.getNoteTitle(id, i); //getNoteTitle(int, int) returns String
if(content != null && content != "0")
title.add(content);
else
break;
}
list.setAdapter(title);
As I said, this works so far.
Thing is - I am very unhappy with the use of ' break; ' here, as I learned during education, this shouldn't be used.
Is there a smoother way to approach this issue?
Also ' content != "0" ' should be ' ! content.equals("0") ' normally, right? But that one doesn't work then... Why is this?
I am not sure what are you trying to do. First of all you should use "equal" method for Strings. The condition "content != "0" will always be true, because you are comparing 2 different objects. The condition "! content.equals("0")" should return true most of the time (when the value is not "0") and probably you should use the debugger to see exactly what is the value of content.
Second if you want to take all the notes from the database and show them to the user you should have first a method in the SQLiteOpenHelper similar to (it is not efficient to interrogate the database for each item, plus the separation of concerns):
public ArrayList<String> getNotesList (int userID){
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.query(TABLE_NAME, new String[] {MyDbHandler.COLUMN_NOTE_TITLE}, MyDbHandler.userID + "=" + userID,null, null, null, null);
ArrayList<String> list = null;
String noteTitle;
if (c != null && c.moveToFirst())
{
list = new ArrayList<String>(c.getCount());
for (int i = 0; i < c.getCount(); i++)
{
noteTitle = c.getString(c.getColumnIndex(MyDbHandler.COLUMN_SESSION_PATH));
list.add(noteTitle);
c.moveToNext();
}
}
c.close();
db.close();
return list;
I think you should not save notes that you don't want to use (e.g. null or "0"), so instead of checking here, I would check in the addNote method.
For the list initialization you have:
MyDbHandler dbh = new MyDbHandler(this);
ArrayList listData = dbh.getNotesList(id)
if (listData != null && listData.length != 0){
title = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listData.setAdapter(title);
}
I didn't test the code, but I hope it helps you. Good luck!
I have the following code in WeekDays.java
ArrayAdapter<TaskInAWeek> adapter1 = (ArrayAdapter<TaskInAWeek>) getListAdapter() ;
TaskInAWeek taski;
ArrayList<Long> checkedItms = new ArrayList<Long>();
ArrayList<Long> uncheckedItms = new ArrayList<Long>();
for(int i=0;i<values.size();i++)
{
Log.i("value's size:" +values.size()," ");
if(EditStatusAdapter.tog==1)
{
Log.i("i::"+i," ");
taski = adapter1.getItem(i);
long id = taski.getId();
Log.i("nid:"+id," ");
checkedItms.add(id);
}
else
{
Log.i("i::"+i," ");
taski = adapter1.getItem(i);
long id = taski.getId();
Log.i("nid:"+id," ");
uncheckedItms.add(id);
}
}
Its custom Array Adapter is EditStatusAdapter.java. I get a NullPointerException at this pttaski = adapter1.getItem(i);.
I have used similar one in one of my activity but it did work fine. I guess its due to the custom array adapter. But I could not ignore it as well. Can anyone tel me how to clear the exception?