<!-- this is my database code -->
package com.example.helper;
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.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper {
/* COLUMN NAMES : FOR BEER */
public static final String KEY_ROWID = "_id";
public static final String KEY_BRAND = "brand";
public static final String KEY_QUANTITY = "quantity";
public static final String KEY_PRICE = "price";
/* TAG : FOR BEER */
private static final String TAG = "BeersDbAdapter";
private DbHelp mDbHelper;
private SQLiteDatabase sqldatabase;
private static final String DATABASE_NAME = "Alcohols.db";
/* TABLE : FOR BEER */
private static final String SQLITE_TABLE_BEER = "Beer_Table";
private static final int DATABASE_VERSION = 45;
private final Context mCtx;
/* CREATING TABLE : FOR BEER */
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE_BEER + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_BRAND + "," +
KEY_QUANTITY + "," +
KEY_PRICE + "," +
" UNIQUE (" + KEY_BRAND +"));";
private static class DbHelp extends SQLiteOpenHelper {
DbHelp(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
/* CREATING DATABASE: FOR BEER */
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* UPGRADING DATABASE : FOR BEER */
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE_BEER);
onCreate(db);
}
}
public DatabaseHelper(Context ctx) {
this.mCtx = ctx;
}
public DatabaseHelper open() throws SQLException {
mDbHelper = new DbHelp(mCtx);
sqldatabase = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
/* FOR BEERS */
public long createBeers(String code, String name,
String region) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_BRAND, code);
initialValues.put(KEY_QUANTITY, name);
initialValues.put(KEY_PRICE, region);
return sqldatabase.insert(SQLITE_TABLE_BEER, null, initialValues);
}
public boolean deleteAllBeers() {
int doneDelete = 0;
doneDelete = sqldatabase.delete(SQLITE_TABLE_BEER, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchBeersByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = sqldatabase.query(SQLITE_TABLE_BEER, new String[] {KEY_ROWID,
KEY_BRAND, KEY_QUANTITY, KEY_PRICE},
null, null, null, null, null);
}
else {
mCursor = sqldatabase.query(true, SQLITE_TABLE_BEER, new String[] {KEY_ROWID,
KEY_BRAND, KEY_QUANTITY, KEY_PRICE},
KEY_BRAND + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllBeers() {
Cursor mCursor = sqldatabase.query(SQLITE_TABLE_BEER, new String[] {KEY_ROWID,
KEY_BRAND, KEY_QUANTITY, KEY_PRICE},
null, null, null, null, null);
return mCursor;
}
/*
public void insertSomeBeers() {
createBeers("Natural Ice ","5.9%","130 cals per 12 oz","$0.75");
createBeers("Budweiser Select ","4.3%","99 cals per 12 oz","$1.45");
createBeers("Molson Canadian ","5%","148 cals per 12 oz","$1.80");
createBeers("Becks Pilsner ","5%","138 cals per 12 oz","$1.67");
createBeers("Amstel Light ","3.5%","95 cals per 12 oz","$2.78");
createBeers("Bud Select 55 ","2.4%","55 cals per 12 oz","$3.18");
createBeers("O'Doul's ","0.4%","65 cals per 12 oz","$13.88");
}
*/
public Cursor getUserInfo() {
Cursor cursor = sqldatabase.query(SQLITE_TABLE_BEER, null, null, null, null, null,
null);
return cursor;
}
}
// THIS CLASS IS AN IMPORT EXPORT CLASS
//this is where i have written code to import my excel files into database
package com.example.cheers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.util.Log;
import com.example.helper.DatabaseHelper;
public class ImportExport {
DatabaseHelper dbHandler;
Context context;
protected static final File DATABASE_DIRECTORY = new File(
Environment.getExternalStorageDirectory(), "ImportExport");
protected static File IMPORT_ITEM_FILE = null;
/*
protected static final File IMPORT_ITEM_FILE = new File(DATABASE_DIRECTORY,
"rates.csv");
*/
boolean flag = false;
public ImportExport(Context context) {
this.context = context;
}
public void hello(){
Log.e("excel", "in exportDatabasecsv()");
}
public Boolean exportDataToCSV(String outFileName) {
Log.e("excel", "in exportDatabasecsv()");
Boolean returnCode = false;
String csvHeader = "";
String csvValues = "";
try {
dbHandler = new DatabaseHelper(context);
dbHandler.open();
if (!DATABASE_DIRECTORY.exists()) {
DATABASE_DIRECTORY.mkdirs();
}
Log.e("export fun:file name", outFileName);
File outFile = new File(DATABASE_DIRECTORY, outFileName);
FileWriter fileWriter = new FileWriter(outFile);
Log.e("after FileWriter :file name", outFile.toString());
BufferedWriter out = new BufferedWriter(fileWriter);
Cursor cursor = dbHandler.getUserInfo();
// Log.e("excel", "cursor col count" + cursor.getCount());
int col_count = cursor.getColumnCount();
Log.e("col count", ""+col_count);
csvHeader += "\"" + "Id" + "\",";
csvHeader += "\"" + "Brand" + "\",";
csvHeader += "\"" + "Abv" + "\",";
csvHeader += "\"" + "Cps" + "\",";
csvHeader += "\"" + "Price" + "\",";
csvHeader += "\n";
if (cursor != null) {
out.write(csvHeader);
while (!cursor.isAfterLast()) {
//csvValues = Long.toString(cursor.getLong(0)) + ",";
Log.e("In getUserInfo()", "_id:"+cursor.getString(0)+",brand:"+cursor.getString(1)+", abv:"+cursor.getString(2)+", cps:"+cursor.getString(3)+", price:"+cursor.getString(4));
csvValues = cursor.getString(0) + ","; //id
csvValues += cursor.getString(1) + ","; // name
csvValues += cursor.getString(2) + ","; // age
csvValues += cursor.getString(3) + ","; // age
csvValues += cursor.getString(4) + ",\n"; // age
out.write(csvValues);
cursor.moveToNext();
}
// Log.e("excel", "csvValues are:- " + csvValues);
}
out.close();
cursor.close();
returnCode = true;
} catch (Exception e) {
returnCode = false;
Log.e("Exception", e.getMessage());
}
dbHandler.close();
return returnCode;
}
public void test(){
Log.e("message","hi");
}
public boolean importDataFromCSV(boolean flag_is_header_old, String dName) {
int i = 0;
boolean flag_is_header = flag_is_header_old;
/* FOR DIFFERENT BRANDS OF DRINKS */
if(dName == "beer")
{
IMPORT_ITEM_FILE = new File(DATABASE_DIRECTORY,
"beer.csv");
}
File file = new File(IMPORT_ITEM_FILE.getPath());
if (file.exists()) {
}
BufferedReader bufRdr = null;
try {
bufRdr = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
try {
while ((line = bufRdr.readLine()) != null) {
String[] insertValues = line.split(",");
if (flag_is_header) {
dbHandler = new DatabaseHelper(context);
dbHandler.open();
//dbHandler.deleteAllBeers();
if(dName == "beer")
{
long row=dbHandler.createBeers(insertValues[1],
insertValues[2], insertValues[3]);
Log.e("no. of rows inserted", ""+row);
}
}else {
flag_is_header = true;
}
}
dbHandler.close();
bufRdr.close();
} catch (IOException e) {
e.printStackTrace();
}
return flag_is_header;
}
}
// THIS IS MY CODE FROM WHERE I AM CALLING THE IMPORTEXPORT CLASS
package com.example.cheers;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.helper.DatabaseHelper;
import com.example.model.SpinnerNavItem;
public class DrinksActivity extends Activity implements ActionBar.OnNavigationListener
{
// action bar
private ActionBar actionBar;
// Title navigation Spinner data
private ArrayList<SpinnerNavItem> navSpinner;
// Navigation adapter
private TitleNavigationAdapter adapter;
/* FOR EXCEL */
boolean flag_is_header_old=false;
boolean flag_is_header_new=false;
boolean if_new = false;
ImportExport importexport;
DatabaseHelper databaseConnector;
Context context;
String dName="";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drinks);
/* EXCEL */
initializeUI();
/* for navigation menu */
actionBar = getActionBar();
// Hide the action bar title
actionBar.setDisplayShowTitleEnabled(false);
// Back Button
getActionBar().setDisplayHomeAsUpEnabled(true);
// Enabling Spinner dropdown navigation
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Spinner title navigation data
navSpinner = new ArrayList<SpinnerNavItem>();
navSpinner.add(new SpinnerNavItem("Drinks", R.drawable.drinkicon));
navSpinner.add(new SpinnerNavItem("Home", R.drawable.home));
navSpinner.add(new SpinnerNavItem("Recipes", R.drawable.recipesicon));
navSpinner.add(new SpinnerNavItem("Remedy", R.drawable.remedyicon));
// title drop down adapter
adapter = new TitleNavigationAdapter(getApplicationContext(), navSpinner);
// assigning the spinner navigation
actionBar.setListNavigationCallbacks(adapter, this);
/* end of navigation menu */
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
try
{
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
if(position == 0)
{
if(if_new==false)
{
dName = "beer";
try
{
databaseConnector.deleteAllBeers();
flag_is_header_new = importexport.importDataFromCSV(flag_is_header_old,dName);
if(flag_is_header_new==true)
{
//Toast.makeText(context, "File imported successfully", 1).show();
Log.i("Drinks : ImportBeer", "File imported successfully");
callB();
}
if_new=false;
}catch (Exception e) {
//Toast.makeText(context, "Import Unsuccessful", 1).show();
Log.e("Drinks : ImportBeer", "Import Unsuccessful");
Log.d("Drinks : ImportBeer", e.getMessage());
}
}
else
{
callB();
}
flag_is_header_new = false;
dName = "";
}
}
});
}
catch(Exception e)
{
Log.e("Drinks : GridView", "Error with gridview onclick");
Log.d("Drinks : GridView", e.getMessage());
}
}
/* FOR EXCEL */
public void initializeUI()
{
context=this;
databaseConnector=new DatabaseHelper(context);
importexport=new ImportExport(context);
}
/* FOR EXCEL */
public void callB(){
try
{
Intent iB = new Intent(DrinksActivity.this, BeerActivity.class);
startActivity(iB);
}catch(Exception e)
{
Log.e("Drinks : callV()", "Error with callB() onclick");
Log.d("Drinks : callB()", e.getMessage());
}
}
}
/* OPTIONS MENU */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
/* OPTIONS MENU */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_about_us:
callAboutUs();
return true;
case R.id.action_contact_us:
// check for updates action
return true;
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void callAboutUs(){
Intent iA = new Intent(DrinksActivity.this,AboutUsActivity.class);
startActivity(iA);
}
/* OPTIONS MENU : LOCATION SERVICE */
private class MyAdapter extends BaseAdapter
{
private List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public MyAdapter(Context context)
{
inflater = LayoutInflater.from(context);
items.add(new Item("Beer", R.drawable.vishal2));
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i)
{
return items.get(i);
}
@Override
public long getItemId(int i)
{
return items.get(i).drawableId;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup)
{
View v = view;
ImageView picture;
TextView name;
if(v == null)
{
v = inflater.inflate(R.layout.activity_image_adapter, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private class Item
{
final String name;
final int drawableId;
Item(String name, int drawableId)
{
this.name = name;
this.drawableId = drawableId;
}
}
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
if(itemPosition == 0)
{
try
{
Intent i = new Intent(DrinksActivity.this, DrinksActivity.class);
}
catch(Exception e)
{
Log.e("Drinks : onNavigationItemSelected", "Error with onNavigationItemSelected onclick");
Log.d("Drinks : onNavigationItemSelected", e.getMessage());
}
}
return false;
}
}
// and this is the code from where i am calling the display method of databse
package com.example.cheers;
import com.example.helper.DatabaseHelper;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class WhsikeyRecipeList extends Activity {
public DatabaseHelper dbHelper;
public SimpleCursorAdapter dataAdapter;
String value2 = "Whiskey";
Cursor cursor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whsikey_recipe_list);
/*FOR TITLE*/
//Typeface font;
//TextView text;
//text = (TextView) findViewById(R.id.brand);
//font = Typeface.createFromAsset(getAssets(), "fonts/Outwrite.ttf");
//text.setTypeface(font);
dbHelper = new DatabaseHelper(this);
dbHelper.open();
//fillBeerList();
//Clean all data
//dbHelper.deleteAllBeers();
//Add some data
//dbHelper.insertSomeBeers();
//Generate ListView from SQLite Database
displayListView();
}
/* OPTIONS MENU */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.whsikey_recipe_list, menu);
return super.onCreateOptionsMenu(menu);
}
/* OPTIONS MENU */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_about_us:
callAboutUs();
return true;
case R.id.action_contact_us:
// check for updates action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void callAboutUs(){
Intent iA = new Intent(WhsikeyRecipeList.this,AboutUsActivity.class);
startActivity(iA);
}
public void displayListView() {
try
{
//cursor = dbHelper.getWRecipesInfo();
cursor = dbHelper.fetchAllWRecipes();
}
catch(Exception e)
{
Log.e("WhsikeyRecipeList : Cursor", "Error calling getWRecipesInfo()");
Log.d("WhsikeyRecipeList : Cursor:getWRecipesInfo()", e.getMessage());
}
// The desired columns to be bound
String[] columns = new String[] {
DatabaseHelper.WhiskyRecipes_NAME
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.brecipes_name
};
<!-- create the adapter using the cursor pointing to the desired data
as well as the layout information-->
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_database_helper,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("wrecipes_name"));
try
{
getWhiskeyDetails(countryCode);
}
catch(Exception e)
{
Log.e("WhsikeyRecipeList : setOnItemClickListener", "Error calling getWhiskeyDetails()");
Log.d("WhsikeyRecipeList : setOnItemClickListener: getWhiskeyDetails()", e.getMessage());
}
/*
finally
{
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
Log.e("countryCode", countryCode);
}
*/
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchWRecipesByName(constraint.toString());
}
});
}
public void getWhiskeyDetails(String countryCode){
String data = countryCode;
Log.d("displayListView:BeerRecipeList", countryCode);
try
{
Intent myIntent = new Intent(WhsikeyRecipeList.this,AlcoholListTitles.class);
myIntent.putExtra("whiskeyTitle", data);
myIntent.putExtra("recipeTitle", value2);
startActivity(myIntent);
}
catch(Exception e)
{
Log.e("WhsikeyRecipeList : getWhiskeyDetails()", "Error calling AlcoholListTitles");
Log.d("WhsikeyRecipeList : getWhiskeyDetails(): AlcoholListTitles class", e.getMessage());
}
}
}
//... when i am commenting out the import line and trying to load the data from the database //after i have first imported the data... d data is not getting displayed
// y确实发生了这种情况..具体原因......请帮我看看 //我认为某个地方数据库正在更新,因此我之前从excel加载到表中的数据i被删除了 //请帮我弄清楚探索