I want help for displaying data in listview from local database SQLite. I have already data in the database.
so please help me with where am I doing mistakes?
below code of DatabseHelper.Java
private static final String DATABASE_NAME = "Barcode_Printing.db";
static final String TABLE_NAME = "Item_Master";
static final String Item_name = "Item_Name";
static final String wEight = "Weight";
static final String MrP = "MRP";
static final String BarcodE = "BARCODE";
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + BarcodE + " INTEGER PRIMARY KEY, " + Item_name + " TEXT, " + wEight + " TEXT, " + MrP + " INTEGER, EXPIRY_DATE TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getAllItems() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{BarcodE, Item_name, wEight, MrP},
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
return cursor;
}
else
{
return null;
}
}
below for activity_dispaly_items.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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="com.packlab.alpesh.barcodeprinting.Display_Items">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ListView
android:id="#+id/lvItem_Display"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
tools:layout_editor_absoluteY="3dp" />
</android.support.design.widget.CoordinatorLayout>
below for items_display_layout.xml
<?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">
<TextView
android:id="#+id/tvItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.065"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvBarcode"
android:layout_width="wrap_content"
android:layout_height="19dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="48dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.119"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvMrp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.119"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvWeight" />
<TextView
android:id="#+id/tvWeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.119"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvBarcode" />
</android.support.constraint.ConstraintLayout>
below code for DisplayItems.Java
its give me error directly "There was an error!"
its don't go in try. its go directly in Catch.
public class Display_Items extends AppCompatActivity
{
SimpleCursorAdapter simpleCursorAdapter;
ListView display_Items;
DatabaseHelper DatabaseHelper;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display__items);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
spinner = findViewById(R.id.spinner_Comapny);
setSupportActionBar(toolbar);
display_Items = findViewById(R.id.lvItem_Display);
DatabaseHelper = new DatabaseHelper(this);
loadSpinnerData();
displayProductList();
}
private void displayProductList()
{
try
{
Cursor cursor = DatabaseHelper.getAllItems();
if (cursor == null)
{
Toast.makeText(Display_Items.this, "Unable to generate cursor.", Toast.LENGTH_SHORT).show();
return;
}
if (cursor.getCount() == 0)
{
Toast.makeText(Display_Items.this, "No Products in the Database.", Toast.LENGTH_SHORT).show();
return;
}
String[] columns = new String[] {
DatabaseHelper.BarcodE,
DatabaseHelper.Item_name,
DatabaseHelper.wEight,
DatabaseHelper.MrP
};
int[] boundTo = new int[] {
R.id.tvBarcode,
R.id.tvItemName,
R.id.tvWeight,
R.id.tvMrp
};
simpleCursorAdapter = new SimpleCursorAdapter(this,
R.layout.item_display_layout,
cursor,
columns,
boundTo,
0);
display_Items.setAdapter(simpleCursorAdapter);
}
catch (Exception ex)
{
Toast.makeText(Display_Items.this, "There was an error!", Toast.LENGTH_SHORT).show();
}
}
}
i provide simple way to read data from sqllite used below code ..
first make one pojo class ..
public class MyTable {
public String itemName,weight,mrp,barcod;
}
then after data base class make method for read data ...
public List<MyTable> getMyItems() {
List<MyTable> mySuperList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_NAME ;
Cursor c = db.rawQuery(selectQuery, null);
if (c != null) {
c.moveToFirst();
while (c.isAfterLast() == false) {
MyTable myTable = new MyTable();
myTable.itemName = (c.getString(c.getColumnIndex("Item_Name")));
myTable.weight = (c.getString(c.getColumnIndex("Weight")));
myTable.mrp = (c.getString(c.getColumnIndex("MRP")));
myTable.barcod = (c.getString(c.getColumnIndex("BARCODE")));
mySuperList.add(myTable);
c.moveToNext();
}
}
return mySuperList;
}
then after used this method and bind data into listview.
as above you bind data into listview then make custom adapter and take one layout for show all data in different view control.
adapter::
public class CommentsAdapter extends ArrayAdapter<MyTable> {
Context context;
List<MyTable> data = null;
public CommentsAdapter(Context context, int layoutResourceId, List<MyTable> data) {
super(context, layoutResourceId, data);
this.context = context;
this.data = data;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// if(context.get()!=null) {
final LayoutInflater inflater = ((Activity) context).getLayoutInflater();
final View outerContiner = inflater.inflate(R.layout.comment_item, parent, false);// define your layout
TextView text = (TextView) outerContiner.findViewById(R.id.comment_text);
TextView barcode = (TextView) outerContiner.findViewById(R.id.comment_barcode);
text.setText(data.get(position).itemName);
barcode.setText(data.get(position).barcode);
return outerContiner;
//}
}
}
then after used below code bind data..
Note ::Here layout same in adapter constructor and getView Method.
List<MyTableTwo> myTableTwos=dbHelper.getMyItems();
CommentsAdapter commentsAdapter=new CommentsAdapter(DbInsert.this,R.layout.table_layout,myTableTwos);
ListView listView=findViewById(R.id.liLvData);
listView.setAdapter(commentsAdapter);
commentsAdapter.notifyDataSetChanged();
Related
I am building a list box manipulated by cursor adapter. I have written the code below. RoomShare is the activity which holds the list. MessDatabase is the class that extends from SQLiteOpenHelper. TempDataFromDB is the temporary class that holds the record derived from DB.DB2CursorAdapter is the cursor adapter.
In RoomShare activity I am creating the MessDatabase object(derived from SQLiteOpenHelper). In the constructor of MessDatabase, I am creating table "Share_room" and adding a row to it Then Select* query is run on cursor.Then DB2CursorAdapter object is created. In the newView of DB2CursorAdapter, I am populating 2 textviews.
When I populate 2 textViews, the list item appears overwritten. But when I use 1 textview, in db_cursor_roomShare.xml, everything is fine. I think some problem with xml file.
public class RoomShare extends AppCompatActivity {
DB2CursorAdapter DBAdapter;
MessDatabase mdb;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_share);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String selectQuery = "SELECT * FROM " + TempDataFromDB.TABLE_NAME /*+ " ORDER BY " +
TempDataFromDB.COLUMN_MESS_NAME + " DESC"*/;
//this.deleteDatabase("ShareRoom_db");
mdb = new MessDatabase(this);
SQLiteDatabase db = mdb.getWritableDatabase();//getReadableDatabase();
cursor = db.rawQuery(selectQuery,null);
DBAdapter = new DB2CursorAdapter(this, cursor);
final ListView listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(DBAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*Snackbar.make(view, "text u", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();*/
}
});
db.close();
}
public class MessDatabase extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ShareRoom_db";
public MessDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TempDataFromDB.CREATE_TABLE);
//insertMessName("Demo");
db.execSQL("INSERT INTO " + TempDataFromDB.TABLE_NAME +
"(" + TempDataFromDB.COLUMN_MESS_NAME +
")" + "VALUES " + "('One')");
}
public class DB2CursorAdapter extends CursorAdapter {
private LayoutInflater cursorInflater;
public DB2CursorAdapter(Context context, Cursor cursor) {
super(context,cursor);
System.out.println("Sandeep1");
/*cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);*/
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// R.layout.list_row is your xml layout for each row
System.out.println("Sandeep2");
cursorInflater = LayoutInflater.from(parent.getContext());
return cursorInflater.inflate(R.layout.db_cursor_room_share, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
System.out.println("Sandeep3");
TextView tvBody = (TextView) view.findViewById(R.id.tvBody);
TextView tvPriority = (TextView) view.findViewById(R.id.tvPriority);
// Extract properties from cursor
String id = cursor.getString(cursor.getInt(cursor.getColumnIndex(TempDataFromDB.COLUMN_ID)));
String mess_name = cursor.getString(cursor.getColumnIndex(TempDataFromDB.COLUMN_MESS_NAME));
Toast toast=Toast.makeText(context,mess_name,Toast.LENGTH_SHORT);
toast.show();//----This is printing perfectly one
// Populate fields with extracted properties
tvBody.setText(id);
tvPriority.setText(mess_name);
System.out.println("Sandeep4");
}
public class TempDataFromDB {
public static final String TABLE_NAME = "Share_room";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PARTICIPANTS = "Participants";
public static final String COLUMN_MESS_NAME = "Mess_Name";
private int id;
private String Participants;
String[] arrayParticipants;
private String Mess_Name;
// Create table SQL query
public static final String CREATE_TABLE =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_PARTICIPANTS+ " TEXT,"
+ COLUMN_MESS_NAME+"TEXT"
+ ")";
public TempDataFromDB() {
}
public TempDataFromDB(int id, String Participants,String Mess) {
this.id = id;
this.Participants = Participants;
this.Mess_Name = Mess;
}
db_cursor_roomShare.xml
<?xml version="1.0" encoding="utf8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match parent"
<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/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="mess name"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<android.support.constraint.ConstraintLayout>
activity_room_share.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/res-auto"
xmlns:tools="http://schemas.android.tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RoomShare"
<ListView android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weight="1"/>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
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'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);
On a database project, I've a table with three variables, namely '_id', 'item' for a food item name and 'type' for the type of food. I have three type's of food: 'Vege Soup', 'Non Vege Soup' and 'Chai'.
In my MainActivity Class, I have three radio buttons in a group which chooses the 'type' of item, followed by a 'view' button to get a ListView of all the items from the type chosen through the radio buttons.
I use the SimpleCursorAdapter, which is intended to map columns from a cursor to TextViews or ImageViews defined in an XML file.
The expected result is ListView contains the rows information. The current result is a blank ListView. I can't figure why.
MainActivity class:
public class MainActivity extends Activity implements OnClickListener,
OnCheckedChangeListener {
Button dinnerAdd, dinnerView;
RadioGroup dishType;
RadioButton vegeSoupView, nonVegeSoupView, chaiView;
Intent i, v;
String type;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize() {
dinnerView = (Button) findViewById(R.id.bView);
dishType = (RadioGroup) findViewById(R.id.rgDishType);
vegeSoupView = (RadioButton) findViewById(R.id.rDtVegeSoup);
nonVegeSoupView = (RadioButton) findViewById(R.id.rDtNonVegeSoup);
chaiView = (RadioButton) findViewById(R.id.rDtChai);
dinnerAdd.setOnClickListener(this);
dinnerView.setOnClickListener(this);
dishType.setOnCheckedChangeListener(this);
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.bAddDish:
i = new Intent("com.example.databaselist.ADDITEM");
startActivity(i);
break;
case R.id.bView:
didItWork = true;
if (vegeSoupView.isChecked()) {
type = "Vege Soup";
} else {
if (nonVegeSoupView.isChecked()) {
type = "Non Vege Soup";
} else {
if (chaiView.isChecked()) {
type = "Chai";
}
}
}
makeIntent();
startActivity(v);
break;
}
}
public void makeIntent(){
Bundle basket = new Bundle();
basket.putString("type", type);
v = new Intent(MainActivity.this, ItemListView.class);
v.putExtras(basket);
}
}
activity_main.xml:
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
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"
tools:context=".MainActivity" >
<RadioGroup
android:id="#+id/rgDishType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:layout_below="#id/bRandomise">
<RadioButton
android:id="#+id/rDtVegeSoup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Vege Soup" />
<RadioButton
android:id="#+id/rDtNonVegeSoup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Non Vege Soup"
android:textSize="15dp"/>
<RadioButton
android:id="#+id/rDtChai"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chai" />
</RadioGroup>
<Button
android:id="#+id/bView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/rgDishType"
android:layout_centerHorizontal="true"
android:text="View" />
<Button
android:id="#+id/bAddDish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/bView"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Add Dish" />
</RelativeLayout>
The 'view' button when pressed creates an intent to open the listview activity.
ItemListView class:
public class ItemListView extends Activity {
DBAdapter myDb;
MainActivity mA;
Intent a;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list_view);
Bundle gotBasket = getIntent().getExtras();
String from = gotBasket.getString("type");
openDB();
ListViewTypeFromDB_MainActivity(from);
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void ListViewTypeFromDB_MainActivity(String fromguy) {
Cursor cursor = myDb.getRows(fromguy);
startManagingCursor(cursor);
String[] fromFieldNames = new String[] { DBAdapter.KEY_ITEM };
int[] toViewIDs = new int[] { R.id.item_name };
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,
R.layout.item_layout,
cursor,
fromFieldNames,
toViewIDs
);
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
}
item_list_view.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" >
<ListView
android:id="#+id/listViewFromDB"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Here's the layout for each row of the listview.
item_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="NAME!"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
So, as you can see in the ItemListView Class, I have used the SimpleCursorAdapter. Though it managed to get to the item_list_view activity, it came up completely blank. Here is my DatabaseAdapter.
DBAdapter class:
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
// TODO: Setup your fields here:
public static final String KEY_ITEM = "item";
public static final String KEY_TYPE = "type";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_ITEM = 1;
public static final int COL_TYPE= 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_ITEM,
KEY_TYPE};
public static final String[] KEY_ITEM_ONLY = new String[] {KEY_ITEM};
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
public static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_ITEM + " string not null unique, "
+ KEY_TYPE + " string not null"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(String item, String type) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM, item);
initialValues.put(KEY_TYPE, type);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
public Cursor getRows(String type){
String where = KEY_TYPE + "='" + type + "'";
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion + " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
So, is there something wrong with the SimpleCursorAdapter, or could it be a problem in the DBAdapter Class?
I am trying to modify an example of a listview that is connected to a database. it was setup to only allow for one item in the listview to be selected and then for the user to click a "delete person" button. I have made changes that I thought would allow a user to select multiple people and then click delete and have it delete the items in list selected (checked) and then when the user clicks the delete button to go through a for loop and for the items that are checked to get their id and call the database and delete that row or item from the database table. The code runs and deletes items but it deletes the wrong items and only part of the selected items. I know it has something to do with the way I am checking for the id of the selected (checked) items in the list, but I don't know how to fix it. Please see the code in the onDeleteClick() method.
The source code for the main activity:
public class MainActivity extends ListActivity {
private static final int ADD_DIALOG = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView list = getListView();
list.setItemsCanFocus(false);
//list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// initialize the adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
//android.R.layout.simple_list_item_single_choice,
android.R.layout.simple_list_item_multiple_choice,
null,
new String[]{DBHelper.C_NAME},
new int[]{android.R.id.text1});
setListAdapter(adapter);
updateAdapterData();
}
public void updateAdapterData(){
// re-query the data
SQLiteDatabase db = new DBHelper(this).getReadableDatabase();
//SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
Cursor c = db.query(DBHelper.TABLE_PEOPLE, null, null, null, null,
null, null);
((SimpleCursorAdapter)getListAdapter()).changeCursor(c);
db.close();
}
public void onAddClicked(View view){
showDialog(ADD_DIALOG);
}
public void onDeleteClicked(View view){
ListView lstView = getListView(); // added for hw
//int position = getListView().getCheckedItemPosition(); // removed for hw
SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
for(int i = 0; i < lstView.getCount(); i++){
if(lstView.isItemChecked(i)){
long itemId = lstView.getItemIdAtPosition(i);
int rowsAffected = db.delete(DBHelper.TABLE_PEOPLE,
DBHelper.C_ID + " = " + itemId, null);
}
}
db.close();
//if(rowsAffected > 0)
updateAdapterData();
//if(position >= 0){
//long itemId = getListAdapter().getItemId(position);
//SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
//int rowsAffected = db.delete(DBHelper.TABLE_PEOPLE, DBHelper.C_ID
+ " = " + itemId, null);
//db.close();
//if(rowsAffected > 0)
// updateAdapterData();
//}
}
protected Dialog onCreateDialog(int id){
Dialog d;
switch(id){
case ADD_DIALOG:
d = new Dialog(this);
d.setContentView(R.layout.add_person_dialog);
d.setTitle("Add a Person");
final TextView nameText = (TextView)d.findViewById(R.id.name);
d.findViewById(R.id.okay_btn).setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
addPerson(nameText.getText().toString());
dismissDialog(MainActivity.ADD_DIALOG);
}
});
d.findViewById(R.id.cancel_btn).setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
dismissDialog(MainActivity.ADD_DIALOG);
}
});
break;
default:
d = super.onCreateDialog(id);
break;
}
return d;
}
public void addPerson(String name){
// add the new data to the db
DBHelper helper = new DBHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.C_NAME, name);
db.insert(DBHelper.TABLE_PEOPLE, null, cv);
db.close();
// update the view
updateAdapterData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
source code for database helper class:
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "myDatabase.db";
private static final int DB_VERSION = 1;
public static final String TABLE_PEOPLE = "people";
public static final String C_ID = "_id";
public static final String C_NAME = "name";
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String sqlCreateTablePeople = "CREATE TABLE "
+ TABLE_PEOPLE + "( " + C_ID
+ " integer primary key autoincrement, " + C_NAME
+ " text not null);";
db.execSQL(sqlCreateTablePeople);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
final String sqlDropTablePeople = "DROP TABLE IF EXISTS " + TABLE_PEOPLE +
";";
db.execSQL(sqlDropTablePeople);
onCreate(db);
}
}
the layout for the main activity:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Person"
android:onClick="onAddClicked"
/>
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Person"
android:onClick="onDeleteClicked"
/>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
></ListView>
</LinearLayout>
the layout for the add person dialog:
<?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" >
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/okay_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Okay"
/>
<Button
android:id="#+id/cancel_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel"
/>
</LinearLayout>
</LinearLayout>
Try using getCheckedItemIds()
public void onDeleteClicked(View view){
long[] positions = getListView().getCheckedItemIds();
SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
for(int i = 0; i < positions.length; i++){
int rowsAffected = db.delete(DBHelper.TABLE_PEOPLE,
DBHelper.C_ID + " = " + positions[i], null);
}
db.close();
if(rowsAffected > 0)
updateAdapterData();
}