i'am trying develop an application which save points and date in a database but, i want to show into a list the points in green and date in white. The points and the time points are above one another. My code:
Class database
public class BaseDeDatos extends SQLiteOpenHelper{
public BaseDeDatos(Context context) {
super(context, "puntuaciones", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE puntuaciones (puntos INTEGER,fecha VARCHAR)");
}
public void save(int points,String date){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("INSERT INTO puntuaciones VALUES("+points+","+"'"+date+"')");
db.close();
}
public Vector<String> listPoints(int cantidad) {
Vector<String> result = new Vector<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT puntos, fecha FROM " +
"puntuaciones ORDER BY puntos DESC LIMIT " +cantidad, null);
while (cursor.moveToNext()){
result.add(cursor.getInt(0)+cursor.getString(1));
}
cursor.close();
db.close();
return result;
}
and my class with the list
ListView lista;
BaseDeDatos bd;
Vector maxRegis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maximos_registros);
lista=(ListView)findViewById(R.id.lista);
lista.setBackgroundColor(color.Aquamarine);
maxRegis= new Vector();
bd= new BaseDeDatos(this);
maxRegis=bd.listaPuntos(10);
ArrayAdapter adaptador= new ArrayAdapter(this,R.layout.elemento_lista,R.id.tv1,maxRegis);
//MyAdapter adaptador= new MyAdapter(this,bd);
lista.setAdapter(adaptador);
}
and the code of R.layout.elemento_lista
<?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="?android:attr/listPreferredItemHeight" >
<TextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:layout_marginLeft="40dp"
android:inputType="textCapCharacters"
android:textColor="#FFD700"
android:textStyle="bold"
android:text="" />
<TextView
android:id="#+id/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv1"
android:layout_alignParentBottom="true"
android:textStyle="italic"
android:text="" />
if i make a special adapter shows nothing, but with ArrayAdapter shows into the same TextView.
You should use CustomAdapter which extends BaseAdapter
Here is my sample TodoApp with CustomAdapter.
You must inflate R.layout.elemento_lista in
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(R.layout.elemento_lista, null);
}
TextView title = (TextView) convertView.findViewById(R.id.todo_title);
title.setText(getItem(position));
return convertView;
}
Then find your TextView by id, setText, and that's all :-)
Related
So basically my goal is to create a notes a page for people to write text/upload files and display those in a list. Right now I am working on doing it through text. I have never used a Database before and as of right now the code will let the user type in text and it will display it on the screen and add it to the database.
My code:
Main Activity:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
// Declare references
EditText userInput;
TextView recordsTextView;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userInput = (EditText) findViewById(R.id.user_Input);
recordsTextView = (TextView) findViewById(R.id.records_TextView);
/* Can pass nulls because of the constants in the helper.
* the 1 means version 1 so don't run update.
*/
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Print the database
public void printDatabase(){
String dbString = dbHandler.databaseToString();
recordsTextView.setText(dbString);
userInput.setText("");
}
//add your elements onclick methods.
//Add a product to the database
public void addButtonClicked(View view){
// dbHandler.add needs an object parameter.
Products product = new Products(userInput.getText().toString());
dbHandler.addProduct(product);
printDatabase();
}
//Delete items
public void deleteButtonClicked(View view){
// dbHandler delete needs string to find in the db
String inputText = userInput.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
}
MyDBHandler:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "productDB.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
//We need to pass database information along to superclass
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT " +
");";
db.execSQL(query);
}
//Lesson 51
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add a new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete a product from the database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";");
}
// this is goint in record_TextView in the Main activity.
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";// why not leave out the WHERE clause?
//Cursor points to a location in your results
Cursor recordSet = db.rawQuery(query, null);
//Move to the first row in your results
recordSet.moveToFirst();
//Position after the last row means the end of the results
while (!recordSet.isAfterLast()) {
// null could happen if we used our empty constructor
if (recordSet.getString(recordSet.getColumnIndex("productname")) != null) {
dbString += recordSet.getString(recordSet.getColumnIndex("productname"));
dbString += "\n";
}
recordSet.moveToNext();
}
db.close();
return dbString;
}
}
Products:
public class Products {
private int _id;
private String _productname;
//Added this empty constructor in lesson 50 in case we ever want to create the object and assign it later.
public Products(){
}
public Products(String productName) {
this._productname = productName;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_productname() {
return _productname;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
}
activity_main.xml;
<RelativeLayout 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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/user_Input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="69dp"
android:width="300dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/add_Button"
android:layout_below="#+id/user_Input"
android:layout_alignStart="#+id/user_Input"
android:layout_marginTop="40dp"
android:onClick="addButtonClicked"
android:layout_alignLeft="#+id/user_Input" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:id="#+id/delete_Button"
android:layout_alignTop="#+id/add_Button"
android:layout_alignEnd="#+id/user_Input"
android:onClick="deleteButtonClicked"
android:layout_alignRight="#+id/user_Input" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/records_TextView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Use room, it will be easy to use local SQLite db using room, all you need to define entity, dao and database using Room annotations.
For displaying list of records in listview, just create list view adapter and bind record data to views in item layout. I suggest you use RecyclerView instead of listview to get performance benefits.
You can find room and recycler view examples here http://www.zoftino.com/android
Create a ListView somewhere (I created a new 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="net.pelozo.testjava.MainActivity">
<ListView
android:id="#+id/listview_products"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Create row_product.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" >
<TextView
android:id="#+id/textview_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/textview_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Add this method to your database clase:
public ArrayList<Products> getProducts(){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Products> products = new ArrayList<Products>();
while(cursor.moveToNext()){
Products product = new Products();
product.set_id(cursor.getInt(0));
product.set_productname(cursor.getString(1));
products.add(product);
}
cursor.close();
db.close();
return products;
}
create a ProductsAdapter:
public class ProductsAdapter extends ArrayAdapter<Products> {
// View lookup cache
private static class ViewHolder {
TextView id;
TextView name;
}
public ProductsAdapter(Context context, ArrayList<Products> products) {
super(context, R.layout.row_product, products);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Products product = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_product, parent, false);
viewHolder.id = (TextView) convertView.findViewById(R.id.textview_id);
viewHolder.name = (TextView) convertView.findViewById(R.id.textview_name);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data from the data object via the viewHolder object
// into the template view.
viewHolder.id.setText("id:" + product.get_id());
viewHolder.name.setText("name: " + product.get_productname());
// Return the completed view to render on screen
return convertView;
}
}
Now just put it all together:
//get db
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
//add a product
dbHandler.addProduct(new Products("Product Name"));
//retrieve products from db
ArrayList<Products> productsList = dbHandler.getProducts();
// Create the adapter
ProductsAdapter adapter = new ProductsAdapter(this, productsList);
// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.listview_products);
//set adapter
listView.setAdapter(adapter);
I am working on a sqlite database project on android. And it's my first sqlite project. I read lots of article and created my app but there's a problem that I can't find a way to solve it.i want to get NAME_FILTER table to autoCompleteTextView
here is my layout code
<?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:paddingTop="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="#string/customers_name"
android:textSize="16sp" />
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"/>
<EditText
android:id="#+id/edt_filter_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:imeOptions="actionNext"
style="#style/EditText.Input"
android:theme="#style/EditText.Input"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20dp"
android:paddingBottom="20dp">
<Button
android:id="#+id/btn_submit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/btn_submit"
android:textColor="#333333"
android:background="#drawable/buttonshape"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textSize="18sp"
android:drawableStart="#drawable/ic_check_black_24dp"/>
<Button
android:id="#+id/btn_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/btn_cancel"
android:textColor="#333333"
android:background="#drawable/red_button_background"
android:textSize="18sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:drawableStart="#drawable/ic_cancel_black_24dp"/>
</LinearLayout>
</LinearLayout>
and here is my Activity
public class FiltersActivity extends AppCompatActivity implements ActionMode.Callback{
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
private static int Filter_list_position = -1;
private Button btnSubmit;
private Button btnCancel;
private ListView listView;
private FilterListAdapter adapter;
private EditText edtName;
private int seletcedFilterId;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.filters_title);
setContentView(R.layout.activity_filters);
btnCancel = (Button) findViewById(R.id.btn_cancel);
btnSubmit = (Button) findViewById(R.id.btn_submit);
edtName = (EditText) findViewById(R.id.edt_filter_name);
btnCancel.setOnClickListener(onCancelbuttonClicked);
listView = (ListView) findViewById(R.id.listView);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapterr = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, NAME_FILTER);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapterr);//setting the adapter data into the AutoCompleteTextView
refreshList();
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
DataBaseHelper Cllas
public class DatabaseHelper {
private SQLiteDatabase mydb;
public DatabaseHelper(Context context){
mydb = new MyDatabase(context).getWritableDatabase();
}
public void addNewFilter(filter filter){
ContentValues values = new ContentValues();
values.put("name", filter.getName());
mydb.insert(MyDatabase.tableFilters, null, values);
mydb.close();
}
public List<filter> getListOfFilters(){
Cursor c = mydb.rawQuery("select * from " + MyDatabase.tableFilters, null);
List<filter> filters = new ArrayList<>();
while (c.moveToNext()){
filter em = new filter();
em.setId(c.getInt(c.getColumnIndex(MyDatabase.ID_FILTER)));
em.setName(c.getString(c.getColumnIndex(MyDatabase.NAME_FILTER)));
filters.add(em);
}
c.close();
mydb.close();
return filters;
}
public void editFilter(filter filter){
ContentValues values = new ContentValues();
values.put("name", filter.getName());
mydb.update(MyDatabase.tableFilters, values, "id = " + filter.getId(), null);
mydb.close();
}
public void deleteFilter(filter filter){
mydb.delete(MyDatabase.tableFilters, "id = " + filter.getId(), null);
mydb.close();
}
public List<filter> searchFilterByName(String name){
Cursor c = mydb.rawQuery("select * from " + MyDatabase.tableFilters + " where name like '%" + name + "%'", null);
List<filter> filters = new ArrayList<>();
while (c.moveToNext()){
filter em = new filter();
em.setId(c.getInt(c.getColumnIndex(MyDatabase.ID_FILTER)));
em.setName(c.getString(c.getColumnIndex(MyDatabase.NAME_FILTER)));
filters.add(em);
}
c.close();
mydb.close();
return filters;
}
}
and this is my ListAdapter Class
class FilterListAdapter extends BaseAdapter {
private Context context;
private List<filter> filters;
FilterListAdapter(Context context, List<filter> filters){
this.context = context;
this.filters = filters;
}
#Override
public int getCount() {
return filters.size();
}
#Override
public Object getItem(int i) {
return filters.get(i);
}
#Override
public long getItemId(int i) {
return filters.get(i).getId();
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
View rowView = LayoutInflater.from(context).inflate(R.layout.filter_list_item, viewGroup, false);
TextView txtName = (TextView) rowView.findViewById(R.id.txt_filter_name);
txtName.setText(filters.get(position).getName());
return rowView;
}
}
I'm working with Java and XML in Android Studio to populate a ListView with CursorAdapter. I'm kinda new to this and trying to solv a problem. I'm really green so any tips would also help.
My DBHandler looks like that:
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 10;
private static final String DATABASE_NAME = "jogging.db";
public static final String TABLE_TRIP = "Trip";
public static final String TUR_COLUMN_ID = "_id";
public static final String TUR_COLUMN_DISTANCE = "Ditance";
public static final String TUR_COLUMN_SCORE = "Fastest";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TRIP + "(" +
TUR_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TUR_COLUMN_DISTANCE + " TEXT, " +
TUR_COLUMN_SCORE + " TEXT " +
");";
db.execSQL(query);
}
CursorAdapter I'm trying to use to get data to ListView:
public class TripCursorAdapter extends CursorAdapter {
public TripCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.content_trips, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tripId = (TextView) view.findViewById(R.id.tripIdView);
TextView tripDistance = (TextView) view.findViewById(R.id.tripDistanceView);
TextView tripScore = (TextView) view.findViewById(R.id.tripScoreView);
String id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String distance = cursor.getString(cursor.getColumnIndexOrThrow("Ditance"));
String score = cursor.getString(cursor.getColumnIndexOrThrow("Fastest"));
tripId.setText(id);
tripDistance.setText(distance);
tripScore.setText(score);
}
And the activity to set up ListView
public class TripsActivity extends AppCompatActivity {
DBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trips);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbHandler = new DBHandler(this);
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor tripCursor = db.rawQuery("SELECT * FROM Trip", null );
ListView lvItems = (ListView) findViewById(R.id.listView);
TripCursorAdapter tripAdapter = new TripCursorAdapter(this, tripCursor, 0);
lvItems.setAdapter(tripAdapter);
}
XML Files:
trips_content.xml
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="hmk.fitness_app.TripsActivity"
tools:showIn="#layout/activity_trips">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
And I have also item_trip.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:id="#+id/tripIdView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distance"
android:id="#+id/tripDistanceView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:id="#+id/tripScoreView"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
Not quite sure why I get error msg about null object referances. Any tips what I should do?
Change
return LayoutInflater.from(context).inflate(R.layout.content_trips, parent, false);
to
return LayoutInflater.from(context).inflate(R.layout.item_trip, parent, false);
xml for save database please help me to## i want add delete button in listview's each row when button is pressed delete that data from listview and database ##
here is first xml file
<LinearLayout 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="#F3CAE5"
android:orientation="vertical"
android:padding="5dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/frst_txtV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First name"
android:textColor="#000" />
<EditText
android:id="#+id/frst_editTxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/frst_txtV" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/lst_txtV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Last name"
android:textColor="#000" />
<EditText
android:id="#+id/last_editTxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/lst_txtV" />
</LinearLayout>
<Button
android:id="#+id/save_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Save"
android:textColor="#000" />
</LinearLayout>
display_activty.xml list view xml
<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:background="#B58897"
android:gravity="center_horizontal" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="Add" />
<View
android:id="#+id/a"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/btnAdd"
android:background="#8DB3E1" />
<ListView
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/a"
android:divider="#8DB3E1"
android:dividerHeight="2dp" />
</RelativeLayout>
displayadapter.java here i add button if i press button than record is will delete from database as well from listview
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private SQLiteDatabase dataBase;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.btn = (Button) child.findViewById(R.id.Button1);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
}
});
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
Button btn;
//ImageView img;
}
}
listcell.xml this is to display custom listview xml file
<LinearLayout 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="#F3CAE5"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp" >
<TextView
android:id="#+id/txt_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
<TextView
android:id="#+id/txt_fName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<TextView
android:id="#+id/txt_lName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<Button android:text="Button"
android:id="#+id/Button1"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
DisplayActivty.java here is listview adding class
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Addactivty.java add database class
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
edit_first.setText(fname);
edit_last.setText(lname);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
if(fname.length()>0 && lname.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
Create Custom Array Adapter like this
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.inflatelistview, null);
TextView text=(TextView)vi.findViewById(R.id.textView1);
ImageView image=(ImageView)vi.findViewById(R.id.imageView1);
Button btn=(Button)vi.findViewById(R.id.button1);
btn.setTag(position);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
//items.remove(index.intValue());
data.remove(position);
notifyDataSetChanged();
}
});
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
As you're inserting (Addactivty.java add database class) and fetching (DisplayActivty.java here is listview adding class) data from database similarly you can delete.
For example :
public static boolean Delete(Context context, int id) {
SQLiteDatabase db = new MyDataBase(context).getWritableDatabase();
int res = db.delete(CATEGORY, ID + " = " + id, null);
if (db.isOpen())
db.close();
return (res == 0 ? false : true);
}
You need to delete data from database and listView inside the click listener,like :
mHolder.btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
//1. get the clicked item's *ID*
// (as you did id.get(pos), in your adapter class).
//2. delete data from database using this *ID*.
// (see above function).
//3. remove position from your list.
// list.remove(position);
// (in your case you've multiple lists remove position from all)
//4. notifyDataSetChanged();
}
});
Helping link :
notifyDataSetChanged();
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.
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 ^^