我是开发Android应用程序的新手,我正在开发烹饪应用程序。我想在我的数据库中添加一个新的食谱,包括食谱名称,成分,程序,类别,注释和照片。但问题是当我从相机或图库添加照片时,它停止工作,我想查看拍摄到imageview的图像并使用保存按钮将其保存到数据库。但请帮助我。我不知道如何处理我的项目。
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.