saving image in sqlite db using a save button - java

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.

Related

App stops working when clicked on Button coded to save, refresh and search

I need help fixing a problem with my 3 buttons that don't work properly and I'm not sure how to fix it. The "Save" button is to keep my database save, the "Refresh" button is to clear, and the "Search" button is to find an existing database. My TextView shows the existing database after registered. These are my goals to accomplish.
Here are my code files:
XML File:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_verticsl_margin"
android:paddingBottom="#dimen/activity_verticsl_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dip"
android:gravity="center"
android:text="Registration"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtid"
android:hint="ID"
android:inputType="number"
android:layout_marginTop="5dip"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtfirstname"
android:hint="#string/first_name"
android:layout_marginTop="5dip"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtlastname"
android:hint="#string/last_name"
android:layout_marginTop="5dip"
/>
<EditText
android:id="#+id/txtmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:hint="#string/e_mail" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtuser"
android:hint="#string/username"
android:layout_marginTop="5dip"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtpw"
android:hint="#string/password"
android:layout_marginTop="5dip"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="save"
android:textColor="#fff"
android:textSize="15dip"
android:id="#+id/btnsave"
android:layout_weight="1"
android:layout_gravity="center_horizontal"/>
<Button
android:id="#+id/btnclear"
android:layout_width="212dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight=".30"
android:text="refresh"
android:textColor="#fff"
android:textSize="15dip"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="search"
android:textColor="#fff"
android:textSize="15dip"
android:id="#+id/btnsearch"
android:layout_weight="1"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"/>
</TableLayout>
Java File StudentRegistration.java:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StudentRegistration {
public static final String KEY_ROWID ="_id";
public static final String KEY_FNAME = "fname";
public static final String KEY_LNAME = "lname";
public static final String KEY_EMAIL = "email";
public static final String KEY_USER ="user";
public static final String KEY_PASS ="pass";
private static final String DATABASE_NAME = "StudentDB";
private static final String DATABASE_TABLE = "StudentTbl";
private static final int DATABASE_VERSION = 1;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME,
null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_FNAME + " TEXT NOT NULL, " +
KEY_LNAME + " TEXT NOT NULL, " +
KEY_EMAIL + " TEXT NOT NULL, " +
KEY_USER + " TEXT NOT NULL, " +
KEY_PASS + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
onCreate(db);
}
}
public StudentRegistration(Context c) {
ourContext = c;
}
public StudentRegistration open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long savedata(String fname, String lname, String email, String user, String pass) {
ContentValues cv = new ContentValues();
cv.put(KEY_FNAME, fname);
cv.put(KEY_LNAME, lname);
cv.put(KEY_EMAIL, email);
cv.put(KEY_USER, user);
cv.put(KEY_PASS, pass);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData(){
String[] refresh = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, refresh, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iFName = c.getColumnIndex(KEY_FNAME);
int iLName = c.getColumnIndex(KEY_LNAME);
int iEmail = c.getColumnIndex(KEY_EMAIL);
int iUser = c.getColumnIndex(KEY_USER);
int iPass = c.getColumnIndex(KEY_PASS);
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow)
+ " " + c.getString(iFName)
+ " " + c.getString(iLName)
+ " " + c.getString(iEmail)
+ " " + c.getString(iUser)
+ " " + c.getString(iPass)
+ "\n\n";
}
return result;
}
public String getFName(long l){
String[] getfname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getfname, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String fname = c.getString(1);
return fname;
}
return null;
}
public String getLName(long l){
String[] getlname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getlname, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String lname = c.getString(2);
return lname;
}
return null;
}
public String getEmail(long l){
String[] getemail = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getemail, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String email = c.getString(3);
return email;
}
return null;
}
public String getUser(long l){
String[] getuser = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getuser, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String user = c.getString(4);
return user;
}
return null;
}
public String getPass(long l){
String[] getpass = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getpass, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String pass = c.getString(5);
return pass;
}
return null;
}
}
and the java file MainActivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText FirstName, LastName, Email, UserName, Password, ID;
Button Save, Clear, Search;
TextView TxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstName = (EditText)findViewById(R.id.txtfirstname);
LastName = (EditText)findViewById(R.id.txtlastname);
Email = (EditText)findViewById(R.id.txtmail);
UserName = (EditText)findViewById(R.id.txtuser);
Password = (EditText)findViewById(R.id.txtpw);
TxtData =(TextView)findViewById(R.id.textView);
Save =(Button)findViewById(R.id.btnsave);
Clear=(Button)findViewById(R.id.btnclear);
Search=(Button)findViewById(R.id.btnsearch);
Search.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String search = ID.getText().toString();
Long l= Long.parseLong(search);
StudentRegistration mysearch = new
StudentRegistration(MainActivity.this);
mysearch.open();
String returnedFname = mysearch.getFName(l);
String returnedLname = mysearch.getLName(l);
String returnedEmail = mysearch.getEmail(l);
String returnedUser = mysearch.getUser(l);
String returnedPass = mysearch.getPass(l);
mysearch.close();
FirstName.setText(returnedFname);
LastName.setText(returnedLname);
Email.setText(returnedEmail);
UserName.setText(returnedUser);
Password.setText(returnedPass);
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname = FirstName.getText().toString();
String lname = LastName.getText().toString();
String email = Email.getText().toString();
String user = UserName.getText().toString();
String pass = Password.getText().toString();
StudentRegistration save = new StudentRegistration(MainActivity.this);
save.open();
save.savedata(fname, lname, email, user, pass);
FirstName.setText("");
LastName.setText("");
Email.setText("");
UserName.setText("");
Password.setText("");
ID.setText("");
}
});
Clear.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
StudentRegistration refresh = new StudentRegistration(MainActivity.this);
refresh.open();
String data = refresh.getData();
refresh.close();
TxtData.setText(data);
FirstName.setText("");
LastName.setText("");
Email.setText("");
UserName.setText("");
Password.setText("");
ID.setText("");
}
});
}
}
My Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.classifiedinformation">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
How can I accomplish my goals?
First of all some hints about what went wrong would have been nice.
You need to initialize ID like you did with the other EditText's.
Add ID = findViewById(R.id.txtid); to your onCreate(Bundle savedInstanceState) method.
The first thing I got when clicking on 'Save' was the following:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.citiesapps.myapplication.MainActivity$2.onClick(MainActivity.java:76)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
As the stacktrace states you are trying to invoke a method on a null-object in this case 'ID'.
After analyzing your code, i saw your are executing setText on an editText that is not initialized in your java class.
Probable editText code is:
ID.setText(""); Here ID is not initialized with xml file.
Use ID = findViewById(R.id.txtid); for initializing the ID field
Check all editText initialization. Then use that editText.
Thanks :)

How would I create new activity where I would have option to add new items from database?

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

Android - Import database get nullpointerexception on rawquery

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/"

ArrayList<HashMap<String, String>> to SQLite database android

I have a database that has a table with 4 columns : ID, Contact(name), Phone, Message.
ID is auto incremented.
Contact name and number comes from an ArrayList>
Message comes from an EditText.
I am have problems trying to create the part to bring in the ArrayList> to the Database.
I have the part for the message but later I will need to either put that message in every slot? Or maybe not save it in the database but somewhere else.
Also, should I keep the contact name? or just the number since the number is what will be used to send the SMS message?
Thanks in advance!
Below is my code.
Contacts.java - gets the contacts from the contact list and saves them in an ArrayList>
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.deptofpharmacology.test.R;
import java.util.ArrayList;
import java.util.HashMap;
public class Contacts extends ActionBarActivity {
private static final int PICK_CONTACT = 1;
private static final String TAG = "The Goods: ";
DatabHelper myDb;
private static ArrayList<HashMap<String, String>> getContacts = new ArrayList<HashMap<String, String>>();
private static ArrayList<HashMap<String, String>> data1 = new ArrayList<HashMap<String, String>>();
private static HashMap<String, String> contacts = new HashMap<String,String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
myDb = new DatabHelper(this);
// ArrayList<HashMap<String, String>> getD = myDb.insertRecord();
}
/**
this is what's going to be used to transfer the Arraylist<HashMap> to the database
public void AddConPhon(){
boolean isInserted = myDb.insertData(Contacts.this, );
}
**/
public void btnAddContacts_Click(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
public void btnDone_Click(View view){
Intent i = new Intent(Contacts.this, Message.class);
startActivity(i);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id =
c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =
c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
null, null);
phones.moveToFirst();
String phn_no = phones.getString(phones.getColumnIndex("data1"));
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DISPLAY_NAME));
contacts.put(name, phn_no);
HashMap<String, String> h = new HashMap<String, String>();
h.put("name", name);
h.put("phone", phn_no);
data1.add(h);
Toast.makeText(this, "contact info : " + phn_no + "\n" + name, Toast.LENGTH_LONG).show();
Log.d(TAG," " + data1.size());
Log.d(TAG, data1.toString());
}
}
}
}
}
Contacts 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.deptofpharmacology.test.Contacts">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/contact1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="82dp"
android:clickable="true"
android:onClick="btnAddContacts_Click" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/contact2"
android:layout_below="#+id/contact1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp"
android:clickable="true"
android:onClick="btnAddContacts_Click" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/contact3"
android:layout_below="#+id/contact2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="49dp"
android:clickable="true"
android:onClick="btnAddContacts_Click" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/contact4"
android:layout_below="#+id/contact3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:clickable="true"
android:onClick="btnAddContacts_Click" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/Next1"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:clickable="true"
android:onClick="btnDone_Click" />
</RelativeLayout>
the Database
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.HashMap;
public class DatabHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "PostalE.db";
public static final String TABLE_NAME = "emergency_table";
public static final String COL_1= "ID";
public static final String COL_2 = "CONTACTS";
public static final String COL_3 = "NUMBERS";
public static final String COL_4 = "MESSAGE";
public DatabHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, CONTACTS TEXT ,NUMBERS INTEGER, MESSAGE TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertRecord(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", queryValues.get("name"));
values.put("phone", queryValues.get("phone"));
database.insert(COL_2, null, values);
database.insert(COL_3, null, values);
long result = database.insert(TABLE_NAME,null,values);
if(result == -1){
return false;
}else{
return true;
}
}
/**
public boolean insertData(String name, String phone){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,phone);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
**/
public boolean insertData(String message){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_4,message);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
}
This how you add it to the database from Contacts.class
DatabHelper databasecontroller = new DatabHelper(Contacts.this);
//or context
HashMap<String, String> values = new HashMap<String, String>();
values .put("somecolumnname1", sometextbuttonorwhateverview1.getText().toString());
values .put("somecolumnname2", sometextbuttonorwhateverview2.getText().toString());
values .put("somecolumnname13", sometextbuttonorwhateverview3.getText().toString());
databasecontroller.enterdata(values);
Put in Database
public void enterdata(HashMap<String, String> Vi) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("somecolumnname1", Vi.get("somecolumnname1"));
values.put("somecolumnname2", Vi.get("somecolumnname2"));
//etc
database.insert("DatabHelper", null, values);
database.close();
}
Where you do this
HashMap<String, String> h = new HashMap<String, String>();
h.put("name", name);
h.put("phone", phn_no);
data1.add(h);
You can simplify by doing
HashMap<String, String> values = new HashMap<String, String>();
values .put("name", name);
values .put("phone", phn_no);
databasecontroller.enterdata(values);
put in databaseclass
public void inserI(ArrayList<HashMap<String, String>> list1) {
// TODO Auto-generated method stub
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues1 = new ContentValues();
for(int i=0;i<list1.size();i++){
newValues1.put(ITEM, list1.get(i).get("names").toString());
newValues1.put(QUA, list1.get(i).get("phone").toString());
//newValues1.put(RATE,list1.get(i).get(THIRD_COLUMN).toString());
db.insert(QUANTITY, null, newValues1);
}

Retrieve a specific row data in database Android

I think I have read pretty much all the answers about this topic without getting the right answer for my case.
I have a list view in one activity called Library. When I click on an item, I would like to retrieve the informations about the clicked item in another activity. I would like these information to be in different field.
You will probably understand a bit better with my code.
This is the Library activity, on which I have my listview of what I call "tags":
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class InfoTagActivity extends ActionBarActivity {
TextView textTagName;
TextView textTagId;
TextView textTagData;
String tagId;
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
static SQLiteDatabase db = null;
private DatabaseHelper databaseHelper;
long tag_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_tag);
getSupportActionBar().hide();
//String tagName = this.getIntent().getStringExtra(TAG_NAME);
databaseHelper = new DatabaseHelper(this);
textTagName = (TextView) findViewById(R.id.tagName);
textTagId = (TextView) findViewById(R.id.tagId);
textTagData = (TextView) findViewById(R.id.tagInfo);
Intent intent = getIntent();
Cursor cursor = databaseHelper.getAllData();
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("tag_name"));
textTagName.append(name);
String id = cursor.getString(cursor.getColumnIndex("tag_mid"));
textTagId.append(id);
String info = cursor.getString(cursor.getColumnIndex("tag_data"));
textTagData.append(info);
}
}
}
DatabaseHelper.java :
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper {
private static final String TAG = DatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
// table configuration
public static final String TABLE_NAME = "person_table"; // Table name
private static final String TAG_ID = "_id"; // a column named "_id" is required for cursor
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public DatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aTagName, String aTagId, String aTagData) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(TAG_NAME, aTagName);
contentValues.put(TAG_MID, aTagId);
contentValues.put(TAG_DATA, aTagData);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// 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 + "( " + TAG_ID + " INTEGER PRIMARY KEY, " +
TAG_NAME + " TEXT, " + TAG_MID + " TEXT, " + TAG_DATA + " 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
}
}
}
And InfoTagActivity.java , this is in this activity that I want to get the information about the clicked item :
public class InfoTagActivity extends ActionBarActivity {
TextView textTagName;
TextView textTagId;
TextView textTagData;
String tagId;
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
static SQLiteDatabase db = null;
private DatabaseHelper databaseHelper;
long tag_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_tag);
getSupportActionBar().hide();
//String tagName = this.getIntent().getStringExtra(TAG_NAME);
databaseHelper = new DatabaseHelper(this);
textTagName = (TextView) findViewById(R.id.tagName);
textTagId = (TextView) findViewById(R.id.tagId);
textTagData = (TextView) findViewById(R.id.tagInfo);
Intent intent = getIntent();
Cursor cursor = databaseHelper.getAllData();
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("tag_name"));
textTagName.append(name);
String id = cursor.getString(cursor.getColumnIndex("tag_mid"));
textTagId.append(id);
String info = cursor.getString(cursor.getColumnIndex("tag_data"));
textTagData.append(info);
}
}
}
With the associated activity_info_tag.xml :
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/relativeLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/relativeLayout2"
android:paddingTop="10dp">
<TextView
android:id="#+id/tagId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_above="#+id/tagDate"
android:layout_toRightOf="#+id/tagIdText"
android:layout_toEndOf="#+id/tagIdText" />
<TextView
android:id="#+id/tagDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:layout_alignTop="#+id/tagDateText"
android:layout_toRightOf="#+id/tagDateText"
android:layout_toEndOf="#+id/tagDateText"
android:paddingLeft="5dp"
android:paddingRight="5dp"/>
<TextView
android:id="#+id/tagInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:layout_below="#+id/tagDate"
android:layout_toRightOf="#+id/tagInfoText"
android:layout_toEndOf="#+id/tagInfoText"
android:paddingLeft="5dp"
android:paddingRight="5dp"
/>
</RelativeLayout>
My problem is that by now, when I click on a tag of the list view, it always give me the information about the first tag only. I would like to get the information about the tag on which I clicked instead.
Could someone help me on that ?
Thank you a lot for your answers !

Categories