I want to make an quote app which display the quote, the author, and a fav button.
I have a custom ListView which has 2 textViews, and 1 Toggle Button
I'm using SQLite with pre-populated data (So i already have all of the data)
I can populate my 2 textViews with my quote (from quote table) and author (from author table) using SimpleCursorAdapter
The Problem is, i have 1 ToggleButton which has:
Grey Heart image when its not selected (value 0)
Red Heart image when its selected (value 1)
What i want is
When the user click on the grey heart image (fav button), the image change to the red heart image and also updates the fav table in SQLite from 0 to 1.
When the user click on the red heart image (fav button), the image change to the grey heart image and also updates the fav table in SQLite from 1 to 0.
And when the user exit, and goes to my application again. i want the quotes that the user has already favorited before (value 1) still have red heart image.
Here is the code:
DatabaseOpenHelper.java
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";
public static final String COLUMN_GENRE = "genre";
private SQLiteDatabase database;
private final Context context;
// database path
private static String DATABASE_PATH;
/** constructor (Menambil PATH ke file database) */
public DatabaseOpenHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.context = ctx;
DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
+ "/databases/";
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void create() throws IOException {
boolean check = checkDataBase();
SQLiteDatabase db_Read = null;
// Creates empty database default system path
db_Read = this.getWritableDatabase();
db_Read.close();
try {
if (!check) {
copyDataBase();
}
} catch (IOException e) {
throw new Error("Error copying database");
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/** Start DB from here */
/** open the database */
public void open() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
database = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/** close the database */
#Override
public synchronized void close() {
if (database != null)
database.close();
super.close();
}
// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_QUOTES, quotesText );
initialValues.put(COLUMN_AUTHOR, author);
initialValues.put(COLUMN_FAV, fav);
return database.insert(TABLE_NAME, null, initialValues);
}
// updates a user
public boolean updateUser(long rowId, String fav) {
ContentValues args = new ContentValues();
args.put(COLUMN_FAV, fav);
return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
COLUMN_ID + " = " + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// delete a particular user
public boolean deleteContact(long rowId) {
return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves all users
public Cursor getAllUsers() {
return database.query(TABLE_NAME, new String[] { COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
null, null, null);
}
public Cursor getCertain(String valueGenre) {
String WHERE = "genre = ?";
String[] VALUE = new String[] {valueGenre};
return database.query(TABLE_NAME, new String[]{COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE,
null, null, null);
}
quotes_listview (Custom ListView)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linearLayout">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/txtQuote"
style="#style/QuotesFont"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_rowWeight="1"
android:layout_weight="1"
android:layout_margin="15dp" />
<ToggleButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/heartImage"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="30dp"
android:background="#drawable/fav"
android:textOff=""
android:textOn=""
android:layout_rowWeight="1"
android:layout_weight="3"
android:descendantFocusability="blocksDescendants"
android:layout_marginLeft="30dp"
android:layout_marginRight="15dp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/txtAuthor"
style="#style/AuthorFont"
android:layout_below="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="15dp"
android:layout_marginBottom="5dp" />
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="New Text"-->
<!--android:id="#+id/text2"-->
<!--android:layout_below="#+id/text1"-->
<!--android:layout_alignParentRight="true"-->
<!--android:layout_alignParentEnd="true"-->
<!--style="#style/AuthorFont"-->
<!--android:layout_marginBottom="10dp"-->
<!--android:layout_rowWeight="1"-->
<!--android:layout_weight="1" />-->
QuotesActivity.java
public class QuotesActivity extends AppCompatActivity {
ListView quotesList;
DatabaseOpenHelper myDbHelper;
ArrayList<ListOfQuotes> arrQuotes;
QuotesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
myDbHelper = new DatabaseOpenHelper(this);
try {
// check if database exists in app path, if not copy it from assets
myDbHelper.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
// open the database
myDbHelper.open();
myDbHelper.getWritableDatabase();
} catch (SQLException sqle) {
throw sqle;
}
quotesList = (ListView) findViewById(R.id.quotesList);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.genre_array, R.layout.spinner_item);
// Specify the layout to use when the list of choices appears
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//ALL
if (id == 0) {
populateListView();
}
//Entrepreneur
else if (id == 1) {
populateListViewEntrepreneur();
}
//Love
else if (id == 2) {
populateListViewLove();
}
//Work
else if (id == 3) {
populateListViewWork();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Call Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
//Custom Image Back Button
toolbar.setNavigationIcon(R.drawable.back_button);
setSupportActionBar(toolbar);
//To make the title from Android Manifest appear, comment the code below
getSupportActionBar().setDisplayShowTitleEnabled(false);
//Make the app only portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void populateListView() {
Cursor cursor = myDbHelper.getAllUsers();
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewEntrepreneur() {
String testing = "Entrepreneur";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewLove() {
String testing = "Love";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewWork() {
String testing = "Work";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
Related
I have a problem, namely, I have an application that displays in the RecyclerView 2 types of salads and after pressing, one of them should show a view showing their exact details with the option of whether or not we like it. These data are obviously retrieved from the database. And everything works until we just go to a detailed view - when we click on the picture of Greek salad we get a blank view, but what is interesting when we click on the chicken salad we get just a view of Greek salad? So where does the view of the chicken salad? And why the views turned into places. I attach the code at the bottom with the pictures so that you can understand exactly what the problem is.
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "app";
private static final int DB_VERSION = 1;
public MiodzioDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE SALAD (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER, "
+ "FAVORITE INTEGER);");
insertSalatki(db, "Greek salad", R.drawable.salad_greek, 0);
insertSalatki(db, "Chicken salad", R.drawable.salad_chicken, 0);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private static void insertSalatki(SQLiteDatabase db, String name, int resourceId, int favorite){
ContentValues saladValues = new ContentValues();
salatkiValues.put("NAME", name);
salatkiValues.put("IMAGE_RESOURCE_ID", resourceId);
salatkiValues.put("Favorite", favorite);
db.insert("SALAD", null, salatkiValues);
}
}
Salad
public class Salad {
private String name;
private int imageResourceId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImageResourceId() {
return imageResourceId;
}
public void setImageResourceId(int imageResourceId) {
this.imageResourceId = imageResourceId;
}
}
SaladDetailActivity
public class SaladDetailActivity extends AppCompatActivity {
public static final String EXTRA_SALAD = "salad";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_salatki_detail);
int salads = (Integer) getIntent().getExtras().get(EXTRA_SALAD);
try {
SQLiteOpenHelper miodzioDatabaseHelper = new MiodzioDatabaseHelper(this);
SQLiteDatabase db = miodzioDatabaseHelper.getWritableDatabase();
Cursor cursor = db.query("SALATKI",
new String[]{"NAME", "IMAGE_RESOURCE_ID", "FAVORITE"},
"_id = ?",
new String[]{Integer.toString(salads)},
null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
do {
String nameText = cursor.getString(0);
int photoId = cursor.getInt(1);
boolean isFavorite = (cursor.getInt(2) == 1);
TextView name = (TextView) findViewById(R.id.salad_text);
name.setText(nameText);
ImageView photo = (ImageView) findViewById(R.id.salad_image);
photo.setImageResource(photoId);
photo.setContentDescription(nameText);
CheckBox favorite = (CheckBox) findViewById(R.id.favorite);
favorite.setChecked(isFavorite);
}while (cursor.moveToNext());
}
}
cursor.close();
db.close();
}catch (SQLiteException e){
Toast.makeText(this, "Database does not work!", Toast.LENGTH_SHORT).show();
}
Toolbar myChildToolbar = (Toolbar) findViewById(R.id.my_child_toolbar_salad_detail);
setSupportActionBar(myChildToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create_order:
Intent intent = new Intent(this, AddActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onFavoriteClicked(View view) {
int salads = (Integer) getIntent().getExtras().get(EXTRA_SALAD);
CheckBox favorite = (CheckBox) findViewById(R.id.favorite);
ContentValues saladValues = new ContentValues();
saladValues.put("FAVORITE", favorite.isChecked());
SQLiteOpenHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.update("SALAD", saladValues,
"_id = ?", new String[]{Integer.toString(salads)});
db.close();
}
}
SaladMaterialFragment
public class SaladMaterialFragment extends Fragment {
private DatabaseHelper dataBaseHelper;
private Cursor cursor;
private ArrayList<Salad> arrayList = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView saladRecyler = (RecyclerView) inflater.inflate(R.layout.fragment_salad_material, container, false);
try{
SQLiteOpenHelper databaseHelper = new databaseHelper(inflater.getContext());
SQLiteDatabase db = databaseHelper.getReadableDatabase();
cursor = db.query("SALAD",
new String[] {"NAME", "IMAGE_RESOURCE_ID"},
null, null, null, null, null);
if(cursor != null){
if(cursor.moveToFirst()){
do{
Salad salads = new Salad();
salad.setName(cursor.getString(0));
salad.setImageResourceId(cursor.getInt(1));
arrayList.add(salad);
}while (cursor.moveToNext());
}
}
}catch (SQLiteException e){
Toast.makeText(inflater.getContext(), "Database does not work!", Toast.LENGTH_SHORT).show();
}
CaptionedImagesAdapter adapter = new CaptionedImagesAdapter(getActivity(), arrayList);
saladRecyler.setAdapter(adapter);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
saladRecyler.setLayoutManager(gridLayoutManager);
adapter.setListener(new CaptionedImagesAdapter.Listener() {
#Override
public void onClick(int position) {
Intent intent = new Intent(getActivity(), SaladDetailActivity.class);
intent.putExtra(SaladDetailActivity.EXTRA_SALAD, position);
getActivity().startActivity(intent);
}
});
return salatkaRecyler;
}
}
SaladDetailLayout
<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="com.hfad.SaladDetailActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_child_toolbar_salad_detail"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#android:color/holo_green_light"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<TextView
android:id="#+id/salatki_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<ImageView
android:id="#+id/salad_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<CheckBox
android:id="#+id/favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/favorite"
android:onClick="onFavoriteClicked"/>
So when I click on Salad greek, I get an empty view only with the option of whether it is a favorite. And when I hit the chicken salad I get a view of the Greek Salad. I have no idea what's going on?
Problem is in the onClick method in SaladMaterialFragment class.
You are passing the position of the item, and in ArrayList indexing is starting with 0.
But in Database insertion, _id INTEGER PRIMARY KEY AUTOINCREMENT, Database indexing will start with 1.
So you need to change onClick method with below.
adapter.setListener(new CaptionedImagesAdapter.Listener() {
#Override
public void onClick(int position) {
Intent intent = new Intent(getActivity(), SaladDetailActivity.class);
intent.putExtra(SaladDetailActivity.EXTRA_SALAD, position+1);
getActivity().startActivity(intent);
}
});
Just change position with position+1.
Also you are inserting the int value of your drawable resource which is not a good idea. This value is not necessarily constant throughout the life of your app -- a later version may issue a new value to this resource.
So please do not do this.
insertSalatki(db, "Greek salad", R.drawable.salad_greek, 0);
Instead map the drawable to an independent yet constant reference. Some thing like:
insertSalatki(db, "Greek salad", idSaladGreek, 0);
So, since you have potentially many rows in your database with the same salad type (eg. Greek Salad) with potentially many different resource ids, when you query your database for a salad type yon might be getting the wrong resource id. This might be causing the problem of you not being able to display your image.
Test this by comparing the int value coming from the database (int photoId = cursor.getInt(1)) and the int value of R.drawable.salad_greek.
In your SaladDetailActivity you should also check to see if you are getting a valid value for:
int salads = (Integer) getIntent().getExtras().get(EXTRA_SALAD);
I have created database following this tutorial, and I have created one button in main activity which will take users to another activity where they would add some new items. But I don't know how would I do this with ArrayList because I want to add new items in ListView. I want something like this to have in my application. Any help would be appricieated.
Here's the code of DataBase:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "itemManager";
// Contacts table name
private static final String TABLE_ITEMS = "items";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_PRICE = "price";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_PRICE + " TEXT" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new item
void addItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, item.getTitle()); // Title Name
values.put(KEY_PRICE, item.getPrice()); // Price
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
db.close(); // Closing database connection
}
// Getting item
Item getItem(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_TITLE, KEY_PRICE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return item
return item;
}
// Getting All Items
public List<Item> getAllItems() {
List<Item> itemsList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setTitle(cursor.getString(1));
item.setPrice(cursor.getString(2));
// Adding contact to list
itemsList.add(item);
} while (cursor.moveToNext());
}
// return items list
return itemsList;
}
// Updating single item
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, item.getTitle());
values.put(KEY_PRICE, item.getPrice());
// updating row
return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
}
// Deleting single item
public void deleteItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
db.close();
}
// Getting items Count
public int getItemsCount() {
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
and here is the code of MainActivity:
public class MainActivity extends BaseActivity {
Button addItem;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame_container);
// inflate the custom activity layout
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View activityView = layoutInflater.inflate(R.layout.activity_main, null,false);
frameLayout.addView(activityView);
// Setting toolbar
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
DatabaseHandler db = new DatabaseHandler(this);
addItem = (Button) findViewById(R.id.button1);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
Here's my Main Activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<Button
android:id="#+id/button1"
style="#style/MyCustomButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/button" />
<ListView
android:id="#+id/list"
android:layout_margin="5dp"
android:layout_below="#+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_centerHorizontal="true"
android:divider="#color/list_divider_row"
android:dividerHeight="10.0sp"
android:listSelector="#drawable/list_row_selector" >
</ListView>
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/listView1"
android:layout_alignRight="#+id/listView1"
android:layout_below="#+id/app_bar"
android:padding="10dp" >
<TextView
android:id="#+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:text="Items"
android:textColor="#474747"
android:textSize="16sp" />
<TextView
android:id="#+id/item_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="#+id/item_text"
android:text="(2)"
android:textColor="#474747"
android:textSize="14sp" />
<TextView
android:id="#+id/total_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Rs. 5700"
android:textColor="#000000"
android:textSize="20dp" />
</RelativeLayout>
</RelativeLayout>
In a nutshell, you need to pass the "result" of adding an item back to the main activity. Then, if there was an item added, you should call your adapter to update the adapter data.
// Your previous code
addItem = (Button) findViewById(R.id.button1);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent, ADD_ITEM_REQ_CODE);
}
});
// Then handle the result
public void onActivityResult(int reqCode, int resultCode, Intent data){
if (reqCode == ADD_ITEM_REQ_CODE && resultCode == RESULT_OK){
// get your ListView adapter and update data
mListAdapter.notifyDataSetChanged();
}
}
Your second activity, the one that adds an item should call setResult(RESULT_OK) when the item was added successfully and setResult(RESULT_CANCELLED) otherwise.
There some other things with your code, for instance, where do you populate your ListView? Normally, you would get the instance though a findViewById and set an adapter to that ListView, with the corresponding data.
Honestly, I think you should have a look to the tutorials again, specially these:
http://developer.android.com/training/basics/intents/result.html
http://developer.android.com/guide/topics/ui/layout/listview.html
I followed this tutorial to import database. Then I try to read the data using ArrayList to display them in listview. But I got nullpointer exception on my rawQuery saying it is invoking a null object reference.
DB.java
public class DB extends SQLiteOpenHelper {
//The Android's default system path of your application database.
private static String DB_PATH = "data/data/hairulhazri.malayforyou/databases/";
private static String DB_NAME = "malayforyou";
private static String TABLE_LOCATION = "Frasa";
private final Context context;
private SQLiteDatabase db;
// constructor
public DB(Context context) {
super( context , DB_NAME , null , 1);
this.context = context;
}
// Creates a empty database on the system and rewrites it with your own database.
public void create() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
// By calling this method and empty database will be created into the default system path
// of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// Check if the database exist to avoid re-copy the data
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String path = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
// database don't exist yet.
e.printStackTrace();
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
// copy your assets db to the new system DB
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
//Open the database
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch(SQLException sqle) {
db = null;
return false;
}
}
#Override
public synchronized void close() {
if(db != null)
db.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// PUBLIC METHODS TO ACCESS DB CONTENT
// -----------------------------------------------------------------------------------------------------------------
public ArrayList<Frasa> getFrasa(String situation) {
//ArrayList of Frasa class objects
ArrayList<Frasa> arrFrasa = null;
//String query = "SELECT * FROM Frasa WHERE Situation = " + situation;
String selectQuery = "SELECT " +
Frasa.KEY_ID + "," +
Frasa.KEY_PHRASE + "," +
Frasa.KEY_TRANSLATE + "," +
Frasa.KEY_PRONOUNCE +
" FROM " + TABLE_LOCATION + " WHERE situation = " +situation;
db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
Cursor curFrasa = db.rawQuery(selectQuery, null);
if (curFrasa != null && curFrasa.moveToFirst()) {
arrFrasa = new ArrayList<Frasa>();
while (curFrasa.isAfterLast() == false) {
//Frasa is a class with list of fields
Frasa fra = new Frasa();
fra.setId(curFrasa.getInt(curFrasa.getColumnIndex(Frasa.KEY_ID)));
fra.setPhrase(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PHRASE)));
fra.setTranslate(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_TRANSLATE)));
fra.setPronounce(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PRONOUNCE)));
arrFrasa.add(fra);
curFrasa.moveToNext();
}
}
curFrasa.close();
db.close();
return arrFrasa;
}
}
Frasa.java (Database table and columns)
public class Frasa {
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_PHRASE = "phrase";
public static final String KEY_TRANSLATE = "translate";
public static final String KEY_PRONOUNCE = "pronounce";
// property help us to keep data
public int id;
public String situation;
public String phrase;
public String translate;
public String pronounce;
public Frasa() {
}
public Frasa(int id, String situation, String phrase, String translate, String pronounce) {
this.id = id;
this.situation = situation;
this.phrase = phrase;
this.translate = translate;
this.pronounce = pronounce;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhrase() {
return phrase;
}
public void setPhrase(String phrase) {
this.phrase = phrase;
}
public String getTranslate() {
return translate;
}
public void setTranslate(String translate) {
this.translate = translate;
}
public String getPronounce() {
return pronounce;
}
public void setPronounce(String pronounce) {
this.pronounce = pronounce;
}
}
public class GreetingAdapter extends ArrayAdapter<Frasa> {
Context context;
int layoutResourceId;
ArrayList<Frasa> data = new ArrayList<Frasa>();
public GreetingAdapter(Context context, int layoutResourceId, ArrayList<Frasa> data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textPhrase = (TextView) row.findViewById(R.id.textViewPhrase);
holder.textTranslate = (TextView) row.findViewById(R.id.textViewTranslate);
holder.btnSpeak = (Button) row.findViewById(R.id.buttonSpeak);
holder.btnRecord = (Button) row.findViewById(R.id.buttonRecord);
holder.btnPlay = (Button) row.findViewById(R.id.buttonPlay);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
Frasa frasa = data.get(position);
holder.textPhrase.setText(frasa.getPhrase());
holder.textTranslate.setText(frasa.getTranslate());
holder.btnSpeak.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Speak button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Play Button Clicked", "**********");
Toast.makeText(context, "Playing recorded audio",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textPhrase;
TextView textTranslate;
Button btnSpeak;
Button btnRecord;
Button btnPlay;
}
}
activity_list_greetings.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt_header"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Greetings"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/black" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listGreetings"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/txt_header" />
list_item_greet.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textViewPhrase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phrase"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_above="#+id/buttonRecord"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonSpeak"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Speak"
android:textColor="#0099CC" />
<Button
android:id="#+id/buttonRecord"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSpeak"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Record"
android:textColor="#0099CC" />
<Button
android:id="#+id/buttonPlay"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonRecord"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Play"
android:textColor="#0099CC" />
<TextView
android:id="#+id/textViewTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Translate"
android:textSize="20sp"
android:textColor="#color/background_material_dark"
android:layout_below="#+id/buttonRecord"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
ListGreetings.java
public class ListGreetings extends ActionBarActivity {
TextView txtPhrase, txtTranslate;
Button speakButton;
MediaPlayer pronounce;
ListView userList;
GreetingAdapter greetAdapter;
//ArrayList<Frasa> frasaArray = new ArrayList<Frasa>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_greetings);
DB db = new DB(this);
db.open();
//get Frasa data
ArrayList<Frasa> frasaArray = db.getFrasa("Greetings");
/**
* set item into adapter
*/
greetAdapter = new GreetingAdapter(ListGreetings.this, R.layout.list_item_greet, frasaArray);
userList = (ListView) findViewById(R.id.listGreetings);
userList.setItemsCanFocus(false);
userList.setAdapter(greetAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_greetings, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Is it my way of calling getFrasa wrong? Or the database cannot be detected? I'm sure I already pushed the database file to both assets folder & inside the package. Sorry, if I'm not formatting the codes correctly. Thanks in advance for any help.
The problem is that you are trying to open the Database from a different location
private static String DB_PATH = "data/data/hairulhazri.malayforyou/databases/";
private static String DB_NAME = "malayforyou";
...
...
db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
db is returning NULL because your database is stored in /assets folder not in "data/data/hairulhazri.malayforyou/databases/"
I'm a newbie in developing an android app and I am currently developing cooking application. I want to add a new recipe to my db with recipe name, ingredients, procedures, category, notes and photo. But the problem is when I add photo from camera or gallery, it stop working and I want to view the image taken to an imageview and save it to db using a save button. But please help me. I don't know what to do with my project.
MY DBAdapter
package com.elasandesu.quickeasykitchenv3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_RNAME = "rname";
public static final String KEY_RCAT = "rcat";
public static final String KEY_RING = "ring";
public static final String KEY_RSTEPS = "rsteps";
public static final String KEY_RNOTE = "rnote";
public static final String KEY_RPHOTO = "rphoto";
//public static final String KEY_RPHOTONME = "rphotornme";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_RNAME = 1;
public static final int COL_RCAT = 2;
public static final int COL_RING = 3;
public static final int COL_RSTEPS = 4;
public static final int COL_RNOTE = 5;
public static final int COL_RPHOTO = 6;
//public static final int COL_RPHOTONME =7;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_RNAME, KEY_RCAT, KEY_RING, KEY_RSTEPS, KEY_RNOTE, KEY_RPHOTO};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Quick.sqlite";
public static final String DATABASE_TABLE = "recipe";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 5;
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ROWID + " INTEGER PRIMARY KEY," + KEY_RNAME + " TEXT,"
+ KEY_RCAT + " TEXT," + KEY_RING+ " TEXT," + KEY_RSTEPS + " TEXT,"
+ KEY_RNOTE + " TEXT," + KEY_RPHOTO + " BLOB" + ")";
db.execSQL(CREATE_RECIPE_TABLE);
}
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_RNAME, rName);
initialValues.put(KEY_RCAT, rCat);
initialValues.put(KEY_RING, rIng);
initialValues.put(KEY_RSTEPS, rSteps);
initialValues.put(KEY_RNOTE, rNote);
//initialValues.put(KEY_RPHOTO, rPhoto);
//initialValues.put(KEY_RPHOTONME, rPhotonme);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
//Get specific row by category
public Cursor getCateg (String categ) throws SQLException {
String where = "SELECT * FROM recipe where rcat=\""+categ+"\"";
Cursor c = db.rawQuery(where, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
//KEY_RCAT + " = \'" + categ + " \'";
//"select * from contacts where id="+id+"", null
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_RNAME, rName);
newValues.put(KEY_RCAT, rCat);
newValues.put(KEY_RING, rIng);
newValues.put(KEY_RSTEPS, rSteps);
newValues.put(KEY_RNOTE, rNote);
//newValues.put(KEY_RPHOTO, rPhoto);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteAssetHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
}
Activity Code
package com.elasandesu.quickeasykitchenv3;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Addrecipe extends Activity implements OnItemSelectedListener{
String[] cat = {"BEEF","CHICKEN",
"PORK", "FISH", "VEGETABLES"};
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
private String selectedImagePath;
String DB_NAME = Environment.getExternalStorageDirectory() + "/Quick.sqlite";
String TABLE_NAME = "recipe";
ImageView recphoto;
DBAdapter db;
EditText recname, recing, recsteps, recnote;
Spinner spinner1;
TextView category;
Button save, reset, upload;
public static String rcat = " ";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addrecipe);
category = (TextView) findViewById(R.id.categorytxtview);
spinner1 = (Spinner) findViewById(R.id.categorysp);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cat);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter_state);
spinner1.setOnItemSelectedListener(this);
save = (Button) findViewById(R.id.savebtn);
reset = (Button) findViewById(R.id.resetbtn);
recname = (EditText) findViewById(R.id.recipename);
recing = (EditText) findViewById(R.id.ingredient);
recnote = (EditText) findViewById(R.id.note);
recsteps = (EditText) findViewById(R.id.procedure);
recphoto= (ImageView) findViewById(R.id.image);
openDB();
final String[] option = new String[] { "Take from Camera", "Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
Button addImage = (Button) findViewById(R.id.uploadbtn);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
//insert activity here :D
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras= data.getExtras();
if (extras != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage.compress(CompressFormat.PNG, 0, stream);
byte[] bytes = stream.toByteArray();
recphoto.setImageBitmap(selectedImage);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
recphoto.setImageURI(selectedImageUri);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
cameraIntent.putExtra("crop", "true");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
db = new DBAdapter(this);
db.open();
}
private void closeDB() {
db.close();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinner1.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void saveHasBeenClicked (View v) {
String rName = recname.getText().toString();
String rIng = recing.getText().toString();
String rSteps =recsteps.getText().toString();
String rNote = recnote.getText().toString();
String rCat = (String) spinner1.getSelectedItem();
long newId = db.insertRow(rName,"\n"+ rCat," \n "+ rIng," \n" + rSteps, rNote);
Cursor cursor = db.getRow(newId);
displayRecordSet(cursor);
Intent evilIntent = new Intent(Addrecipe.this, Selected.class);
startActivity(evilIntent);
}
public void onClick_ClearAll(View v) {
db.deleteAll();
Toast.makeText(getBaseContext(), "Cleared ", Toast.LENGTH_LONG).show();
}
// Display an entire record set to the screen.
private void displayRecordSet(Cursor cursor) {
String message = "";
// populate the message from the cursor
// Reset cursor to start, checking to see if there's data:
if (cursor.moveToFirst()) {
do {
// Process the data:
int id = cursor.getInt(DBAdapter.COL_ROWID);
String rName = cursor.getString(DBAdapter.COL_RNAME);
String rCat = cursor.getString(DBAdapter.COL_RCAT);
String rIng = cursor.getString(DBAdapter.COL_RING);
String rSteps = cursor.getString(DBAdapter.COL_RSTEPS);
String rNote = cursor.getString(DBAdapter.COL_RNOTE);
// Append data to the message:
message += "id=" + id
+", Recipe Name : " + rName
+", Category : " + rCat
+", Ingredients : " + rIng
+", Procedure: " + rSteps
+", Note: " + rNote
+"\n";
} while(cursor.moveToNext());
Toast.makeText(getBaseContext(), "Save Has Been Clicked "+ message, Toast.LENGTH_LONG).show();
}
// Close the cursor to avoid a resource leak.
cursor.close();
}
}
And the XML file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/clr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/nb"
android:onClick="displayClicked"
android:screenOrientation="landscape"
tools:ignore="HardcodedText" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="1462dp" >
<EditText
android:id="#+id/recipename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/recipenametxtview"
android:layout_alignBottom="#+id/recipenametxtview"
android:layout_alignParentRight="true"
android:layout_marginRight="70dp"
android:ems="10"
android:hint="Type the Recipe Name"
tools:ignore="TextFields" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/categorytxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/recipenametxtview"
android:layout_below="#+id/recipename"
android:layout_marginTop="50dp"
android:text="Category:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/ingtxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/categorytxtview"
android:layout_below="#+id/categorysp"
android:layout_marginTop="42dp"
android:text="Ingredients:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/categorysp"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignLeft="#+id/recipename"
android:layout_alignRight="#+id/recipename"
android:layout_alignTop="#+id/categorytxtview" />
<TextView
android:id="#+id/notetxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="253dp"
android:text="Note:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/ingredient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingtxtview"
android:layout_alignRight="#+id/categorysp"
android:layout_below="#+id/ingtxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type Here the Ingredients : e.g. 1 kilo of Flour"
android:inputType="text"
android:singleLine="false"
tools:ignore="TextFields" />
<EditText
android:id="#+id/procedure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_alignRight="#+id/ingredient"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type in this format 1.) procedure 1 [newline] 2.) procedure 2"
tools:ignore="TextFields" />
<EditText
android:id="#+id/note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/notetxtview"
android:layout_alignRight="#+id/procedure"
android:layout_below="#+id/notetxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Includes information, cautions and other health information"
tools:ignore="TextFields" />
<TextView
android:id="#+id/recipenametxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/itemRname"
android:layout_marginLeft="62dp"
android:layout_marginTop="67dp"
android:text="Recipe Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phototxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/note"
android:layout_below="#+id/note"
android:layout_marginTop="101dp"
android:text="Photo:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/proceduretxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingredient"
android:layout_below="#+id/ingredient"
android:layout_marginTop="172dp"
android:text="Procedure:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/uploadbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/phototxtview"
android:layout_alignBottom="#+id/phototxtview"
android:layout_toRightOf="#+id/ingtxtview"
android:text="Upload Photo" />
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_below="#+id/uploadbtn"
android:layout_marginTop="42dp"/>
<Button
android:id="#+id/resetbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/savebtn"
android:layout_alignBottom="#+id/savebtn"
android:layout_alignRight="#+id/note"
android:layout_marginRight="55dp"
android:onClick="onClick_ClearAll()"
android:text="Reset" />
<Button
android:id="#+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/uploadbtn"
android:layout_below="#+id/image"
android:layout_marginTop="56dp"
android:onClick="saveHasBeenClicked"
android:text="Save" />
</RelativeLayout>
</ScrollView>
please help me.. it will be a great help.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am working on an Android quiz . I have created my database with one question and four options along-with difficulty level. I have created a layout to display the question with four buttons . Now the problem is how will i connect my database with the question and four buttons.
so as to, when I click on right button it moves to the next question and when I click on wrong button it gives an error and exits.
Code In XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center_horizontal"
android:background="#drawable/background">
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="110dp"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="1dip"
android:paddingTop="1dip"
android:src="#drawable/logo2" />
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:gravity="center_horizontal">
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical"
android:background="#99CCFF"
android:id="#+id/group1">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#0000CC"
android:textStyle="bold" android:id="#+id/question"/>
<Button android:onClick="false" android:id="#+id/answer1"
android:layout_width="150dip" />
<Button android:onClick="false" android:id="#+id/answer2"
android:layout_width="150dip" />
<Button android:onClick="false" android:id="#+id/answer3"
android:layout_width="150dip"/>
<Button android:onClick="false" android:id="#+id/answer4"
android:layout_width="150dip" />
</RadioGroup>
</LinearLayout>
MY DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.starchazer.cyk/databases/";
private static String DB_NAME = "questionsDb";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(!dbExist)
{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
public List<Question> getQuestionSet(int difficulty, int numQ){
List<Question> questionSet = new ArrayList<Question>();
Cursor c = myDataBase.rawQuery("SELECT * FROM QUESTIONS WHERE DIFFICULTY=" + difficulty +
" ORDER BY RANDOM() LIMIT " + numQ, null);
while (c.moveToNext()){
//Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
Question q = new Question();
q.setQuestion(c.getString(1));
q.setAnswer(c.getString(2));
q.setOption1(c.getString(3));
q.setOption2(c.getString(4));
q.setOption3(c.getString(5));
q.setRating(difficulty);
questionSet.add(q);
}
return questionSet;
}
}
MY QuestionActivity
public class QuestionActivity extends Activity implements OnClickListener{
private Question currentQ;
private GamePlay currentGame;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
/**
* Configure current game and get question
*/
currentGame = ((XYZ_Application)getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
Button c1 = (Button) findViewById(R.id.answer1 );
c1.setOnClickListener(this);
Button c2 = (Button) findViewById(R.id.answer2 );
c2.setOnClickListener(this);
Button c3 = (Button) findViewById(R.id.answer3 );
c3.setOnClickListener(this);
Button c4 = (Button) findViewById(R.id.answer4 );
c4.setOnClickListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current games
* current question
*/
private void setQuestions() {
//set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion()) + "?";
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
//set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
}
#Override
public void onClick(View arg0) {
/**
* validate a buttonselected has been selected
*/
if (!checkAnswer()) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()){
Intent i = new Intent(this, Main.class);
startActivity(i);
finish();
}
else{
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it
* has then check if its correct and update gamescore
*/
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer==null){
return false;
}
else {
if (currentQ.getAnswer().equalsIgnoreCase(answer))
{
//Log.d("Questions", "Correct Answer!");
currentGame.incrementRightAnswers();
}
else{
//Log.d("Questions", "Incorrect Answer!");
currentGame.incrementWrongAnswers();
}
return true;
}
}
/**
*
*/
private String getSelectedAnswer() {
Button c1 = (Button)findViewById(R.id.answer1);
Button c2 = (Button)findViewById(R.id.answer2);
Button c3 = (Button)findViewById(R.id.answer3);
Button c4 = (Button)findViewById(R.id.answer4);
if (c1.callOnClick())
{
return c1.getText().toString();
}
if (c2.callOnClick())
{
return c2.getText().toString();
}
if (c3.callOnClick())
{
return c3.getText().toString();
}
if (c4.callOnClick())
{
return c4.getText().toString();
}
return null;
}
}
I am sorry I will not be giving code here.
Here is what I would have done
When Actvity Starts
Load Question from Db with Options
I ll prefer option as array/arraylist
Assign Text Option to each button
Add a common onclick listener like this
public void onClick(View v){
int id=v.getId();
String answer=v.getText();
if(answer.equals('ANSWER FROM DB'){
// If right then next question
// Else to MainActivity
}
/**switch(id){
case R.id.answer1:
processAnswer(1);
break;
case R.id.answer2:
processAnswer(2);
break;
// So on
}
**/
}
And processAnswer would look like
void processAnswer(int option){
// Since I have the option here
// I will check it with Database
// If its correct then next question else exit
}