Can't populate textview from database - android

I can't understand why I doesen't get any data out of the database. I have to admit that I am confues about listviews, textviews and adapters.
The database contains a person and a gift. That should be poured into a textview. Somehow it seems that I have to make a listview, but.... I am confused.
I have read a lot, and worked hard, but I have no idea. I would appreciate it if anyone could help me :-)
The only thing that happens is that na empty list is appearing.
Here is the code:
Main Activity.java:
package com.example.julegaveliste2;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends ListActivity {
DatabaseHelper db;
Button knapp1;
Button knapp2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper db = new DatabaseHelper(MainActivity.this);
knapp1 = (Button) findViewById(R.id.Legg_Til);
knapp2 = (Button) findViewById(R.id.Les_database);
knapp2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
visliste(db.getWritableDatabase());
}
});
knapp1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
LagTabell(db.getWritableDatabase());
}
});
}
public static void LagTabell(SQLiteDatabase db)
{
ContentValues jul = new ContentValues();
jul.put("person", "Ida");
jul.put("gave", "blomst");
db.insert("julegaveliste2", "person", jul);
}
public void visliste(SQLiteDatabase db)
{
Cursor cursor=db.rawQuery("SELECT _id, person, gave FROM julegaveliste2", null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.activity_list_item, cursor, new String[]{"person","gave"}, new int[]{R.id.person,R.id.gave},0);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
}
}
DatabaseHelper.java:
package com.example.julegaveliste2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME="julegaveliste2.db";
private static final int SCHEMA=1;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, SCHEMA);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE julegaveliste2 (_id INTEGER PRIMARY KEY AUTOINCREMENT, person TEXT NOT NULL, gave TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
throw new RuntimeException("How did we get here?");
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/gave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
<Button
android:id="#+id/Legg_Til"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="17dp"
android:text="#string/opprett_database" />
<Button
android:id="#+id/Les_database"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Legg_Til"
android:layout_alignBottom="#+id/Legg_Til"
android:layout_toRightOf="#+id/person"
android:text="#string/les_database" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_above="#+id/Legg_Til"
android:layout_alignParentLeft="true"
android:layout_marginBottom="42dp" >
</ListView>
<ListView
android1:id="#+id/listView1"
android1:layout_width="match_parent"
android1:layout_height="100dp" >
</ListView>
</RelativeLayout>

You should try to replace your SimpleCursorAdapter with an ArrayAdapter. To do this we would need a few modifications to your code. We need a new class in your application, which I will call PresentItem, an ArrayAdapter for your list, an XML layout for each row in the list, and a method for converting SQLite rows to PresentItems. First out is the new model, PresentItem:
public class PresentItem {
private String name, present;
private int id;
public PresentItem(int id, String name, String present) {
// Init
}
// Getters, setters, etc.
}
So, when we now read from your database, we can convert each rows we get from our query to new PresentItems:
public List<PresentItem> getPresentItems(SQLiteDatabase db) {
Cursor cursor = db.query("julegaveliste2",
new String[] {"_id", "person", "gave"}, null, null, null, null, null);
List<PresentItem> result = new ArrayList<PresentItem>();
PresentItem item;
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndex("_id");
int id = cursor.getInt(index));
index = cursor.getColumnIndex("name");
String name = cursor.getString(index));
index = cursor.getColumnIndex("present");
String present = cursor.getString(index);
item = new PresentItem(id, name, present);
result.add(item);
}
return result;
}
Once we have the PresentItems parsed from the database, we need a way to display them. To display the PresentItems in your app, we need our own ArrayAdapter, which would look something like this:
public class PresentListAdapter extends ArrayAdapter<PresentItem> {
private Context ctx;
private List<PresentItem> presentItems;
public PresentListAdapter(Context ctx, int layoutResourceId, List<PresentItem> presentItems) {
super(context, layoutResourceId, presentItems);
this.ctx = ctx;
this.presentItems = presentItems;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity) ctx).getLayoutInflater();
convertView = inflater.inflate(mLayoutResourceId, parent, false);
}
PresentItem item = presentItems.get(position);
((TextView) convertView.findViewById(R.id.row_id)).setText("" + item.getId());
((TextView) convertView.findViewById(R.id.name)).setText(item.getName());
((TextView) convertView.findViewById(R.id.present)).setText(item.getPresent());
return convertView;
}
To use the adapter in your app, do something like this:
public void visListe(SQLiteDatabase db){
List<PresentItem> items = getPresentItems(db);
PresentItemAdapter adapter = new PresentItemAdapter(this, R.layout.presentListItem, items);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
And, as you might notice, our adapter uses presentListItem as its layout, which we define in res/layout/presentListItem.xml as:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/row_id"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/name"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/present"
/>
</LinearLayout>
I hope I made it clear and beware bugs in the code - I wrote most of it from memory with a few quick Google searches to help me :) Ask if you need anymore help ^^

Related

Android Adapter only fetching the last entered data

I tried looking around but cant seem to find an answer that could resolve it.
Here is the process of what I'm doing:
1: Users enter data in a alert dialog
2: Data get sent into sql.
3: Adapter runs, takes data and put into a cardview.
4: Cardview is displayed(Stacks according to number of inputs made).
What that is not working to plan, the data that is being outputted overrides all previous inputs,and updates all cardviews with the latest information.
EG: Input 1: Test 1, Input 2: Test 2. Output will be 2 cardviews of Test 2.
Contact Activity
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.sp.R;
public class Contacts extends AppCompatActivity {
private Button newContact;
private AlertDialog.Builder builder;
private AlertDialog dialog;
private RecyclerView recyclerView;
private ContactDatabaseHelper helper;
private ContactAdapter mAdapter;
private EditText new_contact_name;
private EditText new_contact_number;
private EditText new_contact_relation;
private Button button_create_contact;
private Button button_cancel_create;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
helper = new ContactDatabaseHelper(this);
recyclerView = findViewById(R.id.contact_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new ContactAdapter(this,getAllItems());
recyclerView.setAdapter(mAdapter);
newContact = findViewById(R.id.contact_button);
// New Contact Button
newContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder = new AlertDialog.Builder(Contacts.this);
builder.setTitle("Create New Contact");
builder.setCancelable(false);
View view = LayoutInflater.from(Contacts.this).inflate(R.layout.new_contact_dialog,null,false);
CreateDialog(view);
builder.setView(view);
dialog = builder.create();
dialog.show();
}
});
}
private void CreateDialog(View view) {
// ContactDialog ID's
new_contact_name = view.findViewById(R.id.new_contact_name);
new_contact_number = view.findViewById(R.id.new_contact_number);
new_contact_relation = view.findViewById(R.id.new_contact_relation);
button_create_contact = view.findViewById(R.id.button_create_contact);
button_cancel_create = view.findViewById(R.id.button_cancel_create);
button_create_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get String of Name, Number, Relationship
String contactNameStr = new_contact_name.getText().toString();
String contactNumberStr = new_contact_number.getText().toString();
String contactRelationStr = new_contact_relation.getText().toString();
// Insert into ContactTable
helper.insertContactDatabase(contactNameStr,contactNumberStr,contactRelationStr);
mAdapter.swapCursor(getAllItems());
// Outputs a Toast
Toast.makeText(Contacts.this, "Contact Created", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
button_cancel_create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
private Cursor getAllItems(){
return helper.getContactDatabase();
}
}
Contact Adapter
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.sp.R;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyHolder>{
private Context mContext;
private Cursor c;
private ContactDatabaseHelper helper;
public ContactAdapter(Context context,Cursor cursor) {
mContext = context;
c = cursor;
helper = new ContactDatabaseHelper(mContext);
}
public static class MyHolder extends RecyclerView.ViewHolder{
private TextView contact_name;
private TextView contact_number;
private TextView contact_relation;
public MyHolder(View itemView) {
super(itemView);
contact_name = itemView.findViewById(R.id.contact_list_name_item);
contact_number = itemView.findViewById(R.id.contact_list_number_item);
contact_relation = itemView.findViewById(R.id.contact_list_relation_item);
}
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.contact_list,parent,false);
return new MyHolder(view);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
c.moveToFirst();
holder.contact_name.setText(helper.getContactName(c));
holder.contact_number.setText(helper.getContactNumber(c));
holder.contact_relation.setText(helper.getContactRelation(c));
}
#Override
public int getItemCount() {
return c.getCount();
}
public void swapCursor(Cursor newCursor){
if (c != null){
c.close();
}
c = newCursor;
if (newCursor != null){
notifyDataSetChanged();
}
}
}
Contact Database
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ContactDatabaseHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME = "contactlist.db";
private static final int SCHEMA_VERSION = 1;
public ContactDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); }
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE contact_table( name TEXT, number TEXT , relation TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Adds data into Contact database
public void insertContactDatabase (String contact_name, String contact_number, String contact_relation) {
ContentValues cv = new ContentValues();
cv.put("name", contact_name);
cv.put("number", contact_number);
cv.put("relation", contact_relation);
getWritableDatabase().insert("contact_table", "name", cv);
}
// Read Contact database
public Cursor getContactDatabase() {
return (getReadableDatabase().rawQuery(
"SELECT name, number, relation FROM contact_table ORDER BY + name", null));
}
// Delete Contact database
public Integer deleteContactDatabase () {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contact_table",null,null);
}
public String getContactName (Cursor c){ return (c.getString(0)); }
public String getContactNumber (Cursor c){ return (c.getString(1)); }
public String getContactRelation (Cursor c){ return (c.getString(2)); }
}
contacts
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/contact_background"
tools:context=".Contact.Contacts">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/contact_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/contact_button"
android:layout_marginTop="10dp"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/contact_button"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10sp"
android:layout_marginBottom="10sp"
android:background="#43464B"
android:text="New Contact"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
contact_list (Cardview)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/list_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#FFEAB8"
app:cardCornerRadius="15dp"
app:cardElevation="5dp"
app:cardUseCompatPadding="true">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="#00ACEE"
app:cardCornerRadius="5dp"
app:cardElevation="15dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:id="#+id/contact_layout_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="Name"
android:textAlignment="center"
android:textColor="#E6E6E6"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text=":"
android:textSize="20sp" />
<TextView
android:id="#+id/contact_list_name_item"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Name"
android:textColor="#FFFF00"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/contact_layout_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="35dp"
android:orientation="horizontal">
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:text="Number"
android:textAlignment="center"
android:textColor="#E6E6E6"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:text=":"
android:textSize="20sp" />
<TextView
android:id="#+id/contact_list_number_item"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:text="Number"
android:textColor="#FFFF00"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/contact_layout_relation"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"
android:layout_marginBottom="15dp"
android:orientation="horizontal">
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:text="Relationship"
android:textAlignment="center"
android:textColor="#E6E6E6"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text=":"
android:textSize="20sp" />
<TextView
android:id="#+id/contact_list_relation_item"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Relationship"
android:textColor="#FFFF00"
android:textSize="20sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.cardview.widget.CardView>
There are some issues in your code.
I would start from the Cursor that remains open while the recyclerview is recycling views. That's not good, and moreover, you're doing it in UI Thread, and this will slow down your UI a lot.
I would suggest you read all the data and pass it to your adapter. That's what adapters are for: they are a way to access your data, but they do not have to know anything about how your data is accessed. So the first thing is changing the db helper, adding a method that will loop through all the data in your db and returns a list:
public List<Contact> readAllContacts() {
List<Contact> contacts = new ArrayList();
Cursor cursor = this.getContactDatabase();
if (cursor.moveToFirst()){
do {
contacts.add(new Contact(cursor.getString(0), cursor.getString(1), cursor.getString(2)));
} while(cursor.moveToNext());
}
cursor.close();
}
You will also need to create a Contact class, with a public constructor.
Then, I would modify the adapter, to receive a List of Contacts, instead of the cursor:
public ContactAdapter(Context context,List<Contact> contacts) {
mContext = context;
this.contacts = contacts;
}
You won't need the db helper in the adapter anymore, since you already have the whole list and the cursor, now, is already closed, improving performance for the whole UI. Also, you'll need a class attribute named contacts, of type List.
Now you can access the value for the single row by position, so in your onBindViewHolder you will have:
public void onBindViewHolder(MyHolder holder, final int position) {
holder.contact_name.setText(this.contacts.get(position).getName());
holder.contact_number.setText(this.contacts.get(position).getNumber());
holder.contact_relation.setText(this.contacts.get(position).getContactRelation());
}
This will already work. On top of all of this, I warmly suggest you to start using Room instead of writing your own db helper.
I didn't read through and understand all your code but those lines seems off to me:
holder.contact_name.setText(helper.getContactName(c));
holder.contact_number.setText(helper.getContactNumber(c));
holder.contact_relation.setText(helper.getContactRelation(c));
maybe try using the position
Are you debug your code? What about method
public void swapCursor(Cursor newCursor){
if (c != null){
c.close();
}
c = newCursor;
if (newCursor != null){
notifyDataSetChanged();
}
}
notifyDataSetChanged() is method which you should call.
Try copy all items to arrayList (only for test), then get item by position in onBindViewHolder
I am thinking your problem - c.moveToFirst(); in onBindViewHolder

How to use ListView in order to view SQLite Database in Android Studio?

My aim is to get the database values in a ListView. I've never used ListView and don't exactly know how to do it.
So far I have been using an AlertDialog to view the entries of database. But it creates problem as when one entry is added in database and is viewed then it is stored in stack memory and when you add another entry in Database table and then view it, it shows the new entry but after pressing Back button it also shows the previous entry as such.
How can I show entries from database in the ListView ?
Database.java
package com.example.user.phonebook;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.ListView;
public class Database extends SQLiteOpenHelper {
public static final String DATABASE_NAME="PhoneBook.db";
public static final String TABLE_NAME="Information";
public static final String ID="ID";
public static final String NAME="Name";
public static final String EMAIL="Email";
public static final String PHONE="Phone";
public Database(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
String create_table= "CREATE TABLE " + TABLE_NAME + "(" + ID + " TEXT,"
+ NAME + " TEXT," + EMAIL + " TEXT," + PHONE + " TEXT" + ")";
db.execSQL(create_table);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean AddData(String id,String name, String email, String phone)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv= new ContentValues();
cv.put(ID,id);
cv.put(NAME,name);
cv.put(EMAIL,email);
cv.put(PHONE,phone);
long result=db.insert(TABLE_NAME,null,cv);
if (result==-1)
{
return false;
}
else
{
return true;
}
}
public Cursor getData()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cv=db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
return cv;
}
public boolean UpdateDate(String id, String name, String email, String phone)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(ID,id);
cv.put(NAME,name);
cv.put(EMAIL,email);
cv.put(PHONE,phone);
db.update(TABLE_NAME,cv,"ID="+id,null);
return true;
}
}
MainActivity.java
package com.example.user.phonebook;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2,ed3,ed4;
TextView tv;
Button bn1,bn2,bn3;
Database mydb;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText4);
ed4=(EditText)findViewById(R.id.editText3);
tv=(TextView) findViewById(R.id.textView2);
bn1=(Button) findViewById(R.id.button);
bn2=(Button) findViewById(R.id.button2);
bn3=(Button) findViewById(R.id.button3);
lv=(ListView)findViewById(R.id.listview) ;
mydb=new Database(this);
bn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean value=mydb.AddData(ed4.getText().toString(),ed1.getText().toString(),ed2.getText().toString(),ed3.getText().toString());
if (value==true)
{
Toast.makeText(getApplicationContext(),"Data Inserted",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
}
}
});
bn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor cv=mydb.getData();
if (cv.getCount()==0)
{
Toast.makeText(getApplicationContext(),"No data found",Toast.LENGTH_SHORT).show();
return;
}
while (cv.moveToNext())
{
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append("ID : "+cv.getString(0)+"\n");
stringBuffer.append("Name : "+cv.getString(1)+"\n");
stringBuffer.append("Email ID : "+cv.getString(2)+"\n");
stringBuffer.append("Phone No. : "+cv.getString(3)+"\n\n");
message("Details", stringBuffer.toString());
}
}
});
bn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isupdated=mydb.UpdateDate(ed4.getText().toString(),ed1.getText().toString(),ed2.getText().toString(),ed3.getText().toString());
if (isupdated==true)
{
Toast.makeText(getApplicationContext(),"Data Updated",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Updation failed",Toast.LENGTH_SHORT).show();
}
}
});
}
public void message(String title, String messageis)
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(messageis);
AlertDialog dialog=builder.create();
dialog.show();
}
}
XML Layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Name"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="#+id/editText2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:ems="10"
android:hint="Email ID"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="#+id/editText4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/editText4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="76dp"
android:ems="10"
android:hint="Phone Number"
android:inputType="phone"
app:layout_constraintBottom_toTopOf="#+id/button2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Save"
app:layout_constraintEnd_toStartOf="#+id/button2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/button2" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="256dp"
android:text="View"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Update"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/button2"
app:layout_constraintTop_toTopOf="#+id/button2" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="ID"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="#+id/button2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText4"
app:layout_constraintVertical_bias="0.076" />
<ListView
android:id="#+id/listview"
android:layout_width="347dp"
android:layout_height="185dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:divider="#f00"
android:dividerHeight="1sp"
android:listSelector="#faa"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.846"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button2"
app:layout_constraintVertical_bias="0.028" />
</android.support.constraint.ConstraintLayout>
Thanks in advance.
Make a model class with three params
String id,String name, String email, String phone
In your code in Database.java class make a method "getData" that will return list of Table: TABLE_NAME
Like this
public List<ModelName modelname> getData()
{
SQLiteDatabase db=this.getReadableDatabase();
List<ModelName > modelList=new ArrayList<>();
Cursor res=db.rawQuery("SELECT * FROM "+TABLE_NAME,null);
if(res!=null && res.moveToFirst())
{
do {
ModelName model=new ModelName ();
model.setId(res.getInt(res.getColumnIndex(ID)));
model.setName(res.getString(res.getColumnIndex(NAME)));
model.setEmail(res.getDouble(res.getColumnIndex(EMAIL)));
model.setPhone(res.getString(res.getColumnIndex(PHONE)));
}while (res.moveToNext());
}
res.close();
db.close();
return modelList;
} // end of getdata method
This method will return list of data that will be needed to populate in listview code like this:
This will return the list
List listName= db.getData;
Add this list in code of listview
// Find ListView to populate
ListView lvItems = (ListView) findViewById(R.id.lvItems);
// Setup cursor adapter using cursor from last step
YourAdapter adapter = new YourAdapter(this, listName);
// Attach cursor adapter to the ListView
lvItems.setAdapter(todoAdapter);
Best of luck
You CursorAdapter,
The CursorAdapter fits in between a Cursor (data source from SQLite query) and the ListView (visual representation) and configures two aspects:
Which layout template to inflate for an item
Which fields of the cursor to bind to which views in the template
simply create an XML layout template in res/layout/item_todo.xml, representing a particular cursor row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Next, we need to define the adapter to describe the process of projecting the Cursor's data into a View. To do this we need to override the newView method and the bindView method. The naive approach to this (without any view caching) looks like the following:
public class TodoCursorAdapter extends CursorAdapter {
public TodoCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_todo, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.tvBody);
TextView tvPriority = (TextView) view.findViewById(R.id.tvPriority);
// Extract properties from cursor
String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
int priority = cursor.getInt(cursor.getColumnIndexOrThrow("priority"));
// Populate fields with extracted properties
tvBody.setText(body);
tvPriority.setText(String.valueOf(priority));
}
}
First, we define a constructor that passes the cursor and context to the superclass. Next, we override the newView method, which is used to inflate a new view template. Finally, we override the bindView method, which is used to bind all data to a given view to populate the template content for the item.
Retrieving the Cursor
In order to use a CursorAdapter, we need to query a SQLite database and get back a Cursor representing the result set. This requires us to use a SQLiteOpenHelper for persistence as described here or an ORM that provides access to the underlying database.
Once you have a database and tables defined, then we can get access to a Cursor by querying the database with rawQuery:
// TodoDatabaseHandler is a SQLiteOpenHelper class connecting to SQLite
TodoDatabaseHandler handler = new TodoDatabaseHandler(this);
// Get access to the underlying writeable database
SQLiteDatabase db = handler.getWritableDatabase();
// Query for items from the database and get a cursor back
Cursor todoCursor = db.rawQuery("SELECT * FROM todo_items", null);
Now, we can use the CursorAdapter in the Activity to display an array of items into the ListView:
// Find ListView to populate
ListView lvItems = (ListView) findViewById(R.id.lvItems);
// Setup cursor adapter using cursor from last step
TodoCursorAdapter todoAdapter = new TodoCursorAdapter(this, todoCursor);
// Attach cursor adapter to the ListView
lvItems.setAdapter(todoAdapter);
This will then trigger the CursorAdapter iterating through the result set and populating the list. We can change the cursor to update the adapter at any time with:
// Switch to new cursor and update contents of ListView
todoAdapter.changeCursor(todoCursor);
Reference Link

Failed to retrieve data in Search View in android

I'm trying to do a simple retrieval of data from SQLite Database to the SearchView.
My problem is the SearchView is not populated with respect to the data stored in the database, although it always shows the green signal of
successfully created the database
Below is the code.
fragment_search.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E6E6E6"
android:orientation="vertical" >
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:background="#FFFFFF" />
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp" >
</SearchView>
<ListView
android:id="#+id/listview_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/searchView"
android:layout_centerHorizontal="true"
android:divider="#E6E6E6"
android:dividerHeight="5dp" />
<LinearLayout
android:id="#+id/rightLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/view1"
android:layout_alignTop="#+id/view1"
android:orientation="vertical"
android:paddingTop="25dp" >
</LinearLayout>
</RelativeLayout>
Search_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/hotelLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/section_search"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="2" >
<ImageView
android:id="#+id/hotel_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="left"
android:src="#drawable/aaa" />
<EditText
android:id="#+id/hotel_name"
android:layout_width="209dp"
android:layout_height="56dp"
android:layout_gravity="fill_horizontal" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/hotel_city"
android:layout_width="96dp"
android:layout_column="1"
android:layout_gravity="left|bottom"
android:layout_row="0"
android:ems="10" />
<EditText
android:id="#+id/hotel_country"
android:layout_width="106dp"
android:layout_column="1"
android:layout_gravity="right|bottom"
android:layout_row="0"
android:ems="10" />
</GridLayout>
</TableRow>
</LinearLayout>
</RelativeLayout>
TableData.java
package com.mytry.test;
import android.provider.BaseColumns;
public class TableData
{
public TableData()
{
}
public static abstract class TableInfo implements BaseColumns
{
public static final String DATABASE_NAME = "tourDguide";
public static final String TABLE_NAME = "Hotels";
public static final String HOTEL_ID = "id";
public static final String HOTEL_NAME = "hotel_name";
public static final String HOTEL_ADDRESS = "hotel_address";
public static final String HOTEL_CITY = "hotel_city";
public static final String HOTEL_COUNTRY = "hotel_country";
public static final String HOTEL_POSTAL = "postal_code";
}
}
DataBaseHandler.java
package com.mytry.test;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.mytry.test.TableData.TableInfo;
public class DataHandler
{
public static final int DATABASE_VERSION = 1;
SQLiteDatabase db;
DataBaseHelper dbhelper;
Context ctx;
private static class DataBaseHelper extends SQLiteOpenHelper
{
public String CREATE_QUERY = "CREATE TABLE "+TableInfo.TABLE_NAME+"("+TableInfo.HOTEL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+TableInfo.HOTEL_NAME+" VARCHAR,"+TableInfo.HOTEL_ADDRESS+" VARCHAR,"+TableInfo.HOTEL_CITY+" VARCHAR,"+TableInfo.HOTEL_COUNTRY+" VARCHAR,"+TableInfo.HOTEL_POSTAL+" INT );";
public DataBaseHelper(Context ctx) {
super(ctx,TableInfo.DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operations", "Successfully Created Database");
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
db.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Successfully Created Table");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists "+TableInfo.TABLE_NAME);
onCreate(db);
}
}
public DataHandler(Context ctx) {
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
// TODO Auto-generated constructor stub
}
public DataHandler open()
{
dbhelper = new DataBaseHelper(ctx);
db = dbhelper.getReadableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public Cursor searchHotels(String inputText) throws SQLException
{
String query = "Select "+TableInfo.HOTEL_ID+" as _id,"+TableInfo.HOTEL_NAME+","+TableInfo.HOTEL_ADDRESS+","+TableInfo.HOTEL_CITY+","+TableInfo.HOTEL_COUNTRY+","+TableInfo.HOTEL_POSTAL+" from "+TableInfo.TABLE_NAME+" where "+TableInfo.HOTEL_NAME+" LIKE '" + inputText + "';";
Log.d("table operations","Successfully transferred query");
Cursor cr = db.rawQuery(query, null);
if(cr!=null)
{
cr.moveToFirst();
}
return cr;
}
}
SeachViewActivity.java
package com.mytry.test;
import com.mytry.test.TableData.TableInfo;
import android.R.anim;
import android.app.Activity;
import android.app.DownloadManager.Query;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SearchViewActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener
{
private ListView list;
private SearchView search;
private DataHandler dbHandler;
private TextView name,city,country;
private EditText edit;
Context ctx=this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_search);
search = (SearchView) this.findViewById(R.id.searchView);
list = (ListView) this.findViewById(R.id.listview_search);
name = (TextView)this.findViewById(R.id.hotel_name);
city = (TextView)this.findViewById(R.id.hotel_city);
country = (TextView)this.findViewById(R.id.hotel_country);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
dbHandler = new DataHandler(getBaseContext());
dbHandler.open();
}
public boolean onQueryTextSubmit(String query)
{
showResults(query + "*");
return false;
}
public boolean onQueryTextChange(String newText)
{
showResults(newText + "*");
return false;
}
public boolean onClose()
{
showResults("");
return false;
}
private void showResults(String query)
{
Cursor cr = dbHandler.searchHotels((query!=null?query.toString(): "####"));
if(cr==null)
{
}
else
{
String[] from = new String[]
{TableInfo.HOTEL_NAME,TableInfo.HOTEL_ADDRESS,TableInfo.HOTEL_CITY,TableInfo.HOTEL_COUNTRY,TableInfo.HOTEL_POSTAL};
int[] to = new int[]{R.id.hotel_name,R.id.hotel_city,R.id.hotel_country};
SimpleCursorAdapter hotels = new SimpleCursorAdapter(this,R.layout.search_list, cr, from, to);
list.setAdapter(hotels);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Cursor cr = (Cursor)list.getItemAtPosition(position);
String hotel_name = cr.getString(cr.getColumnIndexOrThrow("hotel_name"));
String hotel_city = cr.getString(cr.getColumnIndexOrThrow("hotel_city"));
String hotel_country = cr.getString(cr.getColumnIndexOrThrow("hotel_country"));
LinearLayout hotelLayout = (LinearLayout)findViewById(R.id.hotelLayout);
if(hotelLayout == null){
//Inflate the Customer Information View
LinearLayout leftLayout = (LinearLayout)findViewById(R.id.rightLayout);
View hotelInfo = getLayoutInflater().inflate(R.layout.search_list, leftLayout, false);
leftLayout.addView(hotelInfo);
}
name.setText(hotel_name);
city.setText(hotel_city);
country.setText(hotel_country);
search.setQuery("", true);
}
});
}
}
}

Android ListView with dynamic search result shows wrong results

It's very difficult to explain my problem in English, but I will try.
I have a ListView which should show live the results from a search. When I type "d" in the searchfield it should me show all results that begin with a "d".
The problem is, that it doesn't show me the right results. It shows me the first entry from the original list and not the target entry, but it shows the right numbers entries.
When I have this entries in my ArrayList:
Anti
Beta
Delta
Dirty
Echo
Eleven
Earth
and type "d" in the searchfield, it shows me 2 Hits (which is right), but it shows me Anti and Beta. When I type "e", it shows me 3 Hits (which is right) but it shows me Anti, Beta and Delta.
This is the MainActivity:
package de.resper.pzcrettungsdienstkassel;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ArrayList<HashMap<String, Object>> haupt;
ArrayList<HashMap<String, Object>> code;
ArrayList<HashMap<String, Object>> codeResult;
ListView codeListView;
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeListView = (ListView) findViewById(R.id.listsearch);
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final EditText searchBox=(EditText) findViewById(R.id.searchBox);
sql_helper db = new sql_helper(getApplicationContext());
code = new ArrayList<HashMap<String,Object>>();
code = db.getAllCode();
codeResult = new ArrayList<HashMap<String,Object>>();
final CustomAdapterCode adapter_code = new CustomAdapterCode(this, R.layout.activity_main, codeResult);
codeListView.setAdapter(adapter_code);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString=searchBox.getText().toString();
int textLength=searchString.length();
codeResult.clear();
for(int i=0;i<code.size();i++){
String name=code.get(i).get("name").toString();
if(textLength<=name.length()){
if(searchString.equalsIgnoreCase(name.substring(0,textLength))){
codeResult.add(code.get(i));
Log.d("Suchfeld", String.valueOf(i));
Log.d("Suchfeld", code.get(i).get("name").toString());
}
}
}
adapter_code.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
});
}
private class CustomAdapterCode extends ArrayAdapter<HashMap<String, Object>> {
public CustomAdapterCode(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {
super(context, textViewResourceId, Strings);
}
private class ViewHolder{
TextView code_id, code_layout, name_layout, prio1, prio2, prio3;
}
ViewHolder viewHolder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView=inflater.inflate(R.layout.code_list_item, null);
viewHolder=new ViewHolder();
viewHolder.code_id=(TextView) convertView.findViewById(R.id.code_id);
viewHolder.code_layout=(TextView) convertView.findViewById(R.id.code_layout);
viewHolder.name_layout=(TextView) convertView.findViewById(R.id.name_layout);
viewHolder.prio1=(TextView) convertView.findViewById(R.id.prio1);
viewHolder.prio2=(TextView) convertView.findViewById(R.id.prio2);
viewHolder.prio3=(TextView) convertView.findViewById(R.id.prio3);
convertView.setTag(viewHolder);
} else {
viewHolder=(ViewHolder) convertView.getTag();
}
viewHolder.code_id.setText(code.get(position).get("_id").toString());
viewHolder.code_layout.setText(code.get(position).get("code").toString());
viewHolder.name_layout.setText(code.get(position).get("name").toString());
viewHolder.prio1.setText(code.get(position).get("prio1").toString());
viewHolder.prio2.setText(code.get(position).get("prio2").toString());
viewHolder.prio3.setText(code.get(position).get("prio3").toString());
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my sql_helper:
package de.resper.pzcrettungsdienstkassel;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class sql_helper extends SQLiteOpenHelper {
private static final String DATABASE_FILE_NAME="pzc";
private static final int SCHEMA_VERSION=1;
public sql_helper(Context context) {
super(context, DATABASE_FILE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE pzc_haupt (_id INTEGER PRIMARY KEY, name TEXT, unter INTEGER);");
db.execSQL("CREATE TABLE pzc_unter (_id INTEGER PRIMARY KEY, name TEXT, haupt INTEGER);");
db.execSQL("CREATE TABLE pzc_code (_id INTEGER PRIMARY KEY,code INTEGER, name TEXT, unter INTEGER, haupt INTEGER, prio1 INTEGER, prio2 INTEGER, prio3 INTEGER);");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('1','124','Anti','0','1','1','0','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('2','130','Beta','0','1','1','0','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('3','201','Delta','1','0','1','1','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('4','202','Dirty','1','0','1','1','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('5','203','Echo','2','0','1','1','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('6','204','Eleven','2','0','1','1','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('7','205','Earth','3','0','1','1','0');");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<HashMap<String,Object>> getAllHaupt() {
ArrayList<HashMap<String,Object>> hauptList = new ArrayList<HashMap<String,Object>>();
String selectQuery = "SELECT * FROM pzc_haupt";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
HashMap<String , Object> haupt;
if (cursor.moveToFirst()) {
do {
haupt = new HashMap<String, Object>();
haupt.put("_id", Integer.parseInt(cursor.getString(0)));
haupt.put("name", cursor.getString(1));
hauptList.add(haupt);
} while (cursor.moveToNext());
}
return hauptList;
}
public ArrayList<HashMap<String,Object>> getAllCode() {
ArrayList<HashMap<String,Object>> codeList = new ArrayList<HashMap<String,Object>>();
String selectQuery = "SELECT * FROM pzc_code ORDER BY _id ASC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
HashMap<String , Object> code;
if (cursor.moveToFirst()) {
do {
code = new HashMap<String, Object>();
code.put("_id", Integer.parseInt(cursor.getString(0)));
code.put("code", Integer.parseInt(cursor.getString(1)));
code.put("name", cursor.getString(2));
if (Integer.parseInt(cursor.getString(5)) == 1) {
code.put("prio1", "\u25CF");
} else {
code.put("prio1", "");
}
if (Integer.parseInt(cursor.getString(6)) == 1) {
code.put("prio2", "\u25CF");
}else{
code.put("prio2", "");
}
if (Integer.parseInt(cursor.getString(7)) == 1) {
code.put("prio3", "\u25CF");
} else {
code.put("prio3", "");
}
codeList.add(code);
} while (cursor.moveToNext());
}
return codeList;
}
}
The activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="#+id/searchBox"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_margin="10dp"
android:hint="#string/suche">
</EditText>
<ListView
android:id="#+id/listsearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="#000000"
android:layout_marginBottom="10dp" />
</LinearLayout>
</LinearLayout>
The code_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp" >
<TextView android:id="#+id/code_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/prio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textColor="#FF0000" />
<TextView
android:id="#+id/prio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textColor="#FFFF00" />
<TextView
android:id="#+id/prio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textColor="#40FF00" />
<TextView
android:id="#+id/code_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#000000" />
<TextView
android:id="#+id/name_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#000000"
android:layout_marginLeft="5dp" />
</LinearLayout>
I don't use ListActivity beacause I want to build in one more ListView in this activity.
You are not using codeResult at getView method. You are using original code array. Change code with codeResult like below. Your problem will be solved.
viewHolder.code_id.setText(codeResult.get(position).get("_id").toString());
viewHolder.code_layout.setText(codeResult.get(position).get("code").toString());
viewHolder.name_layout.setText(codeResult.get(position).get("name").toString());
viewHolder.prio1.setText(codeResult.get(position).get("prio1").toString());
viewHolder.prio2.setText(codeResult.get(position).get("prio2").toString());
viewHolder.prio3.setText(codeResult.get(position).get("prio3").toString());

Android Custom ListView with ArrayAdapter<String> possible?

I have a prefilled DB in Assets, that will be copied and opened after App start.
I have a activity who Displays the Column Name with rawQuery
Cursor c = database.rawQuery("SELECT _id, Name from DB
ORDER BY Name ASC", null);
ArrayList<String> values = new ArrayList<String>();
while (c.moveToNext()) {
values.add(c.getString(c.getColumnIndex("Name")));
}
c.close();
and starts onItemClick a new intent who Displays the other colums (new activity get "Name" variable with i.putExtra)
private void getSQLData() {
Bundle extras = getIntent().getExtras();
String Name = extras.getString("Name");
DataBaseHelper myDbHelper = new DataBaseHelper(null);
myDbHelper = new DataBaseHelper(this);
SQLiteDatabase database = myDbHelper.getWritableDatabase();
ListView lv = (ListView)findViewById(R.id.listView1);
Cursor c = database.rawQuery("SELECT * from DB WHERE Name='"+Name+"' ORDER BY Name ASC", null);
ArrayList<String> values = new ArrayList<String>();
while (c.moveToNext()) {
values.add(c.getString(c.getColumnIndex("Name")));
values.add(this.getString(R.string.x) + (c.getString(c.getColumnIndex("x"))+" "+this.getString(R.string.x)+":"));
values.add((c.getString(c.getColumnIndex("y")) + this.getString(R.string.y) + " " + this.getString(R.string.y)));
}
c.close();
ArrayAdapter<String> NamenDetails = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
values);
}
lv.setAdapter(NamenDetails); }
I get all SQL datas I need, but in the Default View.
But I Need it customized like for exmaple :
I tried many many tutorials with custom listview and simplecursoradapter but I think all
be defeated by the ArrayListString.
I hope anyone can help me I get frustrated..
Thanks!
This is an example of listview with its single row having two textviews. This the thing you wanted:
CustomListView.java:
package com.customlistview;
import java.util.ArrayList;
import resources.PlacesListAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class CustomListView extends Activity {
/** Called when the activity is first created. */
private ArrayList<String> mPlacesData1 = new ArrayList<String>();
private ArrayList<String> mPlacesData2 = new ArrayList<String>();
PlacesListAdapter mPLAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlacesData1.clear();
mPlacesData2.clear();
mPlacesData1.add("ICD1");
mPlacesData2.add("SubTitle1");
mPlacesData1.add("ICD2");
mPlacesData2.add("SubTitle2");
mPlacesData1.add("ICD3");
mPlacesData2.add("SubTitle3");
mPlacesData1.add("ICD4");
mPlacesData2.add("SubTitle4");
mPlacesData1.add("ICD5");
mPlacesData2.add("SubTitle5");
mPlacesData1.add("ICD6");
mPlacesData2.add("SubTitle6");
mPlacesData1.add("ICD7");
mPlacesData2.add("SubTitle7");
mPlacesData1.add("ICD8");
mPlacesData2.add("SubTitle8");
ListView listView = (ListView) findViewById(R.id.listview);
mPLAdapter = new PlacesListAdapter(CustomListView.this, mPlacesData1, mPlacesData2);
listView.setAdapter(mPLAdapter);
}
}
PlaceListAdapter.java:
package resources;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.customlistview.R;
public class PlacesListAdapter extends BaseAdapter {
// private Context mContext;
private LayoutInflater mInflater;
private ArrayList<String> AL_id_text = new ArrayList<String>();
private ArrayList<String> AL_text = new ArrayList<String>();
public PlacesListAdapter(Context c, ArrayList<String> AL_name_time,
ArrayList<String> AL_name_time1) {
mInflater = LayoutInflater.from(c);
// mContext = c;
this.AL_id_text = AL_name_time;
this.AL_text = AL_name_time1;
}
public int getCount() {
return AL_id_text.size();
}
public Object getItem(int position) {
return AL_id_text.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.place_row, null);
holder = new ViewHolder();
holder.txt_maintext = (TextView) convertView
.findViewById(R.id.txt_maintext);
holder.txt_mtext = (TextView) convertView
.findViewById(R.id.txt_mtext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_maintext.setText(AL_id_text.get(position));
holder.txt_mtext.setText(AL_text.get(position));
return convertView;
}
static class ViewHolder {
TextView txt_maintext;
TextView txt_mtext;
}
}
activity_main.xml:
<?xml version="1.0" encoding="UTF-8"?>
-<LinearLayout android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <ListView android:layout_height="match_parent" android:layout_width="match_parent" android:id="#+id/listview"> </ListView> </LinearLayout>
place_row.xml:
<?xml version="1.0" encoding="UTF-8"?>
-<LinearLayout android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> -<LinearLayout android:orientation="vertical" android:layout_height="70dip" android:layout_width="match_parent" android:id="#+id/lin_main"> <TextView android:layout_height="20dip" android:layout_width="fill_parent" android:id="#+id/txt_maintext" android:singleLine="true" android:paddingRight="5dip" android:paddingLeft="5dip" android:layout_marginTop="5dip" android:textColor="#fff"/> <TextView android:layout_height="20dip" android:layout_width="fill_parent" android:id="#+id/txt_mtext" android:singleLine="true" android:paddingRight="5dip" android:paddingLeft="5dip" android:layout_marginTop="15dip" android:textColor="#fff"/> </LinearLayout> <ImageView android:layout_height="3dip" android:layout_width="match_parent" android:background="#0000ff"/> </LinearLayout>
This is an example. You can make necessary edits to achieve what you want.

Categories

Resources