当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Sqlite Database - How to save Image taken from camera intent as well as hashmap to sqlite to retrieve later?

问题描述:

I am having endless problem with my app, I am busy making an app where the user can take a picture from the point tapped on the map and return with an image, all Of that works a 100% but, the problem is that when the user exits the app or navigates to a different activity all the markers dissapear. So i have asked a question here SO how to save the markers and to the map and some say to use sharedPreferences and others SQLite database.

Now i have implemented both and none work in what i am trying to achieve, and that is to save the image to that specific marker and return that image when the user taps on the marker after the user has exit the app and returned.

So this is my code for my SQlite:

This is my LocationsDB.java

public class LocationsDB extends SQLiteOpenHelper {

/**

* Database name

*/

private static String DBNAME = "locationmarkersqlite";

private static int VERSION = 1;

public static final String FIELD_ROW_ID = "_id";

public static final String FIELD_LAT = "lat";

public static final String FIELD_LNG = "lng";

public static final String FIELD_ZOOM = "zom";

public static final String FIELD_IMAGE = "img";

public static final String FIELD_HASH = "hash";

private static final String DATABASE_TABLE = "locations";

private SQLiteDatabase mDB;

public LocationsDB(Context context) {

super(context, DBNAME, null, VERSION);

this.mDB = getWritableDatabase();

}

@Override

public void onCreate(SQLiteDatabase db) {

String sql = "create table " + DATABASE_TABLE + " ( " +

FIELD_ROW_ID + " integer primary key autoincrement , " +

FIELD_LNG + " double , " +

FIELD_LAT + " double , " +

FIELD_ZOOM + " text , " +

FIELD_IMAGE + " image , " +

FIELD_HASH + "text " +

" ) ";

db.execSQL(sql);

}

public long insert(ContentValues contentValues) {

long rowID = mDB.insert(DATABASE_TABLE, null, contentValues);

return rowID;

}

public int del() {

int cnt = mDB.delete(DATABASE_TABLE, null, null);

return cnt;

}

public Cursor getAllLocations() {

return mDB.query(DATABASE_TABLE, new String[]{FIELD_ROW_ID, FIELD_LAT, FIELD_LNG, FIELD_ZOOM, FIELD_IMAGE, FIELD_HASH}, null, null, null, null, null, null);

}

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

This is myLocationsContentProvider.java

public class LocationsContentProvider extends ContentProvider {

public static final String PROVIDER_NAME = "com.example.mainapp.locations";

public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/locations");

private static final int LOCATIONS = 1;

private static final UriMatcher uriMatcher;

static {

uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

uriMatcher.addURI(PROVIDER_NAME, "locations", LOCATIONS);

}

LocationsDB mLocationsDB;

@Override

public boolean onCreate() {

mLocationsDB = new LocationsDB(getContext());

return true;

}

@Override

public Uri insert(Uri uri, ContentValues values) {

long rowID = mLocationsDB.insert(values);

Uri _uri = null;

if (rowID > 0) {

_uri = ContentUris.withAppendedId(CONTENT_URI, rowID);

} else {

try {

throw new SQLException("Failed to insert : " + uri);

} catch (SQLException e) {

e.printStackTrace();

}

}

return _uri;

}

@Override

public int update(Uri uri, ContentValues values, String selection,

String[] selectionArgs) {

return 0;

}

@Override

public int delete(Uri uri, String selection, String[] selectionArgs) {

int cnt = 0;

cnt = mLocationsDB.del();

return cnt;

}

@Override

public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

if (uriMatcher.match(uri) == LOCATIONS) {

return mLocationsDB.getAllLocations();

}

return null;

}

@Override

public String getType(Uri uri) {

return null;

}

}

Then in my main activity map activity i have this:

private GoogleMap googleMap;

private static final String EXTRA_PLACE = "thePoint";

private static final int TAKE_PICTURE = 0;

LatLng thePoint;

Bitmap bitmap;

final Context context = this;

protected Dialog view;

private Uri fileUri;

private int rotate;

private File image;

private Map<String, Bitmap> myMarkersHash;

private String timeStamp;

private String markerId;

byte[] imageData;

ByteArrayOutputStream baos;

ImageView markerIcon;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.fragment_googlemaps);

myMarkersHash = new HashMap<String, Bitmap>();

setUpMap();

plotMarkers(mMyMarkersArray);

}

private void plotMarkers(ArrayList<MyMarker> markers) {

if (markers.size() > 0) {

for (MyMarker myMarker : markers) {

MarkerOptions markerOption = new MarkerOptions().position(new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude()));

markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.ict_icon));

Marker currentMarker = googleMap.addMarker(markerOption);

mMarkersHashMap.put(currentMarker, myMarker);

CameraPosition cameraPosition = new CameraPosition.Builder().target(

new LatLng(xx.xx, xx.xx)).zoom(9).bearing(0).tilt(80).build();

googleMap.setOnMapLongClickListener(this);

googleMap.setOnMarkerClickListener(this);

googleMap.setOnMapClickListener(this);

googleMap.setOnInfoWindowClickListener(this);

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

googleMap.setMyLocationEnabled(true);

googleMap.getUiSettings().setCompassEnabled(true);

googleMap.getUiSettings().setMyLocationButtonEnabled(true);

googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());

getSupportLoaderManager().initLoader(0, null, this);

}

}

}

private void setUpMap() {

if (googleMap == null) {

googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

if (googleMap != null) {

googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

@Override

public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker) {

marker.showInfoWindow();

return true;

}

});

} else

Toast.makeText(getApplicationContext(), "Unable to create Maps", Toast.LENGTH_SHORT).show();

}

}

public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

public MarkerInfoWindowAdapter() {

}

@Override

public View getInfoWindow(Marker marker) {

return null;

}

@Override

public View getInfoContents(Marker marker) {

View v = getLayoutInflater().inflate(R.layout.infowindow_layout, null);

markerIcon = (ImageView) v.findViewById(R.id.marker_icon);

Bitmap bitmap = myMarkersHash.get(marker.getId());

markerIcon.setImageBitmap(bitmap);

return v;

}

}

@Override

public boolean onMarkerClick(final Marker marker) {

return false;

}

@Override

public void onMapClick(LatLng point) {

}

@Override

public void onMapLongClick(LatLng point) {

thePoint = point;

drawMarker(point);

ContentValues contentValues = new ContentValues();

contentValues.put(LocationsDB.FIELD_LAT, point.latitude);

contentValues.put(LocationsDB.FIELD_LNG, point.longitude);

contentValues.put(LocationsDB.FIELD_ZOOM, googleMap.getCameraPosition().zoom);

contentValues.put(LocationsDB.FIELD_IMAGE, imageData = baos.toByteArray());

contentValues.put(LocationsDB.FIELD_HASH, myMarkersHash.toString());

LocationInsertTask insertTask = new LocationInsertTask();

insertTask.execute(contentValues);

Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

File imagesFolder = new File(Environment.getExternalStorageDirectory(), "My Folder");

imagesFolder.mkdirs();

image = new File(imagesFolder.getPath(), "My__" + timeStamp + ".jpg");

fileUri = Uri.fromFile(image);

imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

startActivityForResult(imageIntent, TAKE_PICTURE);

}

private void drawMarker(LatLng point) {

Marker marker = googleMap.addMarker(new MarkerOptions()

.position(thePoint));

markerId = marker.getId();

}

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {

try {

GetImageThumbnail getImageThumbnail = new GetImageThumbnail();

bitmap = getImageThumbnail.getThumbnail(fileUri, this);

} catch (FileNotFoundException e1) {

e1.printStackTrace();

} catch (IOException e1) {

e1.printStackTrace();

}

ExifInterface exif = null;

try {

exif = new ExifInterface(image.getAbsolutePath());

} catch (IOException e) {

e.printStackTrace();

}

int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);

if (orientation != -1) {

switch (orientation) {

case ExifInterface.ORIENTATION_ROTATE_90:

rotate = 90;

break;

case ExifInterface.ORIENTATION_ROTATE_180:

rotate = 180;

break;

case ExifInterface.ORIENTATION_ROTATE_270:

rotate = 270;

break;

default:

rotate = 0;

break;

}

}

Matrix matrix = new Matrix();

matrix.postRotate(rotate);

bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

baos = new ByteArrayOutputStream();

bitmap.compress(CompressFormat.JPEG, 100, baos);

imageData = baos.toByteArray();

myMarkersHash.put(markerId, bitmap);

}

}

@Override

public void onSaveInstanceState(Bundle savedInstanceState) {

super.onSaveInstanceState(savedInstanceState);

savedInstanceState.putParcelable(EXTRA_PLACE, thePoint);

}

@Override

public void onRestoreInstanceState(Bundle savedInstanceState) {

super.onRestoreInstanceState(savedInstanceState);

thePoint = (LatLng) savedInstanceState.getParcelable(EXTRA_PLACE);

}

@Override

public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {

Uri uri = LocationsContentProvider.CONTENT_URI;

return new CursorLoader(this, uri, null, null, null, null);

}

@Override

public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {

int locationCount = 0;

double lat = 0;

double lng = 0;

float zoom = 0;

byte[] imagea = arg1.getBlob(1);

;

float hash = 0;

locationCount = arg1.getCount();

arg1.moveToFirst();

for (int i = 0; i < locationCount; i++) {

lat = arg1.getDouble(arg1.getColumnIndex(LocationsDB.FIELD_LAT));

lng = arg1.getDouble(arg1.getColumnIndex(LocationsDB.FIELD_LNG));

zoom = arg1.getFloat(arg1.getColumnIndex(LocationsDB.FIELD_ZOOM));

imagea = arg1.getBlob(arg1.getColumnIndex(LocationsDB.FIELD_IMAGE));

hash = arg1.getFloat(arg1.getColumnIndex(LocationsDB.FIELD_HASH));

thePoint = new LatLng(lat, lng);

drawMarker(thePoint);

arg1.moveToNext();

}

if (locationCount > 0) {

googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));

googleMap.animateCamera(CameraUpdateFactory.zoomTo(zoom));

bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);

byte[] imagea = arg1.getBlob(1);

markerIcon.setImageBitmap(bitmap);

myMarkersHash.get(hash);

}

}

@Override

public void onLoaderReset(Loader<Cursor> arg0) {

}

class LocationInsertTask extends AsyncTask<ContentValues, Void, Void> {

@Override

protected Void doInBackground(ContentValues... contentValues) {

getContentResolver().insert(LocationsContentProvider.CONTENT_URI, contentValues[0]);

return null;

}

}

private class LocationDeleteTask extends AsyncTask<Void, Void, Void> {

@Override

protected Void doInBackground(Void... params) {

getContentResolver().delete(LocationsContentProvider.CONTENT_URI, null, null);

return null;

}

}

So as you can see this code does not work to save the HashMap and the Bitmap

So could some one please help me with this, or atleast give a tutorial (with something similar to saving bitmap and HashMap in similar circumstances that what i am trying to do.

PLEASE can some one help! :-(

I have been struggling for the last week with this and have read and studied alot of forums and examples, but none is similar to what i want to achieve?

(Sorry for the long question and lots of code)

PS Once i can get this to work, I want to post it here on SO to help others that are trying to achieve the same thing (I am sure there are a lot of people trying to do this)

分享给朋友:
您可能感兴趣的文章:
随机阅读: