I have retrieved data and successfully shown it in text view.
What do I have to modify in my code to make it look like a list view?
And also how do modify my listview programatically(adding size and padding)?
Here is a part of my DBclass in selecting the items that I've displayed
getFAData() {
// TODO Auto-generated method stub
String [] columns = new String[]{Row_Name};
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
String res = "";
int iRow = c.getColumnIndex(Row_Name);
//int iDesc = c.getColumnIndex(Row_Desc);
//int iID = c.getColumnIndex(Row_id);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
res = res + c.getString(iRow) + "\n";
}
return res;
}
And here is the class file:
public class FirstAid extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.firstaid);
displayresult();
}
public void displayresult (){
TextView tvFa = (TextView) findViewById(R.id.tvFA);
tvFa.setMovementMethod(new ScrollingMovementMethod());
DbHelper tblFa = new DbHelper(this);
tblFa.open();
String result = tblFa.getFAData();
tblFa.close();
tvFa.setText(result);
}
}
Create ArrayList int the get data function of database
public ArrayList<String> getFAData() {
ArrayList<String> comments = new ArrayList<String>();
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
int iRow = c.getColumnIndex(Row_Name);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
comments.add(c.getString(iRow ));
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
in your activity retrieve data like this.
ArrayList<String> array = new ArrayList<String>();
array = tblFa.getFAData();
you need to implement a method in your dbhelper class like this
public List<String> selectAll_data() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME_2, new String[] { "str" },
null , null, null, null, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
Now in your activity
List<String> events = dh.selectAll_data();
String[] arr = new String[events.size()];
arr = events.toArray(arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
If you want to see a real time example check this url
Related
This is my method to get the data.Here its showing "change the type result to string".
public List<String> getData() {
// TODO Auto-generated method stub
String[] coloumn = new String[]{KEY,NAME,DETAIL};
Cursor c=ourDB.query(TABLE_NAME, coloumn, null, null, null, null, null);
List<String> result =" ";
List<String> results = new ArrayList<String>();
int iRow =c.getColumnIndex(KEY);
int iName =c.getColumnIndex(NAME);
int iDetails =c.getColumnIndex(DETAIL);
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow)+" "+ c.getString(iName)+" = "+ c.getString(iDetails)+"\n";
}
return result;
}
This is my class to view the data.
public class View extends Activity {
SimpleCursorAdapter adaptr;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
ListView lv =(ListView) findViewById(R.id.listView1);
Remind info = new Remind(this);
info.open();
List<String> data =info.getData();
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data));
}
}
please any one can suggest any ideas. thanks..!
From the error that you have mentioned, this is an obvious problem.
The following line in getData() is assigning a string literal to a List.
List<String> result =" ";
Change that to
String result = " ";
Use this:
public List<String> getData() {
// TODO Auto-generated method stub
String[] coloumn = new String[]{KEY,NAME,DETAIL};
Cursor c=ourDB.query(TABLE_NAME, coloumn, null, null, null, null, null);
List<String> result =" ";
List<String> results = new ArrayList<String>();
int iRow =c.getColumnIndex(KEY);
int iName =c.getColumnIndex(NAME);
int iDetails =c.getColumnIndex(DETAIL);
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow)+" "+ c.getString(iName)+" = "+ c.getString(iDetails)+"\n";
results.add(result);
}
return results;
}
Directly add your database data to List :
results.add(" "+ c.getString(iRow)+" "+ c.getString(iName)+" = "+ c.getString(iDetails)+"\n");
Return String List instead String :
return results;
Remove this code which is no longer required :
List result =" ";
The problem is i inserted only two rows but on execution it enters into infinite loop and repeatedily showing the same data..Any kind of help would be appreciated
Here is my code.
This is my databse class (i.e DbAdapter)
public Cursor getAllRows() {
String[]columns = new String[]{ KEY_MODEL,KEY_BRAND, KEY_PRICE};
Cursor c = db.query(TABLE_LAPTOPS, columns, null, null, null, null, null);
if (c != null) {
c.moveToLast();
}
return c;
}
This is my main class (i.e Laptops)
DbAdapter obj = new DbAdapter(this);
obj.open();
obj.insertRow("Dell1", "Dell", 345);
obj.insertRow("Hp1", "HP", 546);
obj.close();
obj.open();
Cursor c1 = obj.getAllRows();
try{
if(c1 != null){
ListView empListView = (ListView)findViewById(R.id.listView1);
ArrayList<String> data1 = new ArrayList<String>();
for(c1.moveToFirst();!c1.isAfterLast();c1.moveToNext())
{
Toast.makeText(getApplicationContext(), c1.getString(0), Toast.LENGTH_LONG).show();
}
//empListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data1));
}}catch(SQLException e){
e.printStackTrace();
}
obj.close();
c.moveToLast();
here is the issue
c.moveToFirst();
try this..
Try with Like This
listView = (ListView) rootView.findViewById(R.id.Assignment_VM_List);
AssignmentDatabaseConnector dao = new AssignmentDatabaseConnector(getActivity());
List<AssignmentPojo> assignments = dao.getAllAssignmentList();
AssignmentCustomAdapter assignmentCustomAdapter = new AssignmentCustomAdapter(getActivity(),
assignments, this);
listView.setAdapter(assignmentCustomAdapter);
AssignmentDatabaseConnector :
public List<AssignmentPojo> getAllAssignmentList() {
open();
List<AssignmentPojo> assignmentList = new ArrayList<AssignmentPojo>();
// Select All Query
String selectQuery = "SELECT * FROM Assignment";
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) { // ##Your Main Issue is Here ##
do {
AssignmentPojo assignment = new AssignmentPojo();
assignment.setAssign_Id(cursor.getString(0));
assignment.setAssign_Course(cursor.getString(1));
// Adding contact to list
assignmentList.add(assignment);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
// return contact list
return assignmentList;
}
This is just a sample code you can utilize this code according to your requirements
I have two tables with names disease_table and sysmptoms_table. I retrieved the data from disease_table from the DB and displayed on the listview and when the listitem is clicked, I have to select and display disease category symptoms accordingly and I did that successfully but my code has redundancy, I had to write two methods in the datahelper class to retrieve the symptoms as per the disease in another listview. and I am retrieving the symptom data in list view with the query with the condition of WHERE "disease_id=1" with foreign key reference
the code for the methods is as follows,
//getting pain symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,symptompain));
public List<String> getAllSymptomPain() {
List<String> symptompain = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=1", null, null, null, null);
if(null != cr){
symptompain = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptompain.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptompain;
}
//getting colorchange symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,symptomcolorchange));
public List<String> getAllSymptomColorChange() {
List<String> symptomcolorchange = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=2", null, null, null, null);
if(null != cr){
symptomcolorchange = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptomcolorchange.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptomcolorchange;
}
How can I write these two in a single method and then call it in class which extends listactivity under onListItemclick method?
And my OnListItemClick() method is as follows :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String item=(String)getListAdapter().getItem(position);
if(item.equals("Pain in Teeth")){
// passing the method here
}
else if(item.equals("Pain in Gums")){
// passing the method here
}
else if(item.equals("Pain in Mucosa")){
// passing the method here
}
else if(item.equals("Pain in TMJoint")){
// passing the method here
}
else if(item.equals("Non-Specific Pain")){
// passing the method here
}
}
Try this:
public List<String> getSymptomsByDiseaseId(long diseaseId) {
List<String> symptomsList = new ArrayList<String>();
String selection = "diseaseid=?";
String[] selectionArgs = { String.valueOf(diseaseId) };
Cursor cursor = db.query(false, SYMPTOM_TABLE_NAME, null, selection, selectionArgs, null, null, null, null);
if (cursor.moveToFirst()) {
do {
symptomsList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
return symptomsList;
}
I need to import a list of names from the SQLite Database (where it is stored ) in form of an array . Is this the right way to do it
Code for Database
public String queryAll() {
// TODO Auto-generated method stub
String [] columns = new String [] {KEY_NAME};
Cursor point = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iName = point.getColumnIndex(KEY_NAME);
for(point.moveToFirst();!point.isAfterLast();point.moveToNext()){
result = result + point.getString(iName);
}
return result;
Code to where I should import the data to
DBContact info = new DBContact (this);
info.open();
String data[] = info.queryAll();
info.close();
NewContact = (Button) findViewById(R.id.bAddContact);
I am a beginner , anything would help a lot.
Thank you
public String[] queryAll() {
String [] columns = new String [] {KEY_NAME};
Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (cursor != null) {
try {
final int nameColumnIndex = cursor.getColumnIndex(KEY_NAME);
List<String> names = new ArrayList<String>();
while (cursor.moveToNext()) {
names.add(cursor.getString(nameColumnIndex));
}
return names.toArray(new String[names.size()]);
} finally {
cursor.close();
}
}
return null;
}
I am retrieving data from sqlite to base adapter by cursor.
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
String[] v0 = new String[] { tes0 };
String[] v01 = new String[] { tes1 };
String[] v02 = new String[] { tes2 };
String[] v03 = new String[] { tes3 };
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}
Then, Adapter_listView.java
public class Adapter_ListView extends BaseAdapter {
private int count;
private Context context;
private String[] string1;
private String[] string2;
private String[] string3;
private String con1;
private String con2;
private String con3;
public Adapter_ListView(Context baseContext, String[] v01, String[] v02, String[] v03, int theTotal) {
this.count = theTotal;
this.context = baseContext;
this.string1 = v01;
this.string2 = v02;
this.string3 = v03;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup arg2) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
contentView = inflater.inflate(R.layout.layout_inflate_list2, null);
TextView title = (TextView)contentView.findViewById(R.id.inflate_title);
TextView body = (TextView)contentView.findViewById(R.id.inflate_body);
TextView sub = (TextView)contentView.findViewById(R.id.inflate_sub);
title.setText(string1[position]);
body.setText(string2[position]);
sub.setText(string3[position]);
return contentView;
}
}
from this code always error --> ArrayOuOfBound if execute this code
title.setText(string1[position]);
how i can solve it?
You need to open your database in the activity you retrieve or insert data into your SQLite database. Also make sure you close it when your finished.
final DatabaseHelper m = new DatabaseHelper(this);
m.open();
In your onDestroy or pause. Call
m.close();
This may be the issue, because i dont see where you open your database in the code.
EDIT :
In your DatabaseHelper class. Create a method.
public void open(){
db.open();
}
public void close(){
db.close()
}
Then you will have the method to close and open the database in your activities where you need to insert and retrieve information.
To retrive data from cursor, first you must go to first row data in cursor.
Some code like this:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
...
}
good luck!! :D
It seems you want to load resultset into list, if so please change your code to set adapter outside of loop:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
int theTotal=c.getCount();
String[] v0 = new String[theTotal];
String[] v01 = new String[theTotal];
String[] v02 = new String[theTotal];
String[] v03 = new String[theTotal];
int i=0;
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i] =tes0 ;
v01[i] = tes1 ;
v02[i] = tes2 ;
v03[i] = tes3 ;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
Try this:
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if(c.getCount()>0)
{
int i=0;
int clength=c.getCount();
String[] v0=new String[clength];
String[] v1=new String[clength];
String[] v2=new String[clength];
String[] v3=new String[clength];
while (c.moveToNext())
{
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i]=tes0;
v01[i]=tes1;
v01[i]=tes2;
v01[i]=tes3;
i++;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}