Java.Lang.NullPointerException while using listview simple adapter - java

I have a listview that shows two sqlite tables' values. First I tried to use ArrayAdapter to view them and all values were shown. But they looked messy, so I tried using a simple adapter. hHre is my code.
for(int i=0; i<= promo.size();i++){
ProductModulePromo b =dataSource.getproductmodulepromo(moduleid);
productmoduledesc = b.getProductmoduledesc().toString();
producttype = b.getProducttype().toString();
productpromo = b.getproductpromotion().toString();
map1.put("three",productpromo);
map1.put("two",producttype);
map1.put("one",productmoduledesc);
Globals.promo.add(map1);}
promo is my arraylist<productmodulepromo>(). when i try to compile those code. all values that shown are same. so i try to change with this code on datasource.java and use those arraylist on formpromo.java. here is my DBDatasource.java's code:
public ArrayList<HashMap<String, String>> getproduct1() {
ArrayList<HashMap<String, String>> promo = new ArrayList<HashMap<String, String>>();
database = dbHelper.getReadableDatabase();
Cursor cursor = database.rawQuery("select productmodule.productmoduledescription, productdetail.producttype, productdetail.productpromotion from productmodule, productdetail where productmodule.productmoduleid=productdetail.productmoduleid", null);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
productmoduledesc=cursor.getString(cursor.getColumnIndex(DBHelper.PRODUCT_MODULE_DESC));
producttype = cursor.getString(cursor.getColumnIndex(DBHelper.PRODUCT_TYPE));
productpromo = cursor.getString(cursor.getColumnIndex(DBHelper.PRODUCT_PROMOTION));
map1.put("one",productmoduledesc);
map1.put("two",producttype);
map1.put("three",productpromo);
promo.add(map1);
} while (cursor.moveToNext());
}
cursor.close();
return promo;
}
here is my Formpromo.java :
dataSource = new DBDataSource(this);
dataSource.open();
promo = dataSource.getproduct1();
adapter = new SimpleAdapter(FormPromo.this, promo, R.layout.item_to,
new String[] {"one","two","three"},
new int[] {R.id.edtbrandto,R.id.edtqtyto,R.id.edtharga});
setListAdapter(adapter);
final ListView listpromo = (ListView) findViewById(android.R.id.list);
setListAdapter(adapter);
and I am getting an error as Java.Lang.NullpointerException on map1.put("one",productmoduledesc);. I have no idea how to fix them all. Thanks for help. any help will be appreciated.

Seems like you never set map1, add it to the beginning of the loop, because else you'd overwrite the old values
like this
...
do {
map1 = newHashMap<String, String>(); // add
productmoduledesc=cursor.getString(cursor.getColumnIndex(DBHelper.PRODUCT_MODULE_DESC));
producttype = cursor.getString(cursor.getColumnIndex(DBHelper.PRODUCT_TYPE));
productpromo = cursor.getString(cursor.getColumnIndex(DBHelper.PRODUCT_PROMOTION));
map1.put("one",productmoduledesc);
map1.put("two",producttype);
map1.put("three",productpromo);
promo.add(map1);
} while (cursor.moveToNext());
...

Related

RecyclierView's notifyItemInserted does not work with arrayList

I have 1 ArrayList and 1 RecyclerView. Data from DB are retrieved and stored in the ArrayList for displaying in the RecyclerView. All the things work fine with adding new item to the RecyclerView, but without the adding animation. I know I should use notifyItemInserted for the adding animation, but it didn't work. No inserting animation was appearing. Now I have to go back to the previous page and then get in the page again so that the added item was showing. So, how to add back the inserting animation?
Any help will be very much appreciated. Thanks.
Code to pass the data and set the adapter:
db = new DatabaseHelper(this);
dbList = new ArrayList<>();
dbList = db.getFilteredItems();
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
//newest to oldest order (database stores from oldest to newest)
llm.setReverseLayout(true);
llm.setStackFromEnd(true);
mRecyclerView.setLayoutManager(llm);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new RecyclerAdapter(this, llm, dbList);
mRecyclerView.setAdapter(adapter);
Code to retrieve data from DB:
//retrieve filtered data from DB
public List<AudioItem> getFilteredItems(){
List<AudioItem> audioList = new ArrayList<>();
String titleName = EditActivity.titleName;
String query = "select * from " + TABLE_NAME + " where " + COLUMN_NAME_RECORDING_NAME + " like '" + titleName + "%'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
AudioItem audio = new AudioItem();
audio.setId(Integer.parseInt(cursor.getString(0)));
audio.setName(cursor.getString(1));
audio.setFilePath(cursor.getString(2));
audio.setLength(Integer.parseInt(cursor.getString(3)));
audio.setTime(Long.parseLong(cursor.getString(4)));
audioList.add(audio);
}while (cursor.moveToNext());
cursor.close();
}
return audioList;
}
Code to insert data into the DB:
/* Insert data into database */
public void addRecording(String recordingName, String filePath, long length) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME_RECORDING_NAME, recordingName);
cv.put(COLUMN_NAME_RECORDING_FILE_PATH, filePath);
cv.put(COLUMN_NAME_RECORDING_LENGTH, length);
cv.put(COLUMN_NAME_TIME_ADDED, System.currentTimeMillis());
db.insert(TABLE_NAME, null, cv);
db.close();
if (mOnDatabaseChangedListener != null) {
mOnDatabaseChangedListener.onNewDatabaseEntryAdded();
}
}
Code to invoke the inserting animation:
#Override
public void onNewDatabaseEntryAdded() {
//item added to top of the list
Log.e("Count: ", Integer.toString(getItemCount()));
// notifyDataSetChanged();
notifyItemInserted(getItemCount());
//llm.scrollToPosition(getItemCount() - 1);
}
If you make a new ArrayList every time something changes and assign it to a new adapter and assign that new adapter to the RecyclerView, wonky things happen.
You should break the ArrayLists out into a Model type of object or integrate them into your current DB model object. If you do this, you can simply update itemlist and the changes will be reflected in your RecyclerView.
Here's some pseudo code since I don't really have much of your code to work off of:
public class DataModel {
private ArrayList<Foo> itemlist = new ArrayList<>();
public DataModel(){}
public ArrayList<Foo> getItemList() { return itemlist; }
}
public class YourActivity extends Activity {
private DataModel data = new DataModel();
#Override
protected void onCreate(Bundle b) {
if (b == null) {
RecyclerView dataView = (RecyclerView) findViewById(R.id.recyclerView);
dataView.setAdapter(new RecyclerAdapter(this, new LinearLayoutManager(this), data.getItemList()));
}
}
}
After you set things up this way, whenever you update itemlist, you should be seeing the changes automatically reflected. If not, call notifyDataSetChanged().

Speed up Listview load and sort it

I have small Android app, but the Sqlite database is big, and the form loading is slow. How Can I speed up Listview load and sort it by name?
My code is here:
public void nameload(){
ArrayList<String> names = new ArrayList<String>();
db = openOrCreateDatabase(Adatbazis, MODE_PRIVATE, null);
Cursor Namecursor = db.rawQuery("select DISTINCT name from Table WHERE ztr='"+ztrcode+"'", null);
Namecursor.moveToFirst();
String name = "";
while (!Namecursor.isAfterLast()) {
name = "" + Namecursor.getString(Namecursor.getColumnIndex("name"));
names.add(name);
Namecursor.moveToNext();
}
//A tömb elemeinek betöltése a UI-ba
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
names);
namelist.setAdapter(adapter1);
Namecursor.close();
}
Thank you for help me :)
Always remember Closing the cursor after setAdapter() may prevent the adapter from accessing the data which makes the loading slow.
So move your Namecursor.close(); after the loop, before ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(..)

Remove or Clear content in SimpleAdapter in Android?

Here is the code:
ibtSearchStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try{
searchQuery = etSearchThis.getText().toString();
searchQuery = searchQuery.toUpperCase();
cursor = searchActivity.getData(product, "product", tableColumns);
//Clean ArrayList
resultRow.clear();
resultTable.clear();
//Get Search Result
resultTable = searchActivity.searchByProductName(cursor, searchQuery);
//Display Search Result
for(int ctr = 0; ctr < resultTable.size(); ctr++){
HashMap<String, String> map = new HashMap<String, String>();
resultRow = resultTable.get(ctr);
String result = resultRow.get(2);
map.put("ProductName",result);
list.add(map);
}
Log.e("resultProduct", "" + list);
adapter = new SimpleAdapter(
SearchMain.this,
list,
R.layout.search_result,
new String[]{"ProductName"},
new int[]{R.id.tvProductName}
);
lvSearchResult.setAdapter(adapter);
}
finally{
product.close();
}
}
});
The function of this is that it will search for a match in the database then it will insert the result of the search in a HashMap then on a adapter.
But every click i am not able to remove the previous result.
What is the proper implementation to this?
When you are working with adapters and the information changes, be sure that you are calling adapter.notifyDataSetChanged();
You set a new adapter each time the OnClick event is triggered. As Jay Snayder wrote you should use adapter.notifyDataSetChanged(); instead. But be sure to set the adapter only once and move the following part of your code (e.g. to your onCreate() method of the activity):
adapter = new SimpleAdapter(
SearchMain.this,
list,
R.layout.search_result,
new String[]{"ProductName"},
new int[]{R.id.tvProductName}
);
lvSearchResult.setAdapter(adapter);
Just update the DataSet of your adapter (here: 'list').

How to display data fetched from the database table into listview?

My Function In SQLAdapter class is
public ArrayList<Airline> getairlinedetails(String bookingdate) {
Cursor curCalllog =db.rawQuery("SELECT * FROM "+ BOOK +
" WHERE " + date +
" BETWEEN '" + startdate + "' AND '" + enddate + "'", null);
if (curCalllog != null) {
if (curCalllog.moveToFirst()) {
do {
a=new Airline();
//a.setBookingdate(curCalllog.getString(1));
a.setPickupadd(curCalllog.getString(2));
a.setCity(curCalllog.getString(3));
a.setTrip(curCalllog.getString(4));
a.setFdate(curCalllog.getString(5));
a.setFtime(curCalllog.getString(6));
a.setCdate(curCalllog.getString(7));
a.setPtime(curCalllog.getString(8));
a.setSeats(curCalllog.getInt(9));
a.setAmount(curCalllog.getInt(10));
update.add(a);
} while (curCalllog.moveToNext());
}
}
return update;
}
M Fetching data between two dates and
I Want To show the fetched data into listview please help me how to do it I m new in android development.
You can use SimpleCursorAdapter for showing Databse contents in Listview. Make instance of SimpleCursorAdapter and pass Cursor object into it. Refer this link
If you want Customized Listview, you can customize SimpleCursorAdapter by extending this with your custom adapter class.
you can follow this example :
DataManipulator.java -helper class
//to retrieve data in a list
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","name","number","skypeId","address" },
null, null, null, null, "name asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
CheckData.java
// to show data in a list view
public class CheckData extends ListActivity {
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] name : names2) {
stg = name[1]+" - "+name[2]+ " - "+name[3]+" - "+name[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,
stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
selection.setText(stg1[position]);
}
}
follow this link for complete tutorial
I assume you are getting data from database and there by complete ArrayList with Airline objects.
Now to display data in ListView from ArrayList<Airline>, you have to define Custom adapter class by extending either BaseAdapter or ArrayAdapter.
Here you go: How to define custom adapter for ListView?
I Want To show the fetched data into listview please help me how to do
it I m new in android development
Simpliest way is to use ArrayAdapter with build-in ListView's row layout.
ListView list = (ListView) findViewById(R.id.yourList);
ArrayList<Airline> data = db.getairlinedetails("someString");
ArrayAdapter<Airline> adapter = new ArrayAdapter<Airline>(this,
android.R.layout.simple_list_item_1, data);
list.setAdapter(adapter);
But since this you need to also override toString() method in your Airline class.
Reason is that your ArrayAdapter will convert each child(provided list of airlines) to String and if you won't override toString() you will get default string representation of object but you probably need to show for instance name of airline so your method can looks like
#Override
public String toString() {
return this.name;
}
Note:
This is simple way. But if you want to get more control over ListView and create custom list i recommend you to create own subclass of ListAdapter for example BaseAdapter and define your own Adapter. Sorry but i won't write you implementation because it requires much more code but nice examples you can find here:
Customizing Android ListView Items with Custom ArrayAdapter
Android ListView, ListActivity and ListFragment - Tutorial
Android Custom ListView with Image and Text

Show two columns from SQLite as same string in a listview in android

Hi I am developing an android in which I am loading data from database and showing it in a List View.
My code is as follows
public class rel extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.refill);
//Creating an object called mydbhelper
Dbms mydbhelper = new Dbms(this);
//Loading the database in writable format
SQLiteDatabase db=mydbhelper.getWritableDatabase();
String[] id= new String[]{"_id","medicine","hs"};
//Cursor
Cursor c = db.query("medicines",id,null,null,null, null,null);
startManagingCursor(c);
String[] from = new String[]{"medicine"};
int[] to = new int[] { R.id.textlist1};
// Now creating an array adapter and set it to display using my row
SimpleCursorAdapter notes =new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
What i want to achieve is show a list view as "Medicine-hs" in which medicine is from one column and hs is from an another column of database. For example as
XYZ-HS1
ABC-HS2
as the listview contents
How to achieve this?
Right now I am able to get only Medicine
Please give your kind suggestions
}
I want to say replace this:
String[] from = new String[]{"medicine"};
int[] to = new int[] { R.id.textlist1};
with this:
String[] from = new String[]{"medicine", "medicine-hs"};
int[] to = new int[] { R.id.textlist1, R.id.textlist2};
You will of course need to have a R.id.textlist2 available to use in your layout.
EDIT: Reverted back to the previous revision, which solved the problem.
What you could do is execute the rawQuery() method off the DBHelper class with SQL that combines the fields like so:
SELECT medicine + "-" + hs AS medicineHs FROM medicines ...
so the string array would be
String[] from = new String[]{"medicineHs"};

Categories