ListView From Sqlite in android - android

As I searched whole net still in problem with ListView From Sqlite. After searching so much i am trying my project on android hive example Link here. So in this in Database Handler class they have given that a function i.e List getAllContacts() to get all sqlite data in List format.
I have implemented this in my project my using above function in ViewContact.class.
The PROBLEM is that I am not understanding how to get all data in ListView by using this type of method or by any other method.
See my code (ViewContact.class) :
public class ViewContact extends Activity {
DatabaseHandler helper = new DatabaseHandler(this);
String a;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row);
ListView listContent = (ListView)findViewById(R.id.listView1);
}
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM contacts";
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}// return contact list
return contactList;}}
EDIT:
See After #GrIsHu answer the output is :

Try to bind the data into the listview as below:
List<Contact> contact = new ArrayList<Contact>();
contact=getAllContacts();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, contact);
listContent.setAdapter(adapter);

Below is a code using which i suppose you can meet your requirements. In the below code i would fetch contacts saved in my database and display it in a listView. If the user wants to delete a contact from the database, then he shall long press on the item, and using the dialog that appears, he can delete the contact. Below is the code:
public class viewContacts extends ListActivity {
private static final String TAG = "MYRECORDER";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showcontacts);
//Creating a List View
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
ListView mylist=(ListView) findViewById(android.R.id.list);
mylist.setAdapter(adapter);
//Creating or opening an eisting database
SQLiteDatabase db=openOrCreateDatabase("MYDB", Context.MODE_PRIVATE, null);
//Getting a cursor to fetch data from the database
Cursor c=db.rawQuery("SELECT Number,Name FROM myTbl", null);
Log.d(TAG, "Cursor reference obtained...");
c.moveToFirst();
Log.d(TAG, "Cursor Moved to First Number....");
if(c!=null){
//If there are contents in the database, then c!=null, so using do-while loop access data // in database
do{
String num=c.getString(c.getColumnIndex("Number"));
String name=c.getString(c.getColumnIndex("Name"));
String Name_num=name+" : "+num;
listItems.add(Name_num);
c.moveToNext();
}while(!c.isAfterLast());
//update the list
adapter.notifyDataSetChanged();
//closing the database after use
db.close();
//Below is the code to delete items in data base
mylist.setOnItemClickListener(new OnItemClickListener() {
String str=null;
public void onItemClick(AdapterView<?> arg0, View view,
int arg2, long arg3) {
// TODO Auto-generated method stub
String item = ((TextView)view).getText().toString();
str=item.substring(item.lastIndexOf('+'));
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
//Creating an Alert Dialog
AlertDialog .Builder builder=new AlertDialog.Builder(viewContacts.this);
builder.setMessage("Are you sure you want to delete the contact "+str+" ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
SQLiteDatabase db=openOrCreateDatabase("MYDB", MODE_PRIVATE, null);
Toast.makeText(getBaseContext(), "The contact: "+str+" was successfully deleted", Toast.LENGTH_LONG).show();
String table="myTbl";
String whereClause = "Number = ?";
String[] whereArgs = new String[] { str };
db.delete(table, whereClause, whereArgs);
db.close();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
} );
AlertDialog alert=builder.create();
alert.show();
}
});
}
}
}

Just use SimpleCursorAdapter in this case: http://www.java2s.com/Code/Android/UI/UsingSimpleCursorAdapter.htm

I solve that adding the function toString to my class object.
In your case, add that function to the class contact
public String toString(){
return name;
}

Related

get id of selected spinner data based from database android

hi i have this spinner dropdown that displays data from my database. In my database, i have this table named area and it has this fields, aid its primary key and location which is a varchar. so far i am successful in displaying the data im my spinner. in my DBHelper this is the code that gets the data from DB
public Set<String> getAllData()
{
Set<String> set = new HashSet<String>();
String selectQuery = "SELECT * FROM " + TABLE_AREA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
db.close();
return set;
}
then in my addLocation.java here is how i use it to display the data on my spinner
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addplace);
Spinner spn = (Spinner)findViewById(R.id.areas);
Set<String> aset = db.getAllData();
List<String> aData = new ArrayList<>(aset);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
aData);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(spinnerAdapter);
spn.setOnItemSelectedListener(new SpinnerInfo());
}
private class SpinnerInfo implements AdapterView.OnItemSelectedListener {
private boolean isFirst = true;
String selected;
#Override
public void onItemSelected(AdapterView<?> spinner, View selectedView, int selectedIndex, long id)
{
if (isFirst)
{
isFirst = false;
}
else
{
String selection = spinner.getItemAtPosition(selectedIndex).toString();
selected = selection;
}
Toast tempMessage =
Toast.makeText(addLocation.this,
selected,
Toast.LENGTH_SHORT);
tempMessage.show();
}
#Override
public void onNothingSelected(AdapterView<?> spinner) {
// Won’t be invoked unless you programmatically remove entries
}
}
the thing is i needed to get the id of the selected location not the index in the spinner but it's database id. any idea on how i can do this? thanks so much in advance!
i needed to get the id of the selected location not the index in the
spinner but it's database id. any idea on how i can do this?
Do it as using HashMap:
1. Use HashMap instead of Set with location as a key and location id as value. change getAllData() :
public Map<String, Integer> getAllData()
{
Map<String, Integer> hashMap = new HashMap<String, Integer>();
...
if (cursor.moveToFirst()) {
do {
hashMap.put(cursor.getString(1),cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
return hashMap;
}
2. Pass all keys to Spinner :
Map<String, Integer> hashMap = db.getAllData();
List<String> allLocations = new ArrayList<String>(hashMap.keySet());
3. Now In onItemSelected use selected String to get id of Selected item:
int location_id=hashMap.get(selected);

array adapter is showing field value, not data values from database in android

I am trying to show a listview of data from database in fragments. For that reason I've added a table in database. Now I'm trying to create data adapter. Here is my code:
list=(ListView)rootView.findViewById(R.id.listView1);
try{
DatabaseHandler db = new DatabaseHandler(getActivity());
List<Label> allLabel = db.getAllLabels();
for (Label label : allLabel) {
ArrayAdapter<Label> dataadapter= new ArrayAdapter<Label>(getActivity(),android.R.layout.simple_list_item_1,allLabel);
list.setAdapter(dataadapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View v, int position,long id)
{
Toast.makeText(getActivity(), ((TextView)v).getText(), Toast.LENGTH_LONG).show();
}
});
}
}
catch (Exception e)
{
e.printStackTrace();
}
this is my output of containing field value not data value:
com.qcash.atmlocator.Label#52852d88
com.qcash.atmlocator.Label#52852dd8
com.qcash.atmlocator.Label#52852e08
com.qcash.atmlocator.Label#52852e38
this is the getAllLabels() function used in my code:
public List<Label> getAllLabels(){
List<Label> labels = new ArrayList<Label>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Label label = new Label();
label.setId(cursor.getInt(0));
label.setName(cursor.getString(1));
label.setLatitude(cursor.getDouble(2));
label.setLongitude(cursor.getDouble(3));
labels.add(label);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
How can I get the database value? please help me out.
Adding cursor data to a string and adding that string to the calling function fragment solved that. Here is the code:
String name=cursor.getString(0)+"\n"+cursor.getString(1)+"\n"+cursor.getString(2)+"\n"+cursor.getString(3);
FindPeopleFragment.ArrayofName.add(name);
Finally showing that array to adapter completes that:
ArrayAdapter<String> dataadapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,ArrayofName);
Override the toString() method in Label class. I am assuming that you class has a variable 'name'.
class Label{
// other variables.
#Override
public String toString() {
return name;
}
}
Update:
Change the onItemclick listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View v, int position,long id)
{
Label label = (Label)parent.getItemAtPosition(position);
Toast.makeText(getActivity(), "" + label.toString(), Toast.LENGTH_LONG).show();
}
});

getting the rowId of an item in the listView from sqlite database

hope you could help me with this problem. i want to get the rowId of a selected item in a listview from sqlite so that i can pass the value to another activity.
i already fed the listview with info from my sqlite table and use onClickedItem in the listview and use pos + 1 to get the id, but i dont want this solution because whenever i delete an item from the listview i wont be able to get the correct rowId from the database itself... this is my code :
in my DBhelper:
public List<String> getSYAList() {
List<String> List = new ArrayList<String>();
try {
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SYA ;
Cursor c = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
List.add((c.getString(0)) + " " +(c.getString(1)) + " "+ (c.getString(2)));
} while (c.moveToNext());
}
} catch (Exception e) {
Toast.makeText(ourContext, "Error encountered.",
Toast.LENGTH_LONG).show();
}
return List;
}
in my activity:
private void loadSYA() {
// TODO Auto-generated method stub
final DBhelper entry = new DBhelper(this);
entry.open();
final List<String> sya = entry.getSYAList();
if(sya.size()>0) // check if list contains items.
{
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SYA.this,android.R.layout.simple_dropdown_item_1line, sya);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sqlSYA.setAdapter(arrayAdapter);
sqlSYA.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(SYA.this,SYAInfo.class);
Bundle b = new Bundle();
b.putInt("id", (int)position + 1);
i.putExtras(b);
startActivity(i);
}
}); }
else
{
Toast.makeText(SYA.this,"No items to display",1000).show();
}
entry.close();
}
i really hope you anyone could help me to find a solution for this one. thanks in advance guys !!!

Arraylist display selected listview to textview

I'm just a noob in android. I've got this code from someone's blog.
He made a simple database query and populate an arraylist in listview.
How do I get a value from each selected item in listview to text view in new activity?
Here's the arraylist code:
public ArrayList<ArrayList<Object>> rowTable() {
ArrayList<ArrayList<Object>> fillArray = new ArrayList<ArrayList<Object>>();
Cursor cur;
try {
cur = db.query(TABLE_TEST, new String[] { ROW_ID, ROW_NAME,
ROW_CLASS }, null, null, null, null, null);
cur.moveToFirst();
if (!cur.isAfterLast()) {
do {
ArrayList<Object> fillList = new ArrayList<Object>();
dataList.add(cur.getLong(0));
dataList.add(cur.getString(1));
dataList.add(cur.getString(2));
dataArray.add(fillList);
} while (cur.moveToNext());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR DATABASE", e.toString());
}
return fillArray;
}
and here's the listview code.
private void getArrayList() {
// TODO Auto-generated method stub
ArrayList<ArrayList<Object>> getData = dtbase.rowTable();//
name = new String[getData.size()];
for (int x = 0; x < getData.size(); x++) {
ArrayList<Object> getRow = getData.get(x);
name[x] = getRow.get(1).toString();
}
ArrayAdapter<String> sName = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, name);
lv.setAdapter(sName);
}
can you help me?
It's very easy to get the selected item
Here is the method you need to override.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
...
}
}
Then use the position argument to access the arraylist so you could display it in your textview.

SQL android, creating multiple tables more information

this is my code
`I have created one table, but i want to create two and when i hit the "show" button, i want to be able to select contents from both tables and show them...this is my code...am having problems creating two tables and showing them:
public class Entername extends Activity {
private Button showButton;
private Button insertButton;
private TextView nameEditText;
private TextView addTextView;
private Button doneButton;
public DatabaseHelper dbHelper = new DatabaseHelper(Entername.this,"pubgolfdatabase",2);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.entername);
addTextView = (TextView)findViewById(R.id.textView1);
doneButton= (Button)findViewById(R.id.doneButton);
insertButton = (Button)findViewById(R.id.addButton);
nameEditText = (EditText)findViewById(R.id.name);
showButton =(Button)findViewById(R.id.button1);
showButton.setOnClickListener(new showButtonListener());
insertButton.setOnClickListener(new InsertButtonListener());
doneButton.setOnClickListener(new DoneButtonListener());
/** create the database if it dosen't exist **/
SQLiteDatabase db = dbHelper.getWritableDatabase();
try
{
db.execSQL("create table user_name(ID integer, name varchar(90));");
}
catch(Exception e)
{
e.printStackTrace();
}
}
class InsertButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
if("".equals(nameEditText.getText().toString()))
{
Toast toast = Toast.makeText(Entername.this, "Sorry, you must input both the name and the address!", Toast.LENGTH_LONG);
toast.show();
}
else
{
long flag = 0;
int id = 1;
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("user_name", new String[]{"count(*) ID"}, null, null, null, null, null);
while(cursor.moveToNext())
{
int idFromDatabase = cursor.getInt(cursor.getColumnIndex("ID"));
if(idFromDatabase != 0)
{
id = 1 + idFromDatabase;
}
}
ContentValues values = new ContentValues();
values.put("ID", id);
values.put("name", nameEditText.getText().toString().trim());
flag = db.insert("user_name", null, values);
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this, "You have successful inserted this record into database! ", Toast.LENGTH_LONG);
toast.show();
db.close();
//clear fields //clearing edittexts
nameEditText.setText("");
return;
}
else
{
Toast toast = Toast.makeText(Entername.this, "An error occured when insert this record into database!", Toast.LENGTH_LONG);
toast.show();
db.close();
//clear fields
//clearing edittexts
nameEditText.setText("");
return;
}
}
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
class DoneButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
Intent myIntent = new Intent(v.getContext(), Pickholespubs.class);
startActivityForResult(myIntent, 0);
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
class showButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
String display = "";
SQLiteDatabase db = dbHelper.getWritableDatabase();
/** the result will be loaded in cursor **/
Cursor cursor = db.query("user_name", new String[]{"ID","name"}, null, null, null, null, null);
/** check if the table is empty **/
if (!cursor.moveToNext())
{
addTextView.setText("No data to display, please make sure you have already inserted data!");
db.close();
return;
}
cursor.moveToPrevious();
/** if the table is not empty, read the result into a string named display **/
while(cursor.moveToNext())
{
int ID = cursor.getInt(cursor.getColumnIndex("ID"));
String name = cursor.getString(cursor.getColumnIndex("name"));
display = display + "\n"+"Player"+ID+", Name: "+name;
}
/** display the result on the phone **/
addTextView.setText(display);
db.close();
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
}`
A Simple Answer would be No you can not do it. As Create Table Syntax doesn't allow two DML operations at a same time.
But the alternet way is like as follows,
Create Table table1 ( column list ); Create Table table2 ( column list );
This could be possible. Moral is there must be a ; (semicolon) after each Create Table syntax is completed).

Categories

Resources