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
}
} );
}
Related
I have added layout and classes below. The problem I am having is that although I have specified it in the layout, I cannot see the ImageView and TextViews other than checkbox. Layout shows only CheckBox, does not show the ImageView, the TextView and second TextView!
Project page CheckBox clicked:
Project page on emulator:
Project page in AndroidStudio:
Drink Activity Layout is
XML:
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
tools:context="com.hfad.starbuzz.DrinkActivity" >
<ImageView
android:id="#+id/photo"
android:layout_width="190dp"
android:layout_height="190dp"/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<CheckBox android:id="#+id/favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/favorite"
android:onClick="onFavoriteClicked" />
</LinearLayout>
Drink Activity:
package com.hfad.starbuzz;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class DrinkActivity extends Activity {
public static final String EXTRA_DRINKID = "drinkId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
//Getting a drink from an intent
int drinkId = (Integer) Objects.requireNonNull(getIntent().getExtras()).getInt(EXTRA_DRINKID);
//Creating a cursor
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
try {
SQLiteDatabase db = starbuzzDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query("DRINK",
new String[]{"NAME","DESCRIPTION","IMAGE_RESOURCE_ID","FAVORITE"},
"_id = ?",
new String[]{Integer.toString(drinkId)},null,null,null);
//Move to the first entry in the cursor
if (cursor.moveToFirst()) {
//Get the drink details from the cursor
String nameText = cursor.getString(0);
String descriptionText = cursor.getString(1);
int photoId = cursor.getInt(2);
boolean isFavorite = (cursor.getInt(3) == 1);
//Filling in the name of the drink
TextView name = (TextView) findViewById(R.id.name);
name.setText(nameText);
//Filling in the description of the drink
TextView description = (TextView) findViewById(R.id.description);
description.setText(descriptionText);
//Filling the drink image
ImageView photo = (ImageView) findViewById(R.id.photo);
photo.setImageResource(photoId);
photo.setContentDescription(nameText);
//Filling the Flag for Your Favorite Drink
CheckBox favorite = (CheckBox)findViewById(R.id.favorite);
favorite.setChecked(isFavorite);
}
cursor.close();
db.close();
} catch (SQLiteException e) {
Toast toast = Toast.makeText(this,
" unavailable",
Toast.LENGTH_SHORT);
toast.show();
}
}
//Database refresh on click of a checkbox
public void onFavoriteClicked(View view){
int drinkId = (Integer) Objects.requireNonNull(getIntent().getExtras()).getInt(EXTRA_DRINKID);
//Getting the value of a checkbox
CheckBox favorite = (CheckBox) findViewById(R.id.favorite);
ContentValues drinkValues = new ContentValues();
drinkValues.put("FAVORITE", favorite.isChecked());
//Retrieving a database link and updating the FAVORITE column
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
try {
SQLiteDatabase db = starbuzzDatabaseHelper.getWritableDatabase();
db.update("DRINK",
drinkValues,
"_id = ?",
new String[] {Integer.toString(drinkId)});
db.close();
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
}
}
StarbuzzDatabaseHelper:
package com.hfad.starbuzz;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StarbuzzDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "starbuzz"; // Database name
//Increasing the version number means that the SQLite Assistant will know to update the database.
private static final int DB_VERSION = 12; // Database version and version number.
StarbuzzDatabaseHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
//The onCreate () method is called when the database is first created;
//We use it to create a table and insert data
public void onCreate(SQLiteDatabase db){
updateMyDatabase(db, 0, DB_VERSION);
}
//The updateMyDatabase () method is called from onUpgrade () with parameters passed.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
updateMyDatabase(db, oldVersion, newVersion);
}
//It is necessary to insert the data of several drinks,
//so we created a separate method for inserting.
private static void insertDrink(SQLiteDatabase db, String name,
String description, int resourceId) {
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name);
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceId);
db.insert("DRINK", null, drinkValues);
}
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 1) {
db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte);
insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam",
R.drawable.cappuccino);
insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter);
}
//This code is executed if the user already has version 1 of the database installed
if (oldVersion >= 2) {
}
//Code for adding a new column
}
}
Is your query returning any data? You might want to check the output of cursor.getCount().
Also if you go into Developer Options of your device you can see an option called "Show Layout Bounds". It will show you where your view elements are on the screen.
I finally found a solution, in public class StarbuzzDatabaseHelper
''''
private static final int DB_VERSION = 12;
''''
change to: private static final int DB_VERSION = 2;
''''
if (oldVersion >= 2) {
}
''''
change to: if (oldVersion < 2) {
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC;");
}
''''
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);
Im making an app which stores data in an SQLite database. I want to be able to add, edit and delete data from this database. I can app to it no problem. I am currently working on trying to delete from the database but I keep getting the same error.
(1) no such column: KEY_PUBNAME
Here is my Java file:
package com.example.beer_budget3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
//Need to update delete layout after deleting row
public class Delete extends Activity
{
//Creating an object name for my database
DatabaseSetup2 db = new DatabaseSetup2(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the delete XML file
setContentView(R.layout.delete);//Put one of these in each class
//Delete button that has been created in the delete XML file
Button delete = (Button)findViewById(R.id.deletepub);
delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//This page links back to the MainMenu page
Intent i = new Intent(Delete.this, MainMenu.class);
//Calling the deleting function
deleting(v);
//Activating the intent
startActivity(i);
}
});
}
public void deleting(View v)
{
db.open();
//Save user input into rowId
EditText pnametxt = (EditText)findViewById(R.id.delete1);
//Open the database
String pname2 = pnametxt.getText().toString();
db.deletePub(pname2);
db.close();
}
}
Here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
android:background="#color/background"
tools:context="com.example.beer_budget3.delete" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginBottom="20dp"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details"
android:layout_marginLeft="50dp"
android:layout_marginBottom="30dp"
android:textSize="25sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub"
android:textSize="20sp"/>
<EditText
android:id="#+id/delete1"
android:inputType="text"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/deletepub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="130dp"
android:onClick="delete"
android:text="#string/delete" />
</LinearLayout>
And here is my database adapter:
package com.example.beer_budget3;
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;
import android.widget.EditText;
public class DatabaseSetup2
{
// These are the names of the columns the table will contain
public static final String KEY_ROWID = "_id";
public static final String KEY_PUBNAME = "Pub_Name";
public static final String KEY_LOCATION = "Location";
public static final String KEY_PRICE = "Price";
private static final String DATABASE_NAME = "CillinsAssignment";
private static final String DATABASE_TABLE = "Beer_Budget";
private static final int DATABASE_VERSION = 1;
// This is the string containing the SQL database create statement
private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE +
"( " +KEY_ROWID + " integer primary key autoincrement, "+KEY_PUBNAME +" text not
null, "+KEY_LOCATION+" text not null, "+KEY_PRICE+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;
// utility class that makes it easy to create and maintain an SQLLite database
private SQLiteDatabase db;//Class containing methods to manage a local SQLLite Database file
// constructor for your class
public DatabaseSetup2(Context ctx)
{
// Context is a way that Android transfers info about Activities and apps.
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
// This is the helper class that will create the dB if it doesn’t exist and
//upgrades it if the structure has changed. It needs a constructor, an
//onCreate() method and an onUpgrade() method
private static class DatabaseHelper extends SQLiteOpenHelper
{
// constructor for your dB helper class. This code is standard. You’ve set
//up the parameter values for the constructor already…database name,etc
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// The “Database_create” string below needs to contain the SQL
//statement needed to create the dB
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// If you want to change the structure of your database, e.g.
// Add a new column to a table, the code will go head..
//This method only triggers if the database version number has
//increased
Log.w("test", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Beer_Budget");
onCreate(db);
}
}// end of the help class
// from here on, include whatever methods will be used to access or change data
//in the database
//---opens the database--- any activity that uses the dB will need to do this
public DatabaseSetup2 open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- any activity that uses the dB will need to do this
public void close()
{
DBHelper.close();
}
//---insert a pub into the database---
public long insertPub(String Pub_Name, String Location, String Price)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PUBNAME, Pub_Name);
initialValues.put(KEY_LOCATION, Location);
initialValues.put(KEY_PRICE, Price);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
//---retrieves all the rows---
public Cursor getAllPubs()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE},
null,
null,
null,
null,
null);
}
//---retrieves a particular row---
public Cursor getPub(int _id) throws SQLException
{
Cursor mCursor = db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE
},
KEY_ROWID + "=" + _id,
null,
null,
null,
null
);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
KEY_PUBNAME is clearly declared in the database adapter.
Any help would be great.
If you see your DatabaseHelper, you've defined following:
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
The keyname you've mentioned is KEY_PUBNAME. However where you've created the table, the keyname you've defined is Pub_Name. Over here:
public static final String KEY_PUBNAME = "Pub_Name";
That's why its not found. KEY_PUBNAME is the variable you've declared and not the name of the column. You may want to try to change it in db.delete statement.
I would like my android app to display the contents of a text file onto a virtual table when the user clicks the "List All" button. I am using an example from the developer.android website on creating a virtual table. The programme is unable to run at the moment. Below is the code I am working with and a sample of the text file.Kindly let me know where I may have gone wrong. Many thanks.
CEMMainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
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.widget.SimpleCursorAdapter;
import android.os.Build;
import android.provider.ContactsContract;
public class CEMMainActivity extends ActionBarActivity {
protected static final String FTS_TABLE_CREATE = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cemmain);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
}
.add(R.id.container, new PlaceholderFragment()).commit();
}
//Action once Find button is clicked
Button findequip = (Button)findViewById(R.id.findequip);
findequip.setOnClickListener(new OnClickListener() {
public void onClick(View f) {
public void onCreate(SQLiteDatabase list) {
SQLiteDatabase mDatabase = list;
mDatabase.execSQL(FTS_TABLE_CREATE);
loadEquipmentList();
}
}
});
fragment_cemmain.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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="clinical.equipment.monitor.CEMMainActivity$PlaceholderFragment" >
.......
<Button
android:id="#+id/listallequip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/cleartext"
android:layout_toRightOf="#+id/equipid"
android:onClick="listallequip"
android:text="#string/listallequip" />
</RelativeLayout>
DatabaseOpenHelper.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
public class DatabaseOpenHelper {
private static final String TAG = "ListAllEquipment";
//The columns to be included in table
public static final String COL_TYPE = "EQUIPMENT TYPE";
public static final String COL_ID = "ID";
public static final String COL_LOCATION = "LOCATION";
public static final String COL_STATUS = "STATUS";
public static final String COL_TIME = "TIME";
private static final String DATABASE_NAME = "EQUIPMENT LIST";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
public DatabaseOpenHelper(Context context) {
// TODO Auto-generated constructor stub
}
public void Listalldatabase (Context context) {
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +
COL_TYPE + ", " +
COL_ID + ", " + COL_LOCATION + ", " + COL_STATUS +", " + COL_TIME + ")";
DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelperContext = context;
}
// populate the virtual table
private void loadEquipmentList() {
new Thread(new Runnable() {
public void run() {
try {
loadType();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadType() throws IOException {
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.info_sample);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 5) continue;
long list = addItem(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim(), strings[4].trim());
if (list < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
public long addItem (String type; String id; String location; String status; String time) {
ContentValues initialValues = new ContentValues();
initialValues.put(COL_TYPE, type);
initialValues.put(COL_ID, id);
initialValues.put(COL_LOCATION, location);
initialValues.put(COL_STATUS, status);
initialValues.put(COL_TIME, time);
return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
}
}
#Override
public void onUpgrade(SQLiteDatabase list, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
list.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(list);
}
}
}
info_sample.txt
Equipment Type Equipment ID Location Status Time
Infusion Pump 1234 2 On 12:00
Hoist 3645 1 Off 13:00
Bed 2563 3 Occupied 14:00
Change this..
setContentView(R.layout.activity_cemmain);
to
setContentView(R.layout.fragment_cemmain);
because Button is in fragment_cemmain.xml so setContentView should refer fragment_cemmain.xml
and remove
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
Im creating an app where users can enter the movies they own, to show in a listview, and for random picking a movie from that list.
Now what my problem is, that when clicking on an item in the listview a new activity opens op where the item clicked is the title in a textview. So far i can get the movie from the list who is number 1 to show, but that shows it's title no matter which list item I click, how can i get the specific name depending on what item is clicked?? Thanks in advance.
My Database class:
package com.example;
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 class MovieDatabaseHelper {
private static final String TAG = MovieDatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "mymoviedatabase.db";
// table configuration
private static final String TABLE_NAME = "movie_table"; // Table name
private static final String MOVIE_TABLE_COLUMN_ID = "_id"; // a column named "_id" is required for cursor
private static final String MOVIE_TABLE_COLUMN_TITLE = "movie_title";
private static final String MOVIE_TABLE_COLUMN_YEAR = "production_year";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with MovieDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public MovieDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aMovieTitle, String aMovieYear) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(MOVIE_TABLE_COLUMN_TITLE, aMovieTitle);
contentValues.put(MOVIE_TABLE_COLUMN_YEAR, aMovieYear);
database.insert(TABLE_NAME, null, contentValues);
}
//Retrieves all the records
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME + " ORDER BY " + MOVIE_TABLE_COLUMN_TITLE + " COLLATE NOCASE";
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// Retrieves specific record
public String getMovieTitle()
{
Cursor c =
database.query(TABLE_NAME,
new String[] { MOVIE_TABLE_COLUMN_TITLE }, null, null, null, null, null);
if (c.moveToFirst())
return c.getString(c.getColumnIndex(MOVIE_TABLE_COLUMN_TITLE ));
else
return "Nothing";
}
// Retrieves a random entry from the Database
public String getRandomMovie()
{
Cursor c = database.query(TABLE_NAME + " ORDER BY RANDOM() LIMIT 1",
new String[] { MOVIE_TABLE_COLUMN_TITLE }, null, null, null, null, null);
if(c.moveToFirst())
return c.getString(c.getColumnIndex(MOVIE_TABLE_COLUMN_TITLE ));
else
return "nothing";
}
//Check if record exist
//---deletes a particular record---
public void delete(int _id)
{
database.delete(TABLE_NAME, MOVIE_TABLE_COLUMN_ID+"="+_id, null);
}
//---updates a record---
public boolean updateRecord(long _id, String movie_title)
{
ContentValues args = new ContentValues();
args.put(MOVIE_TABLE_COLUMN_TITLE, movie_title);
return database.update(TABLE_NAME, args, MOVIE_TABLE_COLUMN_ID + "=" + _id, null) > 0;
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + MOVIE_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
MOVIE_TABLE_COLUMN_TITLE + " TEXT, " + MOVIE_TABLE_COLUMN_YEAR + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}
My listview class:
package com.example;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
//import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
private MovieDatabaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
MediaPlayer mp;
private static final String TAG = MyActivity.class.getSimpleName();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dblist);
databaseHelper = new MovieDatabaseHelper(this);
final MediaPlayer mp = MediaPlayer.create(MyActivity.this, R.raw.cartoon015);
listView = (ListView) findViewById(R.id.list_data);
ImageButton okay = (ImageButton) findViewById(R.id.okay);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {
Intent i = new Intent(MyActivity.this,IMDb.class);
startActivity(i);
Log.d(TAG, "clicked on item: " + position);
}
}
);
okay.setOnClickListener
(new View.OnClickListener()
{
public void onClick(View v)
{
mp.start();
mp.setVolume((float) 0.3, (float) 0.3);
Intent intent = new Intent(MyActivity.this,MovieActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
);
// Database query can be a time consuming task ..
// so its safe to call database query in another thread
// Handler, will handle this stuff for you <img src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g" alt=":)" class="wp-smiley">
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
}
public void onClickEnterData(View btnAdd) {
final MediaPlayer mp = MediaPlayer.create(MyActivity.this, R.raw.cartoon015);
mp.start();
mp.setVolume((float) 0.1, (float) 0.1);
startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
databaseHelper.insertData(data.getExtras().getString("tag_movie_title"), data.getExtras().getString("tag_movie_year"));
customAdapter.changeCursor(databaseHelper.getAllData());
}
}
}
My movie detail class:
package com.example;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class IMDb extends Activity {
TextView Movietitle;
private MovieDatabaseHelper databaseHelper;
MediaPlayer mp;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.imdb);
Movietitle = (TextView) findViewById(R.id.movietitle);
databaseHelper = new MovieDatabaseHelper(this);
Button delete = (Button) findViewById(R.id.delete);
Movietitle.setText( databaseHelper.getMovieTitle());
}
}
Well, there is lot of code you are asking for. But I can tell you the steps
Create a Model Class for your movie,, where you can hold the db records
Create list of Model Class and then when you click the item, you get the position of record in list.
Your movie Model class must have getter and setter functions to retrieve record details.