Android Adapter only fetching the last entered data - android

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

Related

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

Run-time Expandable Listview with Edittext and Spinner

My intention is to get data from the run-time growing listview (as shown in below figures) which has Edittext and Spinners and send this data to remote server using json.
Am I on the correct path or there is another kind of method to be used for this.
I want to access Edittext and Spinner from the listview which is expanded at runtime.
My Problem is, whenever a new view is added, it overlaps on the previous view.
Instead, it should get added below the 1st view. (Solved this. See the edited code).
Another thing is how to access edittext & spinner from each view? I want to accept this data from user & save it in the device. How to do that? (in private void SaveUserData() {} method).
Below is my full code.
Edited on 20 Mar 2018
MainActivity.java
package tandel.amit.expandablelistview;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView listView;
Button buttonSave;
FloatingActionButton fab;
Adapter adapter;
int count = 0;
String[] Heading = {"User 1","User 2","User 3","User 4"};
String Name = "Name";
String ID = "ID";
String Gender = "Gender";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
buttonSave = findViewById(R.id.btnSave);
fab = findViewById(R.id.fabAdd);
buttonSave.setOnClickListener(onClickListener);
fab.setOnClickListener(onClickListener);
adapter = new Adapter(getApplicationContext(), R.layout.row_layout);
listView.setAdapter(adapter);
AddView(count++);
}
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnSave:
SaveUserData(); // Save the data to Local Database
break;
case R.id.fabAdd:
AddView(count++); // Add new View in listview
break;
default:
break;
}
}
};
private void AddView(int i) {
DataProvider dataProvider = new DataProvider(Heading[i],Name,Gender,ID);
adapter.add(dataProvider);
adapter.notifyDataSetChanged();
}
private void SaveUserData() {
}
}
Adapter.java
package tandel.amit.expandablelistview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/*
* Created by Amit Tandel on 2/2/2018.
*/
public class Adapter extends ArrayAdapter{
List list = new ArrayList();
public Adapter(#NonNull Context context, int resource) {
super(context, resource);
}
#Override
public void add(#Nullable Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return this.list.get(position);
}
static class DataHandler{
TextView Heading,Name,Gender,ID;
EditText UserName,UserID;
Spinner UserGender;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
DataHandler dataHandler = new DataHandler();
if (convertView == null){ // If row is empty, we need to create row
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHandler.Heading = convertView.findViewById(R.id.tvHeading);
dataHandler.Name = convertView.findViewById(R.id.tvName);
dataHandler.Gender = convertView.findViewById(R.id.tvGender);
dataHandler.ID = convertView.findViewById(R.id.tvID);
dataHandler.UserName = convertView.findViewById(R.id.etName);
dataHandler.UserID = convertView.findViewById(R.id.etID);
dataHandler.UserGender = convertView.findViewById(R.id.spGender);
convertView.setTag(dataHandler);
}else {
dataHandler = (DataHandler) convertView.getTag(); // If row already present then get that row
}
DataProvider dataProvider;
dataProvider = (DataProvider) this.getItem(position);
if (dataProvider != null) {
dataHandler.Heading.setText(dataProvider.getHeading());
dataHandler.Name.setText(dataProvider.getName());
dataHandler.Gender.setText(dataProvider.getGender());
dataHandler.ID.setText(dataProvider.getID());
}
return convertView;
}
}
DataProvider.java
package tandel.amit.expandablelistview;
/*
* Created by Amit Tandel on 2/2/2018.
*/
public class DataProvider {
private String Heading;
private String Name;
private String Gender;
private String ID;
public DataProvider(String Heading, String Name, String Gender, String ID) {
this.setHeading(Heading);
this.setName(Name);
this.setGender(Gender);
this.setID(ID);
}
public String getHeading() {
return Heading;
}
public void setHeading(String heading) {
Heading = heading;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="16dp"
tools:context="tandel.amit.expandablelistview.MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
n
<Button
android:id="#+id/btnSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Save" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:id="#+id/fabAdd"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:src="#drawable/plus"
android:layout_marginBottom="80dp" />
</RelativeLayout>
row_layout.xml
<?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="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="#+id/tvHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="User 1"
android:textSize="18sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tvName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name"
android:textSize="16sp" />
<EditText
android:id="#+id/etName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tvGender"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gender"
android:textSize="16sp" />
<Spinner
android:id="#+id/spGender"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tvID"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID"
android:textSize="16sp" />
<EditText
android:id="#+id/etID"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="8dp"
android:background="#000000" />
</LinearLayout>

Display single record from ListView / ListAdapter from sql database

I do a bit of travelling and I wanted to create an app that allowed me to save taxi bookings into a database. I have only added a few fields to give me an idea how this all works. I'm quite new to programming and followed a number of tutorials to create an app that allows me to take a csv file and upload it to the app database. This works well and I have no problems displaying the data.
I managed to get it to both use Toast and alert to bring up windows with data in, but only 6 fields... I need to have all 16 showing...
I have made some ground on this but still having the Application termination problems when I click on the list items.
I have tried to make an Intent to call the new view results table by new intent in TaxiDetails. no joy... All help appreciated.
Code as below - All help appreciated and thanks in advance....
MainActivity.java
package com.stravides.jdw;
import android.app.AlertDialog;
import android.content.Context;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
TextView lbl;
DBController controller = new DBController(this);
Button btnimport;
Button btnphone;
Button btnclear;
ListView lv;
ArrayList<HashMap<String, String>> myList;
public static final int requestcode = 1;
final Context context = this;
protected Cursor kursor;
protected ListAdapter adapter;
protected SQLiteDatabase db;
public AdapterView.OnItemClickListener mMessageClickedHandler = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Intent intent = new Intent("com.stravides.jdw.TaxiDetails.class");
Cursor kursor = (Cursor) adapter.getItem(position);
intent.putExtra("TAXI_ID", kursor.getInt(kursor.getColumnIndex("_id")));
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lbl = (TextView) findViewById(R.id.txtresulttext);
btnimport = (Button) findViewById(R.id.btnupload);
btnphone = (Button) findViewById(R.id.btnphone);
btnclear = (Button) findViewById(R.id.btnclear);
lv = getListView();
btnimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("gagt/sdf");
try {
startActivityForResult(fileintent, requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity that can handle file selection. Showing alternatives.");
}
}
});
btnclear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "taxiinfo";
db.execSQL("delete from " + tableName);
myList = controller.getAllProducts();
if (myList.size() == 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,R.layout.v, new String[]
{"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks"}, new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
setListAdapter(adapter);
lbl.setText("Data Cleared");
}
}
});
btnphone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uri = "tel:" + "0031251491418";
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
myList= controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]{"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks"}, new int[]{
R.id.txttaxibID, R.id.txttaxibDate, R.id.txttaxibTime,R.id.txttaxibFrom, R.id.txttaxibTo, R.id.txttaxibFlightNum, R.id.txttaxibFlightDest, R.id.txttaxibPassenger, R.id.txttaxibEmail, R.id.txttaxibTelno, R.id.txttaxibMobNo, R.id.txttaxibCostCentre, R.id.txttaxibPersNo, R.id.txttaxibCombine, R.id.txttaxibNumPass, R.id.txttaxibRemarks});
setListAdapter(adapter);
lbl.setText("");
}
lv.setOnItemClickListener(mMessageClickedHandler);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String filepath = data.getData().getPath();
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "taxiinfo";
db.execSQL("delete from " + tableName);
try {
if (resultCode == RESULT_OK) {
try {
FileReader file = new FileReader(filepath);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split(",", 16);
String bID = str[0];
String bDate = str[1];
String bTime = str[2];
String bFrom = str[3];
String bTo = str[4];
String bFlightNum = str[5];
String bFlightDest = str[6];
String bPassenger = str[7];
String bEmail = str[8];
String bTelno = str[9];
String bMobNo = str[10];
String bCostCentre = str[11];
String bPersNo = str[12];
String bCombine = str[13];
String bNumPass = str[14];
String bRemarks = str[15];
contentValues.put("bID", bID);
contentValues.put("bDate", bDate);
contentValues.put("bTime", bTime);
contentValues.put("bFrom", bFrom);
contentValues.put("bTo", bTo);
contentValues.put("bFlightNum", bFlightNum);
contentValues.put("bFlightDest", bFlightDest);
contentValues.put("bPassenger", bPassenger);
contentValues.put("bEmail", bEmail);
contentValues.put("bTelno", bTelno);
contentValues.put("bMobNo", bMobNo);
contentValues.put("bCostCentre", bCostCentre);
contentValues.put("bPersNo", bPersNo);
contentValues.put("bCombine", bCombine);
contentValues.put("bNumPass", bNumPass);
contentValues.put("bRemarks", bRemarks);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
}
} else {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle("Only CSV files allowed");
d.show();
}
} catch (Exception ex) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(ex.getMessage().toString() + "second");
d.show();
}
}
myList= controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]{"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks"}, new int[]{
R.id.txttaxibID, R.id.txttaxibDate, R.id.txttaxibTime,R.id.txttaxibFrom, R.id.txttaxibTo, R.id.txttaxibFlightNum, R.id.txttaxibFlightDest, R.id.txttaxibPassenger, R.id.txttaxibEmail, R.id.txttaxibTelno, R.id.txttaxibMobNo, R.id.txttaxibCostCentre, R.id.txttaxibPersNo, R.id.txttaxibCombine, R.id.txttaxibNumPass, R.id.txttaxibRemarks});
}
}
}
DBController.java
package com.stravides.jdw;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
public class DBController extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public DBController(Context applicationcontext) {
super(applicationcontext, "jdwtaxi.db", null, 1); // creating DATABASE
Log.d(LOGCAT, "Created");
}
#Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE IF NOT EXISTS taxiinfo ( Id INTEGER PRIMARY KEY, bID TEXT,bDate TEXT, bTime TEXT,bFrom TEXT, bTo TEXT, bFlightNum TEXT, bFlightDest TEXT, bPassenger TEXT, bEmail TEXT, bTelno TEXT, bMobNo TEXT, bCostCentre TEXT, bPersNo TEXT, bCombine TEXT, bNumPass TEXT, bRemarks TEXT)";
database.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase database, int version_old,int current_version) {
String query;
query = "DROP TABLE IF EXISTS taxiinfo";
database.execSQL(query);
onCreate(database);
}
public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> taxiList;
taxiList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM taxiinfo";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
//Id, Company,Name,Price
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("bID", cursor.getString(1));
map.put("bDate", cursor.getString(2));
map.put("bTime", cursor.getString(3));
map.put("bFrom", cursor.getString(4));
map.put("bTo", cursor.getString(5));
map.put("bFlightNum", cursor.getString(6));
map.put("bFlightDest", cursor.getString(7));
map.put("bPassenger", cursor.getString(8));
map.put("bEmail", cursor.getString(9));
map.put("bTelno", cursor.getString(10));
map.put("bMobNo", cursor.getString(11));
map.put("bCostCentre", cursor.getString(12));
map.put("bPersNo", cursor.getString(13));
map.put("bCombine", cursor.getString(14));
map.put("bNumPass", cursor.getString(15));
map.put("bRemarks", cursor.getString(16));
taxiList.add(map);
} while (cursor.moveToNext());
}
return taxiList;
}
}
TaxiDetails.java
package com.stravides.jdw;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
/**
* Created by Ken on 09/08/2015.
*/
public class TaxiDetails extends Activity {
protected TextView bID;
protected TextView bDate;
protected TextView bTime;
protected TextView bFrom;
protected TextView bTo;
protected TextView bFlightNum;
protected TextView bFlightDest;
protected TextView bPassenger;
protected TextView bEmail;
protected TextView bTelno;
protected TextView bMobNo;
protected TextView bCostCentre;
protected TextView bPersNo;
protected TextView bCombine;
protected TextView bNumPass;
protected TextView bRemarks;
protected int taxiPos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultstable);
taxiPos = getIntent().getIntExtra("TAXI_ID", 0);
SQLiteDatabase db = (new DBController(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT bID, bDate, bCombine FROM taxiinfo WHERE bID = ?", new String[]{""+taxiPos});
if (cursor.getCount() == 1)
{
cursor.moveToFirst();
bID = (TextView) findViewById(R.id.txttaxibID2);
bID.setText(cursor.getString(cursor.getColumnIndex("bID")));
bDate = (TextView) findViewById(R.id.txttaxibDate2);
bDate.setText(cursor.getString(cursor.getColumnIndex("bDate")));
bCombine = (TextView) findViewById(R.id.txttaxibCombine2);
bCombine.setText(cursor.getString(cursor.getColumnIndex("bCombine")));
}
}
}
activity_main.xml
<?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="vertical"
android:weightSum="9"
android:background="#FFC7C7C7"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Booking Details"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="0.24" />
<!-- divider -->
<LinearLayout
android:id="#+id/lvcontainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:padding="1dp"
android:background="#FFC7C7C7"
android:weightSum="6">
<TextView
android:id="#+id/txttaxibID"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".8"
android:gravity="left"
android:text="Ref"
android:textColor="#000000"
android:textSize="13sp"
android:clickable="false" />
<TextView
android:id="#+id/txttaxibDate"
android:layout_width="15dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:padding="3dp"
android:text="Date"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".8"
android:gravity="left"
android:text="Time"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibFrom"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="From"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibTo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="To"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibCombine"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="Combine"
android:padding="1dp"
android:textColor="#000000"
android:textSize="13sp" />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="#+id/lvcontainer"
android:layout_weight="6.59"
android:clickable="false"></ListView>
<TextView
android:id="#+id/txtresulttext"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="5dp"
android:layout_below="#android:id/list"
android:layout_marginTop="2dp"
android:layout_weight="0.5"
android:gravity="left"
android:text=""
android:textColor="#FFF55F54"
android:textSize="10sp"
android:textStyle="italic|bold"></TextView>
<LinearLayout
android:id="#+id/lvbottom"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="1">
<Button
android:id="#+id/btnupload"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.33"
android:gravity="center"
android:text="UPLOAD"
android:textColor="#ffffff"
android:background="#1083f5"
android:textSize="15sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnclear"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.33"
android:gravity="center"
android:text="CLEAR"
android:textColor="#ffffff"
android:background="#1003f5"
android:textSize="15sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnphone"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.34"
android:gravity="center"
android:text="CALL JDW"
android:textColor="#ffffff"
android:background="#ffff0000"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
v.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="vertical" >
<LinearLayout
android:id="#+id/lvh"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:scrollbars="horizontal"
android:background="#ffe6e6e6"
android:weightSum="5"
android:minHeight="30dp"
android:measureWithLargestChild="false"
android:longClickable="false">
<TextView
android:id="#+id/txttaxibID"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="Ref"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibDate"
android:layout_width="15dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:padding="3dp"
android:text="Date"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibTime"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="Time"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibFrom"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="From"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibTo"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="To"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
resultstable.xml
<TextLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/status2"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:text="Booking Details"
android:textColor="#890000"
android:textSize="25sp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/txttaxibID2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginLeft="20dip"
/>
<TextView
android:id="#+id/txttaxibDate2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginLeft="20dip" />
<TextView
android:id="#+id/txttaxibCombine2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginLeft="20dip" />
</TextLayout>
csv data for testing
372187,20/09/2015,20:00,Schiphol Taxi Counter Jan de Wit Group,Hotel Lion D'or Golden Tulip,KL1064,Cardiff,Ken Midgley,me#home.com,Ken Midgley,441234567889,41024830,1044889,None,1,
372188,21/09/2015,08:00,Hotel Lion D'or Golden Tulip,3H.18 Dudokhuis Hoofdingang,None,None,Ken Midgley,me#home.com,Ken Midgley,441234567889,41024830,1044889,None,1,Have to be in office by 8:30!!!
372189,21/09/2015,17:30,3H.18 Dudokhuis Hoofdingang,Hotel Lion D'or Golden Tulip,None,None,Ken Midgley,me#home.com,Ken Midgley,441234567889,41024830,1044889,None,1,
372190,22/09/2015,08:00,Hotel Lion D'or Golden Tulip,3H.18 Dudokhuis Hoofdingang,None,None,Ken Midgley,me#home.com,Ken Midgley,441234567889,41024830,1044889,None,2,Mike Smith. Have to be in office by 8:30!!!
You need an OnItemClickListener set on your ListView. Here is a simple tutorial how this works - http://www.mkyong.com/android/android-listview-example/
After you learn to intercept and handle the event, you can start thinking about navigating to a details activity, or opening a details dialog.
I suggest you go through all of the basic tutorials in http://developer.android.com - all you need is there.
I do something like this:
public void onClickList(final ListView list) {
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent,
final View view, final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setCancelable(false);
alert.setMessage("youre message");
final AlertDialog.Builder ok = alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
//add your code here
dialog.dismiss();
}
});
alert.show();
}
});
}
Where the list is the ListView object you create. You can send to this method onClickListener() your ListView to manage the popup. By the way, you can create your own xml layout to render a custom view.
Thank you for your assistance on the above - I managed now to resolve this issue.
The problem was thinking too hard about passing the position of the click....
The MainActivity.java needs the following...
public AdapterView.OnItemClickListener mMessageClickedHandler = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Intent intent = new Intent(MainActivity.this,TaxiDetails.class);
intent.putExtra("TAXI_ID", position);
startActivity(intent);
}
};
The TaxiDetails.java then can pick up the extra info in the intent
taxiPos = getIntent().getIntExtra("TAXI_ID", 0);
taxiPos=taxiPos+1;
SQLiteDatabase db = (new DBController(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM taxiinfo WHERE Id = ?", new String[]{""+taxiPos});
if (cursor.getCount() == 1)

Can't populate textview from database

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 ^^

Displaying the button at the end of the ListView with Linear Layout

I am a newbie in android application development. I faced a problem regarding the displaying a button at the end of the List View. I am using Linear Layout. The application can show all the list but cannot show the Button. I have also pasted my XML code here. Any help in this regard, will be highly appreciated.
Mohan
main.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"
>
<ImageView
android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_New"
android:width="170dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:text="Click"
/>
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/btn_New"
android:text="#string/hello"
/>
<ListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/textView"
/>
</RelativeLayout>
contactlistitem.xml
<?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" android:weightSum="1">
<TextView
android:id="#+id/txtDisplayName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium" >
</TextView>
<ImageView android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"></TextView>
</LinearLayout>
ContactListActivity.java
package com.contactlist;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.Data;
public class ContactListActivity extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContactList contactList=this.getContacts();
ArrayAdapter<Contact> adapter=new ContactAdapter(this,contactList.getContacts());
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object o=this.getListAdapter().getItem(position);
Contact c=(Contact)o;
Toast.makeText(this, c.getDisplayName(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, c.getId(), Toast.LENGTH_SHORT).show();
}
private ContactList getContacts()
{
ContactList contactList=new ContactList();
Uri uri=ContactsContract.Contacts.CONTENT_URI;
ContentResolver cr=getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur=cr.query(uri, null, null, null, sortOrder);
if(cur.getCount() >0)
{
String id;
String img;
String name;
while(cur.moveToNext())
{
Contact c =new Contact();
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
img= cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
name=cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
final Bitmap photo;
if(img != null) {
photo = queryContactBitmap(img);
} else {
photo = null;
}
c.setId(id);
c.setImage(photo);
c.setDisplayName(name);
contactList.addContact(c);
}
}
// cur.close();
return contactList;
}
private Bitmap queryContactBitmap(String photoId) {
final Cursor photo = managedQuery(
Data.CONTENT_URI,
new String[] {Photo.PHOTO}, // column where the blob is stored
Data._ID + "=?", // select row by id
new String[]{photoId}, // filter by the given photoId
null);
final Bitmap photoBitmap;
if(photo.moveToFirst()) {
byte[] photoBlob = photo.getBlob(
photo.getColumnIndex(Photo.PHOTO));
photoBitmap = BitmapFactory.decodeByteArray(
photoBlob, 0, photoBlob.length);
} else {
photoBitmap = null;
}
photo.close();
return photoBitmap;
}
}
ContactList.java
package com.contactlist;
import java.util.ArrayList;
import java.util.List;
public class ContactList {
private List<Contact> _contacts=new ArrayList<Contact>();
public List<Contact> getContacts(){return _contacts;}
public void addContact(Contact contact){ this._contacts.add(contact);}
}
ContactAdapter.java
package com.contactlist;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactAdapter extends ArrayAdapter<Contact> {
private final List<Contact> _contacts;
private final Activity _context;
public ContactAdapter(Activity context, List<Contact> contacts)
{
super(context,R.layout.main,contacts);
this._contacts=contacts;
this._context=context;
}
static class ViewHolder {
protected TextView text;
private Contact _contact;
public ImageView imageview;
protected void setContact(Contact contact)
{
text.setText(contact.getDisplayName());
imageview.setImageBitmap(contact.getImage());
_contact=contact;
}
protected Contact getContact() {return _contact;}
}
#Override
public Contact getItem(int position)
{
return _contacts.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view=null;
if(convertView==null)
{
LayoutInflater inflater=_context.getLayoutInflater();
view=inflater.inflate(R.layout.contactlistitem, null);
final ViewHolder viewHolder=new ViewHolder();
viewHolder.text=(TextView)view.findViewById(R.id.txtDisplayName);
viewHolder.imageview =(ImageView)view.findViewById(R.id.contact_image);
viewHolder.setContact(_contacts.get(position));
view.setTag(viewHolder);
}
else
{
view = convertView;
}
return view;
}
}
Contact.java
package com.contactlist;
import java.util.ArrayList;
import android.R.string;
import android.graphics.Bitmap;
public class Contact {
private String _id;
private String _displayName;
private Bitmap _img;
public String getId(){return _id;}
public String getDisplayName(){return _displayName;}
public Bitmap getImage(){return _img;}
public void setId(String id){_id=id;}
public void setDisplayName(String displayName){_displayName=displayName;}
public void setImage(Bitmap img){_img=img;}
}
Try this and see if it works:
<?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"
>
<ImageView
android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_New"
android:width="170dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:text="Click"
/>
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/btn_New"
android:text="#string/hello"
/>
<ListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/textView"
/>
</RelativeLayout>
MainActivity class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.contactList);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
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);
}
Now when you put things inside the listView it should not "push" the button or the textView down.
Firstly you have to set a linear layout in a main relative layout and set its gravity bottom
<RelativeLayout
android:width = "fill..."
android....>
<LinearLayout
android:gravity="bottom"
android:id="#+id/linear1"
android:layout_alignParentBottom="true">
<Button/>
</LinearLayout>
<ListView
android:layout_above="#id/linear"/>
android:layout_weight="1"
delete it.
if you are not express 'android:layout_weightSum' on over level that cotains some components are express 'android:layout_weight' but also component that contain 'android:layout_weight="1"' code is exactly change size to fullscreen.
(i'm sorry, i can't speak english very well....)
android:layout_weight="1" is wrong
android:layout_weight="1" delete it
Or use android:layout_weightSum first.

Categories

Resources