Currently im making a custom listview with baseadapter of(image, ressource and database). I got a problem on putting a data from sqlite inside baseadapter. my code is look like this, Database Code:
public HashMap<String, String> getResult(String year) {
HashMap<String, String> questionmap = new HashMap<String, String>();
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT _id, COLUMN_B, COLUMN_C FROM TABLE_NAME WHERE YEAR_COLUMN='"+ year + "'";
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
questionmap.put("_id", cursor.getString(0));
questionmap.put("COLUMN_B", cursor.getString(1));
questionmap.put("COLUMN_C", cursor.getString(2));
} while (cursor.moveToNext());
}
return questionmap;
}
And Here is my BaseAdapter looks like:
class singlerow_info {
String A, B, C;
int img;
singlerow_info(String A, String B, String C,
int img) {
this.A = A;
this.B = B;
this.C = C;
this.img = img;
}
}
class resultadapter extends BaseAdapter {
//Get YEAR values from previous activity
Intent intent = getIntent();
String year = intent.getStringExtra("YEAR");
HashMap<String, String> questionmap = myDb.getResult(year);
ArrayList<singlerow_info> list;
resultadapter(Context c)
{
list = new ArrayList<singlerow_info>();
//get String A from String resource and get String []B and []C from database
Resources ress = c.getResources();
String[] A = ress.getStringArray(R.array.exam_question);
//do here get B,C from db, Here im stuck with.
String[] B=;
String[] C= ;
int[] images = {R.drawable.icon_1,R.drawable.icon_2};
for (int i =0; i<40; i++ ){
list.add(new singlerow_info(A[i],B[i],C[i],images[i]));
}
}
Please help.
class resultadapter extends BaseAdapter {
//Get YEAR values from previous activity
Intent intent = getIntent();
String year = intent.getStringExtra("YEAR");
ArrayList questionmapB,questionmapC;
ArrayList list;
resultadapter(Context c)
{
list = new ArrayList<singlerow_info>();
questionmapB = new ArrayList<String>;
questionmapC = new ArrayList<String>;
readFromDB();
//get String A from String resource and get String []B and []C from database
Resources ress = c.getResources();
String[] A = ress.getStringArray(R.array.exam_question);
//do here get B,C from db, Here im stuck with.
int[] images = {R.drawable.icon_1,R.drawable.icon_2};
for (int i =0; i<40; i++ ){
list.add(new singlerow_info(A[i],questionmapB.get(i) ,questionmapC.get(i),images[i]));
}
}
private void readFromDB()
{
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT _id, COLUMN_B, COLUMN_C FROM TABLE_NAME WHERE YEAR_COLUMN='"+ year + "'";
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
questionmapB.put("COLUMN_B", cursor.getString(1));
questionmapC.put("COLUMN_C", cursor.getString(2));
} while (cursor.moveToNext());
}
}
Related
I want to Show all database contents in a List View in Android Studio, I expect to see 3 rows that each row contains "name, family and ID" , but I see a comlex of package name and some other characters as follws:
com.google.www.hmdbtest01.Person#529e71b4
com.google.www.hmdbtest01.Person#529e7238
com.google.www.hmdbtest01.Person#529e7298
if I have more rows in my database, I will see more lines like above in the output.
my codes are as follow:
public class ListOfData extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_data);
ListView list = findViewById(R.id.list1);
HmDbManager01 db= new HmDbManager01(this);
ArrayList personList = db.getAll();
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, personList);
list.setAdapter(arrayList);
}
}
db.getAll() is as follows:
public ArrayList<Person> getAll(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM tbl_person", null);
cursor.moveToFirst();
ArrayList<Person> allData = new ArrayList<>();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Person p1 = new Person();
p1.pID=cursor.getString(0);
p1.pName=cursor.getString(1);
p1.pFamily=cursor.getString(2);
allData.add(p1);
cursor.moveToNext();
}
}
cursor.close();
sqLiteDatabase.close();
return allData;
}
and, this is Person:
package com.google.www.hmdbtest01;
public class Person {
public String pID;
public String pName;
public String pFamily;
}
Let me know your comments on this problem.
arrayListAdapter will convert your personList to list of string
change like it:
ArrayList<String> persons = new ArrayList<String>();
personList.forEach(personModel -> {
persons.add(personModel.name + " " + personModel.lastName + " " + personModel.id);
});
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, persons);
I did some changes in my code and it runs but I didn't get appropriate output. I create a method.
public void fetchData() {
dbHandler = new CourseDbHandler(this,null,null,1);
List<CreateCourse> course_data = dbHandler.getdata();
String[] data = new String[course_data.size()];
int i=0;
for(CreateCourse co : course_data)
{
data[i] = co.getCourseSelected();
i++;
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
in this method i used dbHandler.getdata method, which is as follows
public List<CreateCourse> getdata() throws NullPointerException {
String dbString = "";
String course;
String sec;
List<CreateCourse> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
course = c.getString(1);
sec = c.getString(2);
dbString = course+" "+sec;
CreateCourse co = new CreateCourse();
co.setCourseSelected(dbString);
list.add(new CreateCourse(c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
These are the getter and setter method
public void setCourseSelected(String courSelected) {
courseSelected = courSelected;
}
public String getCourseSelected() {
System.out.println(courseSelected);
return courseSelected;
}
It gives an error unfortunately app has stopped.
Create a class with your data:
public class Course {
public String id;
public String course;
public String sec;
public Course (String id, String course, String sec) {
this.id = id;
this.course = course;
this.sec = sec;
}
Then modify your method to return List of your data:
public List<Course> getdata() throws NullPointerException {
List<Course> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
list.add(new Course(c.getString(0), c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
Then you can use this List with ArrayAdapter to show your data in ListView.
I changed all the code and solve my problem in above code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_course);
dbHandler = new CourseDbHandler(this, null, null, 1);
Cursor c = dbHandler.getData();
c.moveToFirst();
// System.out.println("Select");
if(c.equals(null)){
System.out.println("NO DATA");
}
else {
if(c.moveToFirst()) {
do {
dbString=null;
course = c.getString(1);
sec = c.getString(2);
dbString = course + " " + sec;
courseItem.add(dbString);
} while (c.moveToNext());
}
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, courseItem);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
Thank you for your help..
I am trying to populate my AutoCompleteTextView from a column of values in my database.
The query I am running in my database is:
// GET MEMOS
public ArrayList<String> autoCompleteMemo(String table)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> memoList = new ArrayList<String>();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
memoList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return memoList;
}
And here is how I am attempting to set the values:
memoList = new String[db.autoCompleteMemo(table).size()];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, memoList);
etMemo.setAdapter(adapter);
For some reason, this does not appear to be working. Am i converting from ArrayList to String[] properly?
Thanks
Also,
If i do something similar to this
String[] memoList = getResources().getStringArray(R.array.memoList);
and populate that in Strings.xml it works fine.
I changed my DB method to the following and it now works
public String[] autoCompleteMemo(String table) {
SQLiteDatabase db = this.getReadableDatabase();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor.getColumnIndex("memo"));
i++;
}
return str;
}
else {
return new String[] {};
}
}
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
Hi I just want to know better on how to use this. Since I'm using this kind of method in doing my custom listView now I wanted to apply it since I love the approach on this but I don't know how I should do it. Anyway What I have is a database query where I get all the result from a search query in SQLite Database. Now I'm sure about the content of my query since I already tested it but when I display it the result always return the same output which is the last row of the query. For better understanding here's my code:
public ArrayList<HashMap<String,String>> getList(String search_param){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> hashmap = new HashMap<String,String>();
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
if (cursor.moveToFirst()) {
do {
item_list.put("column1", cursor.getString(0));
item_list.put("column2",cursor.getString(1));
list.add(hashmap);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
now to retrieve the list here's what I tried so far:
ArrayList<HashMap<String,String>> new_list;
DatabaseClass db = new DatabaseClass(getActivity());
new_list = db.getList("");
for(int i=0;i<new_list.size();i++){
HashMap<String,String> content = new HashMap<String, String>();
content = new_list.get(i);
Log.v("The hashmap",content.get("column1").toString());
Log.v("The hashmap",content.get("column2").toString());
}
now the content of my Database should be 1,2,3 for column1 and test1,test2,test3 for column2. but what I get from the result are 3,3,3 and test3,test3,test3
I also tried the method of doing
newlist.get(i).get("column1").toString; but it doesn't even solve the problem.
Any idea on what I should do about this?
Within do while you need to create instance for hashmap,
public ArrayList<HashMap<String,String>> getList(String search_param){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> hashmap;
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
if (cursor.moveToFirst()) {
do {
hashMap = new HashMap<String,String>();
hashMap.put("column1", cursor.getString(0));
hashMap.put("column2",cursor.getString(1));
list.add(hashmap);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
This works like charm with me
public ArrayList<HashMap<String, String>> getList(String search_param){
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
int colCount = cursor.getColumnCount();
int rowCount = cursor.getCount();
if (cursor.moveToFirst()) {
do {
HashMap<String, String> col = new HashMap<String, String>();
int size =cursor.getColumnCount();
for (int i = 0; i < size; i++) {
col.put(cursor.getColumnName(i), cursor.getString(i));
}
list.add(col);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}