I'm new to Android and have been working on this app for a while. Pretty much I'm loading initial values into the sqlite database with 3 columns: _id, product, and ingredients. I have an EditText box for the user to search the products to see if they have a certain ingredient in it. A listview is then printed out showing the products with these ingredients. I'm having some overall trouble with this code, specifically when I run it, it shows "Could not read row 0 col 1" from logcat.
Update: Thanks to Todd I fixed my original "Could not read row 0 and col 1" problem but now when I click the search button with edit text input "Apple" (which should output one product), the app doesn't update and stays static. Any help would be appreciated!
MySQLiteHelper.java
package com.lapetit;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCT = "product";
public static final String COLUMN_INGREDIENTS = "ingredients";
private SQLiteDatabase database;
private static final String DATABASE_NAME = "products.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_PRODUCTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_PRODUCT
+ " text not null, " + COLUMN_INGREDIENTS + " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
Cursor check = database.rawQuery("select * from products",null);
//First Time we open Database, add default Values
if ( check.getCount() < 1 )
{
database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(1,'Le Mieux Retinol Serum', 'Apples,Bananas,Carrots')");
database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(2,'Le Mieux Essence Toner', 'Apricots, Beets, Cats')");
database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(3,'Le Mieux Body Wash', 'Alcohol, Marijuana, Meth')");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
}
Products.java
package com.lapetit;
public class Products {
private long id;
private String product;
private String ingredient;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getIngredients() {
return product;
}
public void setIngredients(String ingredient) {
this.ingredient = ingredient;
}
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return product;
}
}
ProductsDataSource.java
package com.lapetit;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class ProductsDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PRODUCT,
MySQLiteHelper.COLUMN_INGREDIENTS};
public ProductsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public List<Products> getAllProducts() {
List<Products> products = new ArrayList<Products>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_PRODUCTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Products product = cursorToProduct(cursor);
products.add(product);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return products;
}
//Search queries
public List<Products> getSearchedProducts(String search) {
List<Products> products = new ArrayList<Products>();
String[] args = new String[1];
args[0] = "%"+search+"%";
Cursor cursor = database.rawQuery("SELECT product FROM products, _id WHERE ingredients like ?", args);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Products product = cursorToProduct(cursor);
products.add(product);
cursor.moveToNext();
}
cursor.close();
return products;
}
private Products cursorToProduct(Cursor cursor) {
Products product = new Products();
product.setId(cursor.getLong(0));
product.setProduct(cursor.getString(1));
return product;
}
}
WithActivity.java
package com.lapetit;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class WithActivity extends ListActivity {
private ProductsDataSource datasource;
private ArrayAdapter adapter;
List<Products> values = new ArrayList<Products>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.with);
EditText inputSearch = (EditText) findViewById(R.id.text);
datasource = new ProductsDataSource(this);
datasource.open();
ArrayAdapter<Products> adapter = new ArrayAdapter<Products>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
public void onClick(View view) {
ArrayAdapter<Products> adapter = (ArrayAdapter<Products>) getListAdapter();
Products product = null;
switch (view.getId()) {
case R.id.search:
EditText inputSearch = (EditText) findViewById(R.id.text);
String stringinput = (String)inputSearch.getText().toString();
List<Products> values = datasource.getSearchedProducts(stringinput);
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
with.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" >
<EditText
android:id="#+id/text"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="text" />
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:onClick="onClick"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="400dp" />
</LinearLayout>
Failed to read row 0, column 1 from a CursorWindow which has 3 rows, 1 columns.
I think your query needs to return more columns...
In getSearchedProducts() you select only the product column:
// Select a single column.
Cursor cursor = database.rawQuery("SELECT product FROM products WHERE ingredients like ?", args);
But in cursorToProduct() you read two columns (ID and Product):
product.setId(cursor.getLong(0));
product.setProduct(cursor.getString(1));
It looks like you need to add the Id to the query.
Cursor cursor = database.rawQuery("SELECT id, product FROM products WHERE ingredients like ?", args);
Related
Thanks for helping me fix my problem!
Issue
The issue is that the data never gets saved into the database, which it did before, but then i updated the database version and now it does not.
Is there an error thrown? Yes there is and its right down below.
E/SQLiteLog: (1) near "0": syntax error
E/SQLiteDatabase: Error inserting 0=20 id=csdfergeg userid=csdfergeg email=erregegergr
android.database.sqlite.SQLiteException: near "0": syntax error (code 1): , while compiling: INSERT INTO Info(0,id,userid,email) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1546)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1417)
at com.vikkivuk.mxelevator.Database.addUserInfo(Database.java:50)
at com.vikkivuk.mxelevator.finishScene$1.onClick(finishScene.java:61)
at android.view.View.performClick(View.java:6294)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
My code:
Database Class:
package com.vikkivuk.mxelevator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " TEXT," + KEY_EMAIL + " TEXT," + Integer.parseInt(KEY_CODE) + " 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 void addUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, info.UserId);
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo(){
List<UserInfo> results = new ArrayList<UserInfo>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[] {String.valueOf(info.ID)});
db.close();
}
}
UserInfo:
package com.vikkivuk.mxelevator;
public class UserInfo {
public String ID;
public String UserId;
public String Email;
public String CODE;
public UserInfo(String uid, String mail, String el_code){
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(String userId, String uid, String mail, String el_code){
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
UserInfoAdapter:
package com.vikkivuk.mxelevator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
public class UserInfoAdapter extends ArrayAdapter<UserInfo> {
public UserInfoAdapter(Context context, List<UserInfo> info) {
super(context, 0, info);
}
public View getView(int position, View convertView, ViewGroup parent){
UserInfo info = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.user_info_item_row, parent, false);
}
TextView uid = convertView.findViewById(R.id.textview_userid);
TextView email = convertView.findViewById(R.id.textview_email);
TextView textcode = convertView.findViewById(R.id.codetext);
uid.setText(info.UserId);
email.setText(info.Email);
textcode.setText(info.CODE);
return convertView;
}
}
Finish scene:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.Random;
public class finishScene extends AppCompatActivity {
EditText userId, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finish_scene);
userId = findViewById(R.id.userid);
email = findViewById(R.id.email);
CheckBox agreeCheck = findViewById(R.id.agreeCheck1);
Boolean checked = agreeCheck.isChecked();
Button submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userId.length() < 5) {
Toast.makeText(getApplicationContext(), "Your UID is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (email.length() < 6) {
Toast.makeText(getApplicationContext(), "Your EMAIL is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (!agreeCheck.isChecked()) {
Toast.makeText(getApplicationContext(), "Please check the agree box!", Toast.LENGTH_SHORT).show();
return;
} else {
Random rand = new Random();
int int_random1 = rand.nextInt(10000);
int int_random2 = rand.nextInt(10);
int int_random3 = rand.nextInt(10);
int int_random4 = rand.nextInt(15);
int int_random5 = rand.nextInt(25);
int random_code = int_random1 + int_random2 + int_random3 + int_random4 + int_random5;
Database db = new Database(finishScene.this);
UserInfo info = new UserInfo(userId.getText().toString(), email.getText().toString(), String.valueOf(random_code));
db.addUserInfo(info);
db.close();
userId.setText("");
email.setText("");
Toast.makeText(getApplicationContext(), "Data saved! Pending approval...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(userId.getContext(), Success.class);
startActivity(intent);
}
}
});
}
}
ShowData:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShowData extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
List<UserInfo> info = new Database(this).getUserInfo();
UserInfoAdapter adapter = new UserInfoAdapter(this, info);
ListView listView = findViewById(R.id.userInfoList);
listView.setAdapter(adapter);
Button goback = findViewById(R.id.goback1);
goback.setOnClickListener(v -> {
Intent intent = new Intent(goback.getContext(), MainActivity.class);
startActivity(intent);
});
}
}
That's all of my classes. Also, I would like to specify that I don't actually know what database versions are since I started with the android studio 3 days ago.
please try this I implemented some change on the UserInfo class
the Id must be an integer and you add a String
database.java
public class MyBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public MyBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " INTEGER," + KEY_EMAIL + " TEXT," + KEY_CODE + " 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 void addUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// contentValues.put(KEY_ID, info.UserId); i removed this
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo() {
List<UserInfo> results = new ArrayList<>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[]{String.valueOf(info.ID)});
db.close();
}
}
and UserInfo :
public class UserInfo {
public int ID;
public int UserId;
public String Email;
public int CODE;
public UserInfo(int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(int userId, int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
i hope that's help you
Hi to everyone I am new to android just a beginner. I am developing an app which shows a list of medicine with the brand name and generic name. I am using ListView for displaying data and this data is coming from SQLite database. What I want when a user enters a name of a medicine in a editText it should show the search result from the ListView like for example my List has a medicine name NICOX a brand name. And user wants to search this name and Enters N in the edit text then this name should be shown in the list view and all other names which start form the letter which the user enters in the edit text I added all my code here is my Main Activity code.
package com.example.clnicmangmentapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddNewProductEntry;
import com.example.clnicmangmentapp.data.AddNewProductDataBaseHelper;
public class MainActivity extends AppCompatActivity {
AddNewProductDataBaseHelper mDataBaseHelper;
SQLiteDatabase database;
Cursor cursor;
SearchView mSearchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSearchView = findViewById(R.id.search_view);
mDataBaseHelper = new AddNewProductDataBaseHelper(this);
database = mDataBaseHelper.getWritableDatabase();
cursor = database.rawQuery("SELECT * FROM " + AddNewProductEntry.TABLE_NAME, null);
ListView listView = findViewById(R.id.list_view);
DispalyDataAdapterView adapter = new DispalyDataAdapterView(this, cursor);
listView.setAdapter(adapter);
adapter.changeCursor(cursor);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
int brandNameCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_PRODUCT_NAME);
int genericNameCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_GENERIC_NAME);
int retailPriceCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_RETAIL_PRICE);
int packSizeCol = cursor.getColumnIndex(AddNewProductEntry.COLUMN_PACK_SIZE);
int oneUnitPriceCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_ONE_UNIT_PRICE);
String brandName = cursor.getString(brandNameCol);
String genericName = cursor.getString(genericNameCol);
Double retailPrice = cursor.getDouble(retailPriceCol);
int packSize = cursor.getInt(packSizeCol);
Double oneUnitPrice = cursor.getDouble(oneUnitPriceCol);
Intent intent = new Intent(MainActivity.this,
DisplayOneProductActivity.class);
intent.putExtra("name", brandName);
intent.putExtra("genericName", genericName);
intent.putExtra("retailPrice", retailPrice);
intent.putExtra("packSize", packSize);
intent.putExtra("oneUnitPrice", oneUnitPrice);
startActivity(intent);
//finish();
}
});
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_item:
// Toast.makeText(MainActivity.this, "Item is clicked",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, AddItemActivity.class);
startActivity(intent);
return true;
case R.id.view_cart_menu:
Intent cartIntent = new Intent(this, ViewCartActivity.class);
startActivity(cartIntent);
default:
return super.onOptionsItemSelected(item);
}
}
}
and here is my AddItemActivity which is adding a new item into a database
package com.example.clnicmangmentapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddNewProductEntry;
import com.example.clnicmangmentapp.data.AddNewProductDataBaseHelper;
import java.text.DecimalFormat;
public class AddItemActivity extends AppCompatActivity {
private static DecimalFormat df = new DecimalFormat("0.00");
AddNewProductDataBaseHelper mDataBaseHelper;
private Button mAddDataBtn;
private Button mCancleBtn;
private EditText mBrandName;
private EditText mGenericName;
private EditText mCompanyName;
private EditText mRetailPrice;
private EditText mPackSize;
private TextView mOneUnitPrice;
private Spinner typeSpinner;
private int mSpinnerType = AddNewProductEntry.CAP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
mDataBaseHelper = new AddNewProductDataBaseHelper(this);
mAddDataBtn = findViewById(R.id.add_data_btn);
mCancleBtn = findViewById(R.id.clear_data_btn);
mBrandName = findViewById(R.id.product_name);
mGenericName = findViewById(R.id.genric_name);
mCompanyName = findViewById(R.id.company_name);
mRetailPrice = findViewById(R.id.retail_price);
mPackSize = findViewById(R.id.pack_size);
typeSpinner = (Spinner) findViewById(R.id.medicine_type);
// for setting spinner to take the value drop down menu
setSpinner();
mAddDataBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
insertData();
clearInputs();
}
});
mCancleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddItemActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void setSpinner(){
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.medicine_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
typeSpinner.setAdapter(adapter);
typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String selectedItem = (String) parent.getItemAtPosition(position);
if(!TextUtils.isEmpty(selectedItem)){
if(selectedItem.equals(getString(R.string.cap))){
Toast.makeText(AddItemActivity.this, "Cap is clicked",
Toast.LENGTH_LONG).show();
mSpinnerType = AddNewProductEntry.CAP;
}else if(selectedItem.equals(getString(R.string.tab))){
Toast.makeText(AddItemActivity.this, "Tab is clicked",
Toast.LENGTH_LONG).show();
mSpinnerType = AddNewProductEntry.TAB;
}else if(selectedItem.equals(getString(R.string.syp))){
Toast.makeText(AddItemActivity.this, "Syp is clicked",
Toast.LENGTH_LONG).show();
mSpinnerType = AddNewProductEntry.SYP;
}else{
Toast.makeText(AddItemActivity.this, "Inj is clicked",
Toast.LENGTH_LONG).show();
mSpinnerType = AddNewProductEntry.INJ;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
// this method clear all edit text after inter data to database as add button is pressed
private void clearInputs(){
mBrandName.getText().clear();
mGenericName.getText().clear();
mCompanyName.getText().clear();
mRetailPrice.getText().clear();
mPackSize.getText().clear();
}
private void insertData(){
String brand_name = mBrandName.getText().toString().toUpperCase().trim();
String generic_name = mGenericName.getText().toString().toUpperCase().trim();
String company_name = mCompanyName.getText().toString().toUpperCase().trim();
String retail_price = mRetailPrice.getText().toString().trim();
Double retailPrice = Double.parseDouble(retail_price);
String pack_size = mPackSize.getText().toString().trim();
int packSize = Integer.parseInt(pack_size);
Double oneUnitPrice = retailPrice/packSize;
// in this line of code we limiting out put to decimal places like 33.33
String convertedPrice = df.format(oneUnitPrice);
SQLiteDatabase sqLiteDatabase = mDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AddNewProductEntry.COLUMN_PRODUCT_NAME, brand_name);
contentValues.put(AddNewProductEntry.COLUMN_GENERIC_NAME, generic_name);
contentValues.put(AddNewProductEntry.COLUMN_COMPANY_NAME, company_name);
contentValues.put(AddNewProductEntry.COLUMN_RETAIL_PRICE, retail_price);
contentValues.put(AddNewProductEntry.COLUMN_PACK_SIZE, packSize);
contentValues.put(AddNewProductEntry.COLUMN_TYPE_OF_PRODUCT, mSpinnerType);
contentValues.put(AddNewProductEntry.COLUMN_ONE_UNIT_PRICE, convertedPrice);
long newRowId = sqLiteDatabase.insert(AddNewProductEntry.TABLE_NAME,null,
contentValues);
if(newRowId == -1){
Toast.makeText(AddItemActivity.this,"Error Inserting Data",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(AddItemActivity.this,"Data is Inserted Successfully",
Toast.LENGTH_LONG).show();
}
}
}
here is my DisplayDataAdapterView
package com.example.clnicmangmentapp;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddNewProductEntry;
public class DispalyDataAdapterView extends CursorAdapter {
public DispalyDataAdapterView(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_view, parent,
false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView brandNameTextView = view.findViewById(R.id.brand_name_view);
TextView genericNameTextView = view.findViewById(R.id.generic_name_view);
int brandNameCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_PRODUCT_NAME);
int genericNameCol =
cursor.getColumnIndex(AddNewProductEntry.COLUMN_GENERIC_NAME);
String brandName = cursor.getString(brandNameCol);
String genericName = cursor.getString(genericNameCol);
brandNameTextView.setText(brandName);
genericNameTextView.setText(genericName);
}
}
this is my Add New Prodct Contract
package com.example.clnicmangmentapp.data;
import android.provider.BaseColumns;
public class AddNewProductContract {
private AddNewProductContract(){}
public static class AddNewProductEntry implements BaseColumns{
public static final String TABLE_NAME = "add_new_product";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_PRODUCT_NAME = "product_name";
public static final String COLUMN_GENERIC_NAME = "generic_name";
public static final String COLUMN_COMPANY_NAME = "company_name";
public static final String COLUMN_RETAIL_PRICE = "retail_price";
public static final String COLUMN_PACK_SIZE = "pack_size";
public static final String COLUMN_TYPE_OF_PRODUCT = "product_type";
public static final String COLUMN_ONE_UNIT_PRICE = "one_unit_price";
public static final int CAP = 100;
public static final int TAB = 101;
public static final int SYP = 102;
public static final int INJ = 103;
}
public static class AddItemToCart implements BaseColumns{
public static final String TABLE_CART = "add_to_cart";
public static final String _CART_ID = BaseColumns._ID;
public static final String COLUMN_CART_PRODUCT_NAME = "cart_product_name";
public static final String COLUMN_CART_QUANTITY = "cart_product_quantity";
public static final String COLUMN_CART_PRICE = "cart_product_price";
public static final String COLUMN_CART_TOTAL_PRICE = "cart_total_price";
}
}
and here is my database helper class
package com.example.clnicmangmentapp.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddNewProductEntry;
import com.example.clnicmangmentapp.data.AddNewProductContract.AddItemToCart;
import androidx.annotation.Nullable;
public class AddNewProductDataBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "products";
private static final int DATABASE_VERSION = 1;
public AddNewProductDataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_ENTITIES = "CREATE TABLE " + AddNewProductEntry.TABLE_NAME + "("
+ AddNewProductEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ AddNewProductEntry.COLUMN_PRODUCT_NAME + " TEXT, "
+ AddNewProductEntry.COLUMN_GENERIC_NAME + " TEXT, "
+ AddNewProductEntry.COLUMN_COMPANY_NAME + " TEXT, "
+ AddNewProductEntry.COLUMN_RETAIL_PRICE + " REAL, "
+ AddNewProductEntry.COLUMN_PACK_SIZE + " INTEGER, "
+ AddNewProductEntry.COLUMN_TYPE_OF_PRODUCT + " INTEGER, "
+ AddNewProductEntry.COLUMN_ONE_UNIT_PRICE + " REAL )" ;
String CREATE_CART_TABLE = "CREATE TABLE " + AddItemToCart.TABLE_CART + "("
+ AddItemToCart._CART_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ AddItemToCart.COLUMN_CART_PRODUCT_NAME + " TEXT, "
+ AddItemToCart.COLUMN_CART_QUANTITY + " INTEGER, "
+ AddItemToCart.COLUMN_CART_PRICE + " REAL, "
+ AddItemToCart.COLUMN_CART_TOTAL_PRICE + " REAL )";
db.execSQL(CREATE_TABLE_ENTITIES);
db.execSQL(CREATE_CART_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String DROP_TABLE_PRODUCTS = " DROP TABLE IF EXISTS " +
AddNewProductEntry.TABLE_NAME;
String DROP_TABLE_ADD_TO_CART = " DROP TABLE IF EXISTS " +
AddItemToCart.TABLE_CART;
db.execSQL(DROP_TABLE_PRODUCTS);
db.execSQL(DROP_TABLE_ADD_TO_CART);
onCreate(db);
}
}
here is my list view xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Search"
android:padding="8dp"
android:layout_marginBottom="4dp">
</EditText>
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
and here is my list item 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="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/brand_name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="#string/brand_name"
android:textSize="18sp"/>
<TextView
android:id="#+id/generic_name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Generic Name"
android:paddingLeft="8dp"/>
</LinearLayout>
please help to solve this issue
I try this code and it works now I am able to filter the list but when I click on filter result the app crashed and give me a error
android.database.StaleDataException: Attempting to access a closed
CursorWindow.Most probable cause: cursor is deactivated prior to
calling this method.
at
android.database.AbstractWindowedCursor.
checkPosition(AbstractWindowedCursor.java :141)
at
android.database.AbstractWindowedCursor.
getString(AbstractWindowedCursor.java:52)
at
com.example.clnicmangmentapp.MainActivity$3.
onItemClick(MainActivity.java:97)
here is code which I try
adapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
String search = constraint.toString();
String searchResult = (" SELECT * FROM " +
AddNewProductEntry.TABLE_NAME + " WHERE " +
AddNewProductEntry.COLUMN_PRODUCT_NAME + " LIKE '%" + search +
"%'");
return database.rawQuery(searchResult, null);
}
});
mSearchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
adapter.getFilter().filter(s);
// Don't forget to notify the adapter
adapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
here I work for another code this is working code
it can filter the data but data not shown only empty list but when I click on a item it shows me correct data
public void showSearch(String search){
String searchQuery = (" SELECT * FROM " +
AddNewProductEntry.TABLE_NAME + " WHERE " +
AddNewProductEntry.COLUMN_PRODUCT_NAME + " LIKE '%" + search +
"%'");
cursor = database.rawQuery(searchQuery, null);
SimpleCursorAdapter adapterSimple = new
SimpleCursorAdapter(MainActivity.this,
android.R.layout.simple_list_item_2, cursor,
new String[] {AddNewProductEntry.COLUMN_PRODUCT_NAME,
AddNewProductEntry.COLUMN_GENERIC_NAME},
new int[] {R.id.brand_name_view, R.id.generic_name_view},
0);
listView.setAdapter(adapterSimple);
adapterSimple.notifyDataSetChanged();
}
and I use this function in my mSearchEditText like this
mSearchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
String search = s.toString();
showSearch(search);
}
#Override
public void afterTextChanged(Editable s) {
}
});
this code is working and filtring the data as I type a word but it shows empty list and when I click on this list it show me the data of that list item.
As I am already displaying list of data using my DisplayDataAdpaterView so I user this method and excecated this method in my editText search's method
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String search = s.toString();
showSearch(search);
}
this method to search result from database and bind the views and show them as listview
public void showSearch(String search){
String searchQuery = (" SELECT * FROM " +
AddNewProductEntry.TABLE_NAME + " WHERE " +
AddNewProductEntry.COLUMN_PRODUCT_NAME + " LIKE '%" + search + "%'");
cursor = database.rawQuery(searchQuery, null);
// so this is the DisplayAdpater which already displaying data
// so we use this adapter to show search in a list view
adapter = new DispalyDataAdapterView(this,cursor);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
I feel like this is a really simple fix but I am new the android and sqlite in general. I have a array that takes data from a database and then shows them in a list. However every time I restart the app the list adds the items once again into the list. How can I make it not do this?
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.assignmenttracker.MySQLiteHelper;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
private ListView ListView;
private Button addbutton;
public final static String ID_EXTRA="com.example.assignmenttracker._ID";
public static ArrayList<String> ArrayofName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.addbutton = (Button)this.findViewById(R.id.button1);
this.addbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this, AddAssign.class);
startActivity(intent);
}
});
}
private void populateListView() {
MySQLiteHelper db = new MySQLiteHelper(this);
List<tasklist> contacts = db.getSometasklist();
for (tasklist cn : contacts) {
Log.d("Reading: ", "Reading all contacts..");
String log = "Id: "+cn.getID()+" ,Task: " + cn.getTask() + " ,Date: " + cn.getDate() + " ,Status: " + cn.getStatus();
Log.d("Name: ", log);
}
ListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
ListView.setAdapter(adapter);
ListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(MainActivity.this, ViewAssign.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);}
});
}
#Override
public void onResume() {
super.onResume();
populateListView();
}
}
here is the code of mysqlitehelper
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.content.Context;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Contacts Table Columns names
private static final String TABLE_CONTACTS = "tasklist1";
private static final String KEY_ID = "id";
private static final String KEY_TASK = "task";
private static final String KEY_DESC = "desc";
private static final String KEY_MOD = "module";
private static final String KEY_DATE = "date";
private static final String KEY_TYPE = "type";
private static final String KEY_STATUS = "status";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "tasklist1";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_TASKLIST_TABLE = "CREATE TABLE tasklist1 ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"task TEXT, "+
"desc TEXT, "+
"module TEXT, "+
"date TEXT, "+
"type TEXT, "+
"status INTEGER )";
db.execSQL(CREATE_TASKLIST_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older task list table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// create fresh task list table
this.onCreate(db);
}
public void insertTask(tasklist tasklist){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, tasklist.getTask());
values.put(KEY_DESC, tasklist.getDesc());
values.put(KEY_MOD, tasklist.getModule());
values.put(KEY_DATE, tasklist.getDate());
values.put(KEY_TYPE, tasklist.getType());
values.put(KEY_STATUS, tasklist.getStatus());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public List<tasklist> getAlltasklist(int passedid) {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS +
" where id = " + passedid;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDesc(cursor.getString(2));
contact.setModule(cursor.getString(3));
contact.setDate(cursor.getString(4));
contact.setType(cursor.getString(5));
contact.setStatus(cursor.getInt(6));
String name = cursor.getString(1);
String desc =cursor.getString(2);
String module =cursor.getString(3);
String date = cursor.getString(4);
String type = cursor.getString(5);
int status = cursor.getInt(6);
ViewAssign.task= name;
ViewAssign.desc=desc;
ViewAssign.module=module;
ViewAssign.date=date;
ViewAssign.type=type;
ViewAssign.status=status;
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public List<tasklist> getSometasklist() {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDate(cursor.getString(4));
String name = cursor.getString(1) +"\n"+ cursor.getString(4);
MainActivity.ArrayofName.add(name);
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public void deleteTask(long row) {
// Deletes a row given its rowId, but I want to be able to pass
// in the name of the KEY_NAME and have it delete that row.
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=" + row, null);
db.close();
}
}
I suspect the culprint is this:
public static ArrayList<String> ArrayofName = new ArrayList<String>();
It is a static variable, meaning that in some circumstances, it will STILL have the objects you added on app first run when you run it second time.
Possible solutions:
remove "static" keyword, or
clear ArrayOfName before populating it, eg. ArrayOfName.clear()
I know I am late but maybe it will help someone else.
You need to split ArrayList into two parts
Place the following code in MainActivity
public static ArrayList<String> ArrayofName;
And place the following in onCreate() OR onResume() method
ArrayofName = new ArrayList<String>();
I am developing an android application in when user enters in the app, the first activity asks his name to enter in textfield. By clicking on submit button, the name of the user stores in SQLite database and another activity opens and the name of the user will display in next activity. Now, I want something like that, if user closes the app and when he starts it again, then the name of the user should not be asked again and he should directly move to second activity with his name that he entered first time. This is my complete code below :
DatabaseHandler.java
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="Database1";// Database Name...
private static final String TABLE_NAME = "Name"; // Name of the Table...
private static final String KEY_ID = "id"; // Column1 of the table
private static final String KEY_NAME="UserName";// Column2 of the table
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "(" + KEY_ID
+ " integer primary key autoincrement, " + KEY_NAME
+ " text not null);";
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseHandler.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addName(Name name)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_NAME, name.getUsername());
db.insert(TABLE_NAME, null, values);
db.close();
}
public Name getName(int id)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query(TABLE_NAME, new String[]{ KEY_ID,KEY_NAME },KEY_ID +"=?",new String[] { String.valueOf(id) },null,null,null,null);
if(cursor!=null)
{
cursor.moveToFirst();
}
Name name = new Name(Integer.parseInt(cursor.getString(0)),cursor.getString(1));
return name;
}
public List<Name> getAllNames() {
List<Name> nameList = new ArrayList<Name>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Name name = new Name();
name.setId(Integer.parseInt(cursor.getString(0)));
name.setUsername(cursor.getString(1));
// Adding contact to list
nameList.add(name);
} while (cursor.moveToNext());
}
return nameList;
}
}
MainActivity.java
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;
public class MainActivity extends Activity
{
Button submit;
EditText et1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit=(Button)findViewById(R.id.button1);
et1=(EditText)findViewById(R.id.editText1);
final DatabaseHandler db = new DatabaseHandler(this);
submit.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v1)
{
if(v1==submit)
{
String name1=et1.getText().toString();
Log.d("Insert: ", "Inserting ..");
db.addName(new Name(et1.getText().toString()));
Log.d("Reading: ", "Reading all contacts..");
List<Name> names = db.getAllNames();
for (Name n : names) {
String log = "Id: "+n.getId()+" ,Name: " + n.getUsername();
Log.d("Name: ", log);
}
Intent i1=new Intent(getApplicationContext(),NextPage.class);
i1.putExtra("name",name1);
startActivity(i1);
}
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
return super.onOptionsItemSelected(item);
}
}
Main.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: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="com.example.database.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:ems="10"
android:hint="Please Enter Your Name"
android:inputType="textPersonName" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text=" Submit " />
</RelativeLayout>
I am not getting any idea about this how to do it.Please help me...
You could use Shared Preferences instead of a SQLte database. For just storing a name Shared Preferences are more than enough.
So when your application starts, you just check if the specific Shared Preferences are containing the users name and if not you ask the user about the name.
SharedPreferences settings = getSharedPreferences("PREFERENCES", MODE_PRIVATE);
if(settings.getString("USER_NAME", "").equals("")) {
//User has to enter the name
//Do the specific action
String user_name = ...
SharedPreferences.Editor editor = settings.edit();
editor.putString("USER_NAME", user_name);
editor.commit();
}
You will have to do a check to see if a name already exists in the database before you want to add. Change to:
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v1) {
if(v1==submit) {
if( db.db.getAllNames() != null ) {
// Go directly to intent
} else {
// Ask a name
}
} );
}
Attached above is a screenshot of the issue. Will not update with information of the database:
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/categoryChoose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:entries="#array/catergory_arrays"
android:gravity="right" />
<ListView
android:id="#+id/dbListView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_marginTop="10dip" >
</ListView>
<Button
android:id="#+id/scanCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dip"
android:text="#string/scan" />
<Button
android:id="#+id/editItemCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="10dp"
android:text="#string/editItem" />
</LinearLayout>
CurrentItems - Should be displaying current database rows
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class CurrentItems extends Activity {
ItemDatabase db;
Context context;
Button addButton, editButton;
ListView listView;
// the table that displays the data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_inventory);
db = new ItemDatabase(this);
// create references and listeners for the GUI interface
setupViews();
// make the buttons clicks perform actions
addButtonListeners();
displaySearch();
}
private void setupViews() {
// bring up current database items
listView = (ListView) findViewById(R.id.dbListView);
// THE BUTTONS
addButton = (Button) findViewById(R.id.scanCurrent);
editButton = (Button) findViewById(R.id.editItemCurrent);
}
private void addButtonListeners() {
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, AddItem.class));
}
});
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, EditItems.class));
}
});
}
private void displaySearch() {
// TODO Auto-generated method stub
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
final ArrayList<String> items = new ArrayList<String>();
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate:" + row.get(0).toString() + " Title:"
+ row.get(1).toString() + "\n" + "Quantity:"
+ Integer.parseInt(row.get(2).toString()) + "\n");
aa.notifyDataSetChanged();
}
listView.setAdapter(aa);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
ItemsDatabase
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public final class ItemDatabase {
// the Activity or Application that is creating an object from this class.
Context context;
// a reference to the database used by this application/object
private SQLiteDatabase db;
// These constants are specific to the database.
private final String DATABASE_NAME = "ItemDatabase.sqlite";
private final int DATABASE_VERSION = 3;
// These constants are specific to the database table.
private final String TABLE_NAME = "foodItems";
private final String COLUMN_NAME_ENTRY_ID = "entryid";
private final String COLUMN_NAME_BARCODE = "barcode";
private final String COLUMN_NAME_TITLE = "title";
private final String COLUMN_NAME_QUANTITY = "quantity";
private final String COLUMN_NAME_DATE = "date";
String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_NAME;
String SQL_CREATE_TABLE = "create table " + TABLE_NAME + " ("
+ COLUMN_NAME_ENTRY_ID
+ " integer primary key autoincrement not null," + COLUMN_NAME_DATE
+ " date," + COLUMN_NAME_BARCODE + " text," + COLUMN_NAME_TITLE
+ " text," + COLUMN_NAME_QUANTITY + " int" + ");";
public ItemDatabase(Context context) {
this.context = context;
// create or open the database
ItemDatabaseHelper helper = new ItemDatabaseHelper(context);
this.db = helper.getWritableDatabase();
}
public void addRow(String rowStringOne, String rowStringTwo,
String rowStringThree, int rowIntFour) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_QUANTITY, rowIntFour);
// ask the database object to insert the new data
try {
db.insert(TABLE_NAME, null, values);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo,
String rowStringThree, int rowIntFour) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_QUANTITY, rowIntFour);
// ask the database object to update the database row of given rowID
try {
db.update(TABLE_NAME, values, COLUMN_NAME_ENTRY_ID + "=" + rowID,
null);
} catch (Exception e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID) {
// ask the database manager to delete the row of given id
try {
db.delete(TABLE_NAME, COLUMN_NAME_ENTRY_ID + "=" + rowID, null);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays() {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY }, null, null,
null, null, COLUMN_NAME_TITLE + " DESC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
while (cursor.moveToNext()) {
// your content
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getColumnIndex(COLUMN_NAME_DATE));
dataList.add(cursor.getColumnIndex(COLUMN_NAME_TITLE));
dataList.add(cursor.getColumnIndex(COLUMN_NAME_QUANTITY));
dataArrays.add(dataList);
}
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public class ItemDatabaseHelper extends SQLiteOpenHelper {
public ItemDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// execute the query string to the database.
db.execSQL(SQL_CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade
// policy is to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
}
No errors are thrown in the logcat. Should display data in order of Date, Title and then Quantity.
All help will be appreciated.
cursor.getColumnIndex
returns the index of a column by name. So you have indexes as a result. You should do something like:
dataList.add(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));