我正在尝试制作一个Android应用程序,在使用Android默认摄像头捕获图像后,将图像名称,经度,经度和时间戳保存到sqlite数据库中。我设法拍了一张照片并将其保存到特定的文件夹但我在将数据保存到数据库时遇到问题。这是我迄今为止的努力:
public class CameraActivity extends Activity {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "PHOTO MAP";
private Uri fileUri;
File file =new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "PHOTO MAP");
private ImageView imgPreview;
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
try {
//opening GPSTracker
GPSTracker gps = new GPSTracker(this);
gps = new GPSTracker(CameraActivity.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
} else {
gps.showSettingsAlert();
}
} finally{
//TODO
}
imgPreview = (ImageView) findViewById(R.id.imgPreview);
captureImage();
}
//icture captured or user cancelled
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == RESULT_OK){
galleryAddPic();
//newPhotograph(imgPreview);
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "user cancelled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "failed to capture image", Toast.LENGTH_SHORT).show();
}
}
/*
@Override
public void onResume(){
super.onResume();
captureImage();
}
*/
//Null pointer exception if not added
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putParcelable("file_uri", fileUri);
}
//Null pointer exception if not added
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
//Back pressed returns you to main menu
@Override
public void onBackPressed(){
Intent backIntent = new Intent(this, MainMenu.class);
startActivity(backIntent);
finish();
}
/*----------------------------------------------------------------------------------------------------------------
* HELPER METHODS
----------------------------------------------------------------------------------------------------------------*/
private void captureImage(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
if(!mediaStorageDir.exists()){
if(!mediaStorageDir.mkdirs()){
Log.d(IMAGE_DIRECTORY_NAME,"Failed create" + IMAGE_DIRECTORY_NAME + "directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
if(type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
private void previewCapturedImage(){
try{
imgPreview.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options);
imgPreview.setImageBitmap(bitmap);
newPhotograph(imgPreview);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
//make photo available to android default gallery
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(file.getPath());
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
//add photograph to database(with slightly different name though - need fix)
private void newPhotograph(View view){
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
DatabaseHandler dbHandler = new DatabaseHandler(this);
Photographs photograph = new Photographs(timeStamp.toString(), String.valueOf(gps.getLatitude()), String.valueOf(gps.getLongitude()), timeStamp.toString());
dbHandler.addPhotograph(timeStamp.toString(), String.valueOf(gps.getLatitude()), String.valueOf(gps.getLongitude()), timeStamp.toString());
}
//method for button over image view to returns as on camera activity
public void cameraActivity(View view){
Intent cameraIntent = new Intent(this,
CameraActivity.class);
startActivity(cameraIntent);
finish();
}
//method for button over image view to send as to Map activity
public void mapActivity(View view){
Intent mapIntent = new Intent(this, MapActivity.class);
startActivity(mapIntent);
finish();
}
}
数据库处理程序:
public class DatabaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "photographsManager";
private static final String TABLE_PHOTOGRAPHS = "photographs";
private static final String KEY_ID = "_id";
private static final String KEY_NAME = "name";
//============================================================================= change Photographs.java Double to String???===>changed(Commit??)
private static final String KEY_LAT = "latitude";
private static final String KEY_LON = "longitude";
//==============================================================================
private static final String KEY_TMS = "timeStamp";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PHOTOGRAPHS_TABLE = "CREATE TABLE " + TABLE_PHOTOGRAPHS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_LAT + " DOUBLE" + KEY_LON + "DOUBLE" + KEY_TMS + "String" + ")";
db.execSQL(CREATE_PHOTOGRAPHS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PHOTOGRAPHS);
// Create tables again
onCreate(db);
}
/*
* CRUD operations
*/
public void addPhotograph(String name, String Latitude, String Longitude, String timeStamp){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name);
values.put(KEY_LAT, Longitude);
values.put(KEY_LON, Longitude);
values.put(KEY_TMS, timeStamp);
db.insert(TABLE_PHOTOGRAPHS, null, values);
db.close();
}
public Photographs getPhotograph(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PHOTOGRAPHS, new String[] { KEY_ID }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Photographs photograph = new Photographs(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
return photograph;
}
public List<Photographs> getPhotographs(){
List<Photographs> list = new ArrayList<Photographs>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_PHOTOGRAPHS;
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Photographs photograph = new Photographs();
photograph.setID(Integer.valueOf(cursor.getString(0)));
photograph.setName(cursor.getString(1));
photograph.setLatitude(cursor.getString(2));
photograph.setLongitude(cursor.getString(3));
photograph.setTimeStamp(cursor.getString(4));
list.add(photograph);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
}
照片模型:
public class Photographs {
int _id;
String _name;
String _Latitude;
String _Longitude;
String _timeStamp;
//empty constructor
public Photographs(){
}
//constructor
public Photographs(int id, String name, String latitude, String longitude, String timeStamp){
this._id = id;
this._name = name;
this._Latitude = latitude;
this._Longitude = longitude;
this._timeStamp = timeStamp;
}
//constructor
public Photographs(String name, String latitude, String longitude, String timeStamp){
this._name = name;
this._Latitude = latitude;
this._Longitude = longitude;
this._timeStamp = timeStamp;
}
//ACCESSORS
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getLatitude(){
return this._Latitude;
}
public void setLatitude(String latitude){
this._Latitude = latitude;
}
public String getLongitude(){
return this._Longitude;
}
public void setLongitude(String longitude){
this._Longitude = longitude;
}
public String getTimeStamp(){
return this._timeStamp;
}
public void setTimeStamp(String timeStamp){
this._timeStamp = timeStamp;
}
}
非常感谢任何帮助,请提前感谢您的时间。
答案 0 :(得分:0)
由于这行代码发生了所有Null指针异常后:
dbHandler.addPhotograph(timeStamp.toString(),String.valueOf(gps.getLatitude()),String.valueOf(gps.getLongitude()),timeStamp.toString());
从我读到的内容中,String.valueOf()将对象作为参数,并将表示作为字符串返回。 valueOf()实现如下:
public static String valueOf(Object obj) {
return(obj == null)? &#34;空&#34; :obj.toString(); }
由于我没有传递一个对象而是一个premetive类型(double),因此我提出了一个null。我改变了解析双(经度和纬度)的方式,问题得到解决。我不知道扩展是否足够,但现在它可以工作。