public List<UserDataHelper> getData() {
List<UserDataHelper> list = new ArrayList<UserDataHelper>();
String selectQuery = "SELECT * FROM " + TABLE;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
UserDataHelper quest = new UserDataHelper();
quest.setID(cursor.getInt(0));
quest.setName(cursor.getString(1));
quest.setSent(cursor.getInt(2));
quest.setRecieved(cursor.getInt(3));
quest.setTotal(cursor.getInt(4));
quest.setTimeSpent(cursor.getString(5));
list.add(quest);
} while (cursor.moveToNext());
}
return list;
}
This is for a listView but I want to fetch data individually and display it in textView. How can I achieve that? There are a lot of tutorials for listviews but not for textViews so can someone help me out please.
try this
for (UserDataHelper user:getData())
{
textView.append(user.getID()+" "+user.getName()
+" "+user.getRecieved()+" "+user.getSent()
+" "+user.getTimeSpent()+" "+user.getTotal()+"\n");
}
You could simply use the class object to set/get values, do following for string values:-
textView.setText(quest.getName());
and for the integer values make sure to use one
of the following:-
textView.setText(""+quest.getId());
or
textView.setText(String.valueOf(integer));
Related
UPDATE: PROBLEM FIXED -
The ActionBar was covering the first item on the list.
SOLUTION: Android AppBarLayout overlaps listview
In my program, I am retrieving data from the database and displaying it using List View.
However, the first row elements are always skipped in the process and the display begins from the second row.
public void displaydata(){
Cursor res = myDb.getAllData();
lv = (ListView) findViewById(R.id.idListView);
if(res.getCount() == 0){
//show message
return;
}
ArrayList<String> buffer = new ArrayList<>();
while(res.moveToNext()){
buffer.add(res.getString(1));
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,buffer);
lv.setAdapter(adapter);
}
How do I make it display from the first row?
Any help is appreciated, thanks.
EDIT: I have tried all suggested answers of using a 'do-while' and a 'for loop', all of which give the same result.
Try changing
while(res.moveToNext()){
buffer.add(res.getString(1));
};
to
Edit: change the while so it increments after:
do {
buffer.add(res.getString(1));
} while (cursor.moveToNext());
Personally, I would recommend a CursorAdapter when using a database.
lv = (ListView) findViewById(R.id.idListView);
String from = { COLUMN_NAME };
int[] to = { android.R.id.text1 };
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
myDb.getAllData(),
from, to);
lv.setAdapter(adapter);
Try out this this code may be useful for fetching data from db using cursor.
public ArrayList<BasicInfo> getFetchBasicInfo() {
ArrayList<BasicInfo> data = new ArrayList<BasicInfo>();
String sql = "select * from basic_info;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
String LastName = c.getString(c.getColumnIndex("last_name"));
String Sabcription = c.getString(c
.getColumnIndex("salutation_id"));
data.add(new BasicInfo(FirstName, LastName));
}
c.close();
}
return data;
}
I am developing a simple social media for my case study. I was able to retrieve the post from the people the user follows. Here's the screenshot:
As you can see, the problem is that the posts were not sorted according to date/id. Instead, it is sorted according to the people the user follows. It is because I am only merging the cursors using mergecursor. Here's a part of my code:
ListView listviewFeed = (ListView) findViewById(R.id.listviewFeed);
Cursor cursorFeed = DataAdapters.getFeed(dbHelper, strUserID);
//This code is for retrieving user's own posts
Cursor cursorFollowing = DataAdapters.getFollowing(dbHelper,strUserID);
//This code is for retrieving the followed users.
if(cursorFollowing.getCount()>0) {
for (int intCtr = 0; intCtr < cursorFollowing.getCount(); intCtr++) {
int intUseridI = cursorFollowing.getColumnIndex(Tables.FollowTable.COLUMN_USERID);
String strUseridI = cursorFollowing.getString(intUseridI);
Cursor cursorFollowingFeed = DataAdapters.getFeed(dbHelper, strUseridI);
\\This code is for retrieving the posts of the people the user follows.
if(intCtr>0)
{
mergeCursor = new MergeCursor(new Cursor[]{mergeCursor, cursorFollowingFeed});
}else {
mergeCursor = new MergeCursor(new Cursor[]{cursorFeed, cursorFollowingFeed});
}
//This code is for merging the cursors.
if (intCtr + 1 == cursorFollowing.getCount()) {
cursorFollowing.close();
} else {
cursorFollowing.moveToNext();
}
}
ListViewAdapterMeasurement adapterMeasurement = new ListViewAdapterMeasurement(this, mergeCursor);
listviewFeed.setAdapter(adapterMeasurement);
}else
{
ListViewAdapterMeasurement adapterMeasurement = new ListViewAdapterMeasurement(this, cursorFeed);
listviewFeed.setAdapter(adapterMeasurement);
}
It is all working well. I just want to order the posts by Date or by ID.
Is there any way to sort MergeCursor?
I guess there is no way to sort the MergeCursor so I tried to think of other ways.
I changed my query like this:
public static Cursor getFeed (DBHelper dbHelper, String strUserID)
{
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursorFollowing = getFollowing(dbHelper,strUserID);
String strQuery = "SELECT * FROM feed_tbl WHERE "+ Tables.FeedTable.COLUMN_USERID + "="+strUserID;
if(cursorFollowing.getCount()>0)
{
for(int intCtr=0;intCtr<cursorFollowing.getCount();intCtr++)
{
int intUseridI = cursorFollowing.getColumnIndex(Tables.FollowTable.COLUMN_USERID);
String strUseridI = cursorFollowing.getString(intUseridI);
String strConcatQuery = " OR "+ Tables.FeedTable.COLUMN_USERID + "="+strUseridI;
if (intCtr + 1 == cursorFollowing.getCount()) {
cursorFollowing.close();
} else {
cursorFollowing.moveToNext();
}
strQuery = strQuery +""+strConcatQuery;
Log.v(TAG,strQuery);
}
}
Cursor cursor = db.rawQuery(strQuery+" ORDER BY "+ Tables.FeedTable.COLUMN_ID + " DESC",null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
The result on the log tag is this:
V/FeedMe: SELECT * FROM feed_tbl WHERE feed_userid=1 OR feed_userid=2 OR feed_userid=4 OR feed_userid=5
Just to make things clear to those who have the same problem with me which is about MergeCursor sorting. THERE IS NO SUCH WAY TO SORT MERGECURSOR :)
Thankyou!
I want to set Hashmap value using data from database and set it in model class, it doesn't work yet and shows empty data. Here is my code, get Data from database
private ArrayList<Kategori> categories;
private ArrayList<ChatRoom> chatroom_list;
private HashMap<Integer, ArrayList<ChatRoom>> chatrooms;
void getDataList(){
categories = new ArrayList<>();
chatrooms = new HashMap<>();
chatroom_list = new ArrayList<>();
try{
categories.clear();
cursor = db.rawQuery("SELECT * FROM kategori ORDER BY id ASC", null);
//cursor2 = db.rawQuery("SELECT * FROM chatroom ORDER BY id ASC LIMIT ", null);
Kategori kategori;
while (cursor.moveToNext()){
kategori = new Kategori();
kategori.setId(cursor.getInt(cursor.getColumnIndex("id")));
kategori.setNama(cursor.getString(cursor.getColumnIndex("nama")));
categories.add(kategori);
}
listAdapter.notifyDataSetChanged();
}catch(Exception e){
e.printStackTrace();
}
try{
chatroom_list.clear();
chatrooms.clear();
ChatRoom chatRoom;
for (int i=0;i<categories.size();i++){
cursor2 = db.rawQuery("SELECT * FROM chatroom WHERE status = '0' ORDER BY id ASC", null);
while (cursor2.moveToNext()){
chatRoom = new ChatRoom();
chatRoom.setId(cursor2.getInt(cursor2.getColumnIndex("id")));
chatRoom.setNama(cursor2.getString(cursor.getColumnIndex("nama")));
chatRoom.setDosen(cursor2.getString(cursor2.getColumnIndex("dosen")));
chatRoom.setInfo(cursor2.getString(cursor2.getColumnIndex("info")));
chatRoom.setId_kategori(cursor2.getInt(cursor2.getColumnIndex("id_kategori")));
if(categories.get(i).getId()==chatRoom.getId_kategori())
chatroom_list.add(chatRoom);
}
chatrooms.put(categories.get(i).getId(), chatroom_list);
}
}catch(Exception e){
e.printStackTrace();
}
}
when I check it, Hashmap just shows empty data, Thank you!
I suppose your bug is here:
if(categories.get(i).getId()==chatRoom.getId_kategori())
chatroom_list.add(chatRoom);
I guess getId() returns Integer, which is an object. Comparing objects with == fails in most cases. When it comes to Integer, it fails once the value is under -128 or over 127 (though this can be overriden. Also there are other circumstances when comparing integers using == can like magically fail or succed. Just don't do it).
Anyhow. Check if getId() returns Integer or Long. If so, change it to categories.get(i).getId().equals(chatRoom.getId_kategori())
I am trying to get all data from my SQLite using Query LIKE statement. But I don't know how to get it.
I try to modified the Query that I use to get All the data without filtering, and its work fine.
I already try to search this problem but I still don't get it.
Here's my Search.java
Intent search = getIntent();
String searchResult = search.getStringExtra("TAG_SEARCH");
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
Log.d("Reading: ", "Reading all contacts..");
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllSearchResult();
ArrayList <String> allItems2 = new ArrayList<String>();
for (AllItem cn : allItems) {
allItems2.add(cn.getItem_name());
allItems2.add(cn.getAreaNAme());
allItems2.add(cn.getPriceCategory());
allItems2.add(cn.getImageCount());
allItems2.add(cn.getID());
allItems2.add(cn.getCategory_name());
allItems2.add(cn.getKids());
allItems2.add(cn.getFreeTextForKids());
allItems2.add(cn.getDescription());
allItems2.add(cn.getPromotion());
allItems2.add(cn.getPromotionFreeText());
allItems2.add(cn.getPromotionStartDate() + " - ");
allItems2.add(cn.getPromotionEndDate());
allItems2.add(cn.getYoutube());
allItems2.add(cn.getYoutubeLink());
allItems2.add(cn.getPhone());
allItems2.add(cn.getMobilePhone());
allItems2.add(cn.getReview());
allItems2.add(cn.getAddress());
allItems2.add(cn.getLatitude());
allItems2.add(cn.getLongitude());
allItems2.add(cn.getOpenDetail());
allItems2.add(cn.getFacebook());
allItems2.add(cn.getTwitter());
allItems2.add(cn.getInstagram());
allItems2.add(cn.getWebsite());
}
CustomAdapterAccommodation adapter = new CustomAdapterAccommodation(Search.this, allItems2);
listview.setAdapter(adapter);
}
I want to use the String from Intent to search the data on DATABASE.
This is my DatabaseHandler.java
// Getting All search result
public List<AllItem> getAllSearchResult() {
List<AllItem> allsearchResultList = new ArrayList<AllItem>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ALLITEM;
// If i try change like this its show nothing
// String selectQuery = "SELECT * FROM " + TABLE_ALLITEM + " WHERE " + KEY_ITEM_NAME_ALLITEM + " = '%a%'";
Log.d("Query search", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
AllItem allitem = new AllItem();
allitem.setTableID(cursor.getInt(0));
allitem.setID(cursor.getString(1));
allitem.setCategory_name(cursor.getString(2));
allitem.setItem_Name(cursor.getString(3));
allitem.setDescription(cursor.getString(4));
allitem.setAddress(cursor.getString(5));
allitem.setArea (cursor.getString(6));
allitem.setAreaName (cursor.getString(7));
allitem.setLongitude (cursor.getString(8));
allitem.setLatitude (cursor.getString(9));
allitem.setOpenDetail (cursor.getString(10));
allitem.setKids (cursor.getString(11));
allitem.setFreeTextForKids (cursor.getString(12));
allitem.setCuisineID (cursor.getString(13));
allitem.setCuisineName (cursor.getString(14));
allitem.setCuisineUniqueCode (cursor.getString(15));
allitem.setBarTypeID (cursor.getString(16));
allitem.setBarTypeName (cursor.getString(17));
allitem.setBarTypeCode (cursor.getString(18));
allitem.setRoomTypeID (cursor.getString(19));
allitem.setRoomTypeName (cursor.getString(20));
allitem.setRoomTypeCode (cursor.getString(21));
allitem.setWellnessTypeID (cursor.getString(22));
allitem.setWellnessTypeName (cursor.getString(23));
allitem.setWellnessTypeCode (cursor.getString(24));
allitem.setAttractionsTypeID (cursor.getString(25));
allitem.setAttractionsTypeName (cursor.getString(26));
allitem.setAttractionsTypeCode (cursor.getString(27));
allitem.setShopsTypeID (cursor.getString(28));
allitem.setShopsTypeName (cursor.getString(29));
allitem.setShopsTypeCode (cursor.getString(30));
allitem.setAdventuresTypeID (cursor.getString(31));
allitem.setAdventuresTypeName (cursor.getString(32));
allitem.setAdventuresTypeCode (cursor.getString(33));
allitem.setRomanceTypeID (cursor.getString(34));
allitem.setRomanceTypeName (cursor.getString(35));
allitem.setRomanceTypeCode (cursor.getString(36));
allitem.setGalleriesTypeID (cursor.getString(37));
allitem.setGalleriesTypeName (cursor.getString(38));
allitem.setGalleriesTypeCode (cursor.getString(39));
allitem.setFurnitureTypeID (cursor.getString(40));
allitem.setFurnitureTypeName (cursor.getString(41));
allitem.setFurnitureTypeCode (cursor.getString(42));
allitem.setEventTypeID (cursor.getString(43));
allitem.setEventTypeName (cursor.getString(44));
allitem.setEventTypeCode (cursor.getString(45));
allitem.setPriceCategory (cursor.getString(46));
allitem.setHotelOfficialStarRating (cursor.getString(47));
allitem.setPhone (cursor.getString(48));
allitem.setMobilePhone (cursor.getString(49));
allitem.setReview (cursor.getString(50));
allitem.setPromotion (cursor.getString(51));
allitem.setPromotionFreeText (cursor.getString(52));
allitem.setPromotionStartDate (cursor.getString(53));
allitem.setPromotionEndDate (cursor.getString(54));
allitem.setActive (cursor.getString(55));
allitem.setImageCount (cursor.getString(56));
allitem.setCreatedBy (cursor.getString(57));
allitem.setCreatedDate (cursor.getString(58));
allitem.setUpdatedBy (cursor.getString(59));
allitem.setUpdatedDate (cursor.getString(60));
allitem.setFacebook (cursor.getString(61));
allitem.setTwitter (cursor.getString(62));
allitem.setInstagram (cursor.getString(63));
allitem.setWebsite (cursor.getString(64));
allitem.setYoutube (cursor.getString(65));
allitem.setYoutubeLink (cursor.getString(66));
allitem.setMember (cursor.getString(67));
allitem.setMemberStartDate (cursor.getString(68));
allitem.setMemberEndDate (cursor.getString(69));
allitem.setNew (cursor.getString(70));
allitem.setEventStartDate (cursor.getString(71));
allitem.setEventEndDate (cursor.getString(72));
// Adding food to list
allsearchResultList.add(allitem);
} while (cursor.moveToNext());
}
// return food list
return allsearchResultList;
}
Is there anyone can help me how to solved this problem?
When the user press the button search, the Text send to Search class and the Text is the key to get all the data from SQLite. Then show it in ListView.
Thanks before :D
Use LIKE not =
LIKE allows you to use wildcars:
% represents multiple characters
_ represents one character
String filter = "a";
String selectQuery = "SELECT * FROM " + TABLE_ALLITEM + " WHERE " + KEY_ITEM_NAME_ALLITEM + " LIKE '%"+filter+"%' ";
I'm trying to retrieve a column (a database column where names are saved) and puting them to a listview. I have a class called Data with "getters" and "setters".
The following code is placed in a DBHandler class which extends SQLiteOpenHelper. This code is called from the MainActivity.java where the listview is meant to be updated with an onClickButton event.
public String[] getNames (int a, int b) {
String[] names = new String[] {};
String selectQuery = "SELECT * FROM " + TABLE_NAME
+ " WHERE " + KEY_ONE + " = ? AND " + KEY_TWO + " = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(a), String.valueOf(b)});
if (cursor.moveToFirst()) {
int i = 0;
do {
Data myData = new Data();
names [i] = cursor.getString(1); //Names in cursor
++i;
} while (cursor.moveToNext());
}
return names;
}
In the MainActivity.java I call the following code before updating and notifying the update of the listview adapter:
values = db.getNames (1, 1);
I don't know why but this isn't working, it throws many errors with String lengths and crashes the app when I click the button that is suposed to enter the onClickButton.
Thanks
Follow the laalto answer and at last convert your ArrayList to Array like below:
String[] arrRecords = names.toArray(new String[names.size()]);
String[] names = new String[] {};
...
names [i] = cursor.getString(1); //Names in cursor
You're assigning to an empty array which causes ArrayIndexOutOfBoundsException.
Consider using a list such as ArrayList where you can append your values, e.g.
List<String> names = new ArrayList<String>();
...
names.add(cursor.getString(1));
If you really need to return a String[], you can convert the list with toArray():
String[] arr = new String[names.size()];
names.toArray(arr);
return arr;
Also, when posting questions that involve exceptions, always include the exception stacktrace from logcat in the question itself.
Why use like this
String[] names = new String[] {}; //no size
names [i] = cursor.getString(1); //it can work?
Use ArrayList<String>
List<String> names = new ArrayList<String>(); //declare
names.add(<column-val>); //add column value to list