Android - SQLite query like MySQL - android

I have the following to fetch data from android SQLite database
my function in android
public List<String> getMyDetails()
{
List<String> dataList = new ArrayList<String>();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM pic_details WHERE _id=1",null);
if (cursor .moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
dataList.add(name);
} while (cursor.moveToNext());
}
return dataList;
}
In activity calling like this
List<String> piclist= dbHelper. getMyDetails();
Its returning the name of the candidate. But I want to return the entire column of the table something like this in PHP, MySQL
$sql=mysql_query("SELECT * FROM pic_details WHERE _id=1");
$i=0;
$out=array();
while($t=mysql_fetch_array($sql)){
$out[$i]['name']=$t['name'];
$out[$i]['file']=$t['file'];
$out[$i]['age']=$t['age'];
$out[$i]['date_time']=$t['date_time'];
$i++;
}
return $out;
So that I can fetch the $out according to my necessary.
Can any one please help me ?
Thanks in advance

As you provided in the php code in your question, it's not a single column. It's a row data. So, which you basically want is the entire row information. In order to get the entire row details, you have to do something like this.
String name = cursor.getString(cursor.getColumnIndex("name"));
String address = cursor.getString(cursor.getColumnIndex("address"));
So, the generic would be:
datatype fetchedData = cursor.getterofthatparticulardatatype(cursor.getColumnIndex(columnName));
Edit:
Either use POJO class as the other answerer said or this:
public List<HashMap<String, String>> getMyDetails()
{
List<HashMap<String, String>> datalist = new ArrayList<HashMap<String, String>>();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM pic_details WHERE _id=1",null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> hashmap = new HashMap<String, String>();
String name = cursor.getString(cursor.getColumnIndex("name"));
String story = cursor.getString(cursor.getColumnIndex("story"));
hashmap.put("nameKey",name);
hashmap.put("storyKey",story);
dataList.add(hashmap);
} while (cursor.moveToNext());
}
return dataList;
}
The way you should retrieve:
List<HashMap<String, String>> piclist= dbHelper. getMyDetails();
for(HashMap hashmap : piclist)
{
String name = hashmap.get("nameKey");
String story = hashmap.get("storyKey");
Log.d("name,story",name+", "+story);
}

First you create Java class.
public class Person {
private String image;
private String name;
public Person(String image, String name) {
super();
this.image = image;
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then create ArrayList of person class
Public List<Person> getMyDetails()
{
List<Person> dataList = new ArrayList<Person>();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM pic_details WHERE _id=1",null);
if (cursor .moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
person = new Person(image, name)
dataList.add(person);
} while (cursor.moveToNext());
}
return dataList;
}
Then use this arraylist in you activity class.

Related

Cursor not working as expected

I'm trying to pass objects from a SQLite database to a fragment, but they're getting nulled somewhere along the way.
The Log.i line in DatabaseHelper outputs as expected, but the Log.i line in CollectionsFragment does not -- it returns the correct number of values, but all of them are null.
I feel like logging collectionsList in DatabaseHelper would be useful, but I'm not sure how to do that with an ArrayList.
Snippet from DatabaseHelper:
public List<Book> getAllCollections(int authorID) {
List<Book> collectionsList = new ArrayList<>();
// Select all query
String selectQuery = "SELECT DISTINCT collection FROM " + BOOKS + " WHERE author_id = '" + authorID + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Book book = new Book();
book.setCollection(cursor.getString(0));
Log.i("stories", cursor.getString(0)); // returns with correct values
collectionsList.add(book);
} while (cursor.moveToNext());
}
return collectionsList;
// not sure how to log collectionsList here
}
Snippet from CollectionsFragment:
// link ListView object with XML ListView
collectionsListView = (ListView) view.findViewById(R.id.collections_list_view);
// create new instance of DatabaseHelper
DatabaseHelper db = new DatabaseHelper(getActivity());
// return view;
// create list of collections through getAllCollections method
List<Book> collectionsList = db.getAllCollections(authorID);
Log.i("testing", collectionsList.toString()); // returns [null, null]
// create new ArrayAdapter
ArrayAdapter<Book> arrayAdapter =
new ArrayAdapter<Book>(getActivity(), android.R.layout.simple_list_item_1, collectionsList);
// link ListView and ArrayAdapter
collectionsListView.setAdapter(arrayAdapter);
Book Class:
public class Book {
int id;
String title;
int author_id;
String collection;
String body;
#Override
public String toString() {
return title;
}
public Book() {
}
public Book(int id, String title, int author_id, String collection, String body) {
this.id = id;
this.title = title;
this.author_id = author_id;
this.collection = collection;
this.body = body;
}
// getters
public int getStoryID() {
return this.id;
}
public String getTitle() {
return this.title;
}
public int getAuthorID() {
return this.author_id;
}
public String getCollection() {
return this.collection;
}
public String getBody() {
return this.body;
}
// setters
public void setStoryID(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthorID(int author_id) {
this.author_id = author_id;
}
public void setCollection(String collection) {
this.collection = collection;
}
public void setBody(String body) {
this.body = body;
}
}

What to use to store the rows after reading from table in android

What is the best way to save data read from SQLiteDatabase Android, and access them using row number or column name?
Hi Below is my code that I am using to fetch the data but I want to store the rows in some kind of dataset so that i can fetch the data using column number or name . I want to dynamically show these data in a grid in android.
MyDatabaseSQLHelper myDatabaseSQLHelper = new MyDatabaseSQLHelper(this);
SQLiteDatabase mySQLiteDatabase = myDatabaseSQLHelper.getReadableDatabase();
String[] projection = {
Items._ID,
Items.COL_ITEM_NAME,
Items.COL_ITEM_PRICE,
Items.COL_ITEM_QUANTITY,
Items.COL_ITEM_AMOUNT
};
Cursor cursor = mySQLiteDatabase.query(Items.TABLE_NAME,projection,null,null,null,null,null);
To store all rows fetch from database you can store it in Array list of type modal class. for you your modal class could be like this
ItemBeen.java
public class ItemBeen {
String id,itemName,itemPrice,itemQty,itemAmount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemPrice() {
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
public String getItemQty() {
return itemQty;
}
public void setItemQty(String itemQty) {
this.itemQty = itemQty;
}
public String getItemAmount() {
return itemAmount;
}
public void setItemAmount(String itemAmount) {
this.itemAmount = itemAmount;
}
}
then now in your class make method for get data from database and it store all record to array list and return that array list , like this.
public ArrayList<ItemBeen> getItemList() {
Cursor cur;
ArrayList<itemBeen> itemList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
cur = db.query(Items.TABLE_NAME.TBL_ITEM, projection, null, null, null, null, null);
if (cur != null) {
if (cur.moveToFirst()) {
do {
ItemBeen bean = new ItemBeen();
bean.setId(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ID)));
bean.setItemName(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_NAME)));
bean.setItemPrice(cur.getBlob(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_PRICE)));
bean.setItemQty(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_TQY)));
bean.setItemAmount(cur.getInt(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_AMT)));
itemList.add(bean);
} while (cur.moveToNext());
}
}
return itemList;
}
Now in that class in which you want all item list in that class call this method.declare array list and fetch data.
ArrayList<ItemBeen> itemList = new ArrayList<ItemBeen>();
itemList = DBConstant.dbHelper.getItemList();
and this way in itemList contains all records.

android display data from database using listview

I am trying to make simple android app where the user enter his information and then save it in the database and display the user info using listview. I have three java files: DBHelper.java, MainActivity.java and userInfo.java.
(MainActivity.java) is where the user enters his name and email.
(DBHelper.java) is where the database is created to save the user info.
(userInfo.java) is where the user info can be displayed.
in my app I successfully displayed the data from database using textview, and my question is how I can display the data from database using listview.
updated:
this is the getData() method from DBHelper.java file:
public List<Person> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_EMAIL};
Cursor c = ourDbase.query(TABLE_SCORE, columns, null, null, null, null, null + " DESC");
List<Person> people = new ArrayList<Person>();
int iRow = c.getColumnIndex(KEY_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iEmail= c.getColumnIndex(KEY_EMAIL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
Person p = new Person();
p.setEmail(c.getString(iEmail));
//set other info, like id, name
people.add(person);
}
return people;
}
here is the Person class:
public class Person {
private int ID;
private String NAME;
private String EMAIL;
public Person()
{
ID=0;
NAME="";
EMAIL="";
}
public Person(String qNAME, int qEMAIL) {
NAME = qNAME;
EMAIL= qEMAIL;
}
public int getID()
{
return ID;
}
public String getNAME() {
return NAME;
}
public int getEMAIL() {
return EMAIL;
}
public void setID(int id)
{
ID=id;
}
public void setNAME(String qNAME) {
NAME = qNAME;
}
public void setSCORE(int qEMAIL) {
EMAIL= qEMAIL;
}
}
and this is the code where I get the data from database and set it in textview from userInfo.java:
DbHelper userInfo = new DbHelper(this);
userInfo .open();
String data = userInfo .getData();
userInfo .close();
tv.setText(data);
how I can display the data from database using listview.
Since you dont provide any code about the listview and its adapter, i assume you dont know where to start.
You should create a listview, either with custom-created adapter or basic adapter (from android). After that, add the data from the database to your listview's adapter and use notifyDataSetChanged() to make sure the data is refreshed on the listview.
Simple tutorial : http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
In-depth (recommended) tutorial : http://www.vogella.com/tutorials/AndroidListView/article.html

Not able to implement search using existing table in database in android

I am trying to implement search on user input. The serach results will be shown after searching the relevant option from database.
I have made this method to display the results
public Cursor getBooksBySearch(String query) {
// TODO Auto-generated method stub
String[] args={query};
return(getReadableDatabase().rawQuery("SELECT _id,chapter FROM chapters WHERE chapter LIKE '%" + query + "%", args));
}
Here the query is coming from an activity SearchResultAcitvity.java
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
ListView myListView = (ListView)findViewById(R.id.txt_query);
dbBookHelper = new BooklistHelper(this);
ourCursor = dbBookHelper.getBooksBySearch(query);
startManagingCursor(ourCursor);
adapter = new BookAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
I want to match this coming query string to get the results from my chapter table.
Can I just match the query string m getting in String query = intent.getStringExtra(SearchManager.QUERY) with the data in my database.
Using list view to display.
Please help me in this.
Let me know if you want more information
Thanks in Advance :)
This will return list of data search by keyword
public ArrayList<ObjectType> getSearchData(String keyword)
{
ArrayList<ObjectType> objectTypeList = new ArrayList<ObjectType>();
SQLiteDatabase db = getWritableDatabase();
String checkEntry="SELECT id,firstname,lastname FROM abc_table WHERE firstname like '%"+ keyword +"%'" +" or "+ "p.lastname like '%"+ keyword +"%'";
Cursor cursor = db.rawQuery(checkEntry, null);
try
{
//If entry exist then update
if (cursor.moveToFirst())
{
do
{
ObjectType objectType = new ObjectType();
int PID=cursor.getInt(0);
String fname = cursor.getString(1);
String LastName = cursor.getString(2);
objectType.setFirstName(fname);
objectType.setLastName(LastName);
objectTypeList.add(objectType);
}
while(cursor.moveToNext());
}
}
finally
{
if(cursor != null)
cursor.close();
}
return objectTypeList;
}
ObjectType is class
public class ObjectType {
int id;
String firstName;
String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Hope this ll help you.. :)

How to add SQLite rows to an ArrayList<>

I retrieve all the rows from my SQLite-DB Table
Cursor cursor = db.rawQuery("select * from table",null);
Then I want to add each row to an ArrayList
Please help!
IF you're using custom object array, then use like following :
public void fillDataToArray() {
ArrayList<BeanClass> arrayList = new ArrayList<BeanClass>();
DatabaseHandler db = new DatabaseHandler(getActivity());
db.open();
try
{
Cursor c = db.getImageNameForList();
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int count = 0; count < c.getCount(); count++) {
Beanclass detail = new Beanclass ();
detail.setName(c.getString(c
.getColumnIndex(DatabaseHandler._ID)));
detail.setPath(c.getString(c
.getColumnIndexOrThrow(DatabaseHandler._PATH)));
arrayList.add(detail);
c.moveToNext();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
c.close();
db.close();
}
If you use this in activity, change getActivity() to local context or whichever way you use context in activities.
DATA RETRIEVAL METHOD IN DB ADAPTER CLASS :
> public Cursor getImageNameForList() {
return db.rawQuery("select " + IMAGE_PATH + " from "+ TABLE_PRODUCT_IMAGES , null);
}
Code to do that would look like this, depending on whats in your Table. You have to create a Class that is able to represent a Row in your table.
For example if there are people in your table, with name and age, you will need an object Human(String name, int age) to put into a list.
SQLiteDatabase db = helper.getReadableDatabase();
ArrayList<Human> results = new ArrayList<Human>();
try {
String rawQuery = "Select name, age from people";
Cursor c = db.rawQuery(rawQuery, null);
try {
if (!c.moveToFirst())
return null;
do {
results.add(new Human(c.getString(0),c.getInt(1)));
} while (c.moveToNext());
} finally {
c.close();
}
} finally {
db.close();
}
public class Human {
private String name;
private int age;
public Human (String name, int age) {
this.name = name;
this.age = age;
}
}
In your Db Adapter class, add this method
public ArrayList<String>getData()
{
ArrayList<String>names=new ArrayList<String>();
Cursor c = getReadableDatabase().rawQuery("Select * from tableName", null);
c.moveToFirst();
do
{
String s1=c.getString(c.getColumnIndex("<Column_Name>"));
names.add(s1);
}while(c.moveToNext());
return names;
}
after that in your activity class add this
ArrayList<String> cid;
DB_Adapter database = new DB_Adapter(getApplicationContext(), "<your schema name>", null, 1);
cid=database.getData();
After that add your arraylist to your array adapter which is set to ListView

Categories

Resources