在两个活动之间使用相机图像处理意图并将其传递给 Google Maps API 上的标记不起作用
Posted
技术标签:
【中文标题】在两个活动之间使用相机图像处理意图并将其传递给 Google Maps API 上的标记不起作用【英文标题】:Processing intent with camera image between two Activities and passing it to marker on Google Maps API does not work 【发布时间】:2018-02-26 08:13:50 【问题描述】:我是 android 新手,正在开发 Android 应用程序。该应用程序有两个活动:一个编辑活动和一个地图活动。
在Edit Activity中,用户可以在Android手机上输入数据并拍照,效果很好。另一个活动是地图活动,其中显示地图上的标记。
地图上的标记包含一个位图,它也可以正常工作。不工作的部分是相机图片放置在标记而不是位图图形上的部分。
来自相机的图像显示在 Edit Activity 的图像视图中,效果很好。
不工作的部分是将相机意图传递给其他活动并将意图的内容放在标记上。
这里是编辑活动(很多代码被注释掉了):
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.R.attr.data;
import static android.R.attr.id;
import static android.content.ContentValues.TAG;
import static android.provider.MediaStore.ACTION_IMAGE_CAPTURE;
public class EditActivity extends Activity
public static int count = 0;
static final int REQUEST_TAKE_PHOTO = 1;
private static final String KEY_MARKER_ID = "id";
private static final String KEY_MARKER_TITLE = "title";
private static final String KEY_MARKER_DATE = "date";
private static final String KEY_MARKER_LOC = "location";
private static final String KEY_MARKER_LAT = "latlng";
private static final String KEY_MARKER_NAME = "name";
private static final String KEY_MARKER_PIC = "picture";
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.editactivity);
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
helper.getReadableDatabase();
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.btnCapture);
photoButton.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
);
final LatLng latlng = getIntent().getParcelableExtra("location");
//final MarkerImage markerImage = getIntent().getParcelableExtra("data");
final EditText title = (EditText) findViewById(R.id.title);
final EditText date = (EditText) findViewById(R.id.date);
final EditText location = (EditText) findViewById(R.id.location);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
final EditText name = (EditText) findViewById(R.id.name);
Button button = (Button) findViewById(R.id.save);
final Button camerabutton = (Button) findViewById(R.id.btnCapture);
final Intent getCameraImage = new Intent(ACTION_IMAGE_CAPTURE);
button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(final View view)
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
MarkerOptions marker = new MarkerOptions().position(latlng)
.icon(BitmapDescriptorFactory.fromBitmap(bmp)
);
if (title.getText() != null)
marker.title(title.getText().toString());
if (date.getText() != null)
marker.getPosition();
Log.d("String Value of Marker:", String.valueOf(marker));
Intent resultIntent = new Intent();
resultIntent.putExtra("marker", marker);
resultIntent.putExtra("picture", getCameraImage);
Log.d("Längen-und Breitengrad:", String.valueOf(marker));
setResult(Activity.RESULT_OK, resultIntent);
finish();
);
// Here, we are making a folder named picFolder to store
// pics taken by the camera using this application.
//final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
//File newdir = new File(dir);
//newdir.mkdirs();
//final Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
/*if (getCameraImage.resolveActivity(getPackageManager()) != null)
// Create the File where the photo should go
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try
// The user might already exist in the database (i.e. the same user created multiple posts).
//long markerId = addOrUpdateMarker(marker.user);
ContentValues values = new ContentValues();
values.put(KEY_MARKER_ID, id);
values.put(KEY_MARKER_TITLE, String.valueOf(title));
values.put(KEY_MARKER_NAME, String.valueOf(name));
values.put(KEY_MARKER_LOC, String.valueOf(location));
values.put(KEY_MARKER_DATE, String.valueOf(date));
// Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
db.insertOrThrow(TABLE_MARKERS, null, values);
db.setTransactionSuccessful();
catch (Exception e)
Log.d(TAG, "Error while trying to add post to database");
finally
db.endTransaction();
/*File photoFile = null;
try
photoFile = createImageFile();
catch (IOException ex)
// Error occurred while creating the File
// Continue only if the File was successfully created
if (photoFile != null)
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(cameraIntent, REQUEST_TAKE_PHOTO);
/*capture.setOnClickListener(new View.OnClickListener()
public void onClick(View v)
// Here, the counter will be incremented each time, and the
// picture taken by camera will be stored as 1.jpg,2.jpg
// and likewise.
//count++;
//String file = dir+count+".jpg";
//File newfile = new File(file);
//try
// newfile.createNewFile();
//
// catch (IOException e)
//
//
//Uri outputFileUri = Uri.fromFile(newfile);
//cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, REQUEST_TAKE_PHOTO);
);
String mCurrentPhotoPath;
private File createImageFile() throws IOException
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
// ".jpg", /* suffix */
// storageDir /* directory */
//);
// Save a file: path for use with ACTION_VIEW intents
//mCurrentPhotoPath = image.getAbsolutePath();
//return image;
/*@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK)
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
/*if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK)
Log.d("CameraDemo", "Pic saved");
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
这是地图活动:
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import gmbh.webagenten.recycling.PostsDatabaseHelper;
import gmbh.webagenten.recycling.SQLiteSampleActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import static android.content.ContentValues.TAG;
import static gmbh.webagenten.recycling.R.attr.title;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
private GoogleMap mMap;
private static final int EDIT_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState)
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
// Get singleton instance of database
//PostsDatabaseHelper databaseHelper = PostsDatabaseHelper.getInstance((Context) this);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onMapReady(GoogleMap map)
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.id.imageView1);
this.mMap = map;
try
mMap.setMyLocationEnabled(true);
catch (SecurityException e)
LatLng hamburg = new LatLng(53.551085, 9.993682);
mMap.addMarker(new MarkerOptions().position(hamburg).title("Marker in Hamburg")
.icon(BitmapDescriptorFactory.fromBitmap(bmp)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(hamburg));
//PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
//helper.getReadableDatabase();
//Log.d(TAG, "Database in use");
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
@Override
public void onMapClick(final LatLng latLng)
Intent edit = new Intent(MapsActivity.this, EditActivity.class);
edit.putExtra("location", latLng);
Log.d("Längen-und Breitengrad:", String.valueOf(latLng));
MapsActivity.this.startActivityForResult(edit, EDIT_REQUEST);
);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
case (EDIT_REQUEST) :
if (resultCode == Activity.RESULT_OK)
Bundle bundle = data.getExtras();
MarkerOptions markerOptions = data.getParcelableExtra("marker");
MarkerOptions markerImage = data.getParcelableExtra("data");
mMap.addMarker(markerOptions);
//mMap.addMarker(markerImage);
break;
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
/*
@Override
public void onMapReady(GoogleMap googleMap)
mMap = googleMap;
try
mMap.setMyLocationEnabled(true);
catch (SecurityException e)
LatLng hamburg = new LatLng(53.551085, 9.993682);
mMap.addMarker(new MarkerOptions().position(hamburg).title("Marker in Hamburg"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(hamburg));
mMap.setOnMapClickListener(this);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
@Override
public void onMapClick(final LatLng latLng)
Intent edit = new Intent(MapsActivity.this, EditActivity.class);
edit.putExtra("location", latLng);
MapsActivity.this.startActivityForResult(edit, EDIT_REQUEST);
);
*/
XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_
android:layout_
android:background="#222"
android:id="@+id/llMarker">
<ImageView
android:id="@+id/ivMarker"
android:layout_marginTop="5dp"
android:layout_
android:layout_ />
<item>
<ImageView android:id="@+id/imageView1" android:layout_ android:layout_></ImageView>
</item>
</LinearLayout>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical">
<EditText
android:id="@+id/title"
android:layout_
android:layout_
android:hint="Title"
android:inputType="text" />
<EditText
android:id="@+id/date"
android:layout_
android:layout_
android:hint="Date"
android:inputType="date" />
<EditText
android:id="@+id/location"
android:layout_
android:layout_
android:hint="Location"
android:inputType="text" />
<EditText
android:id="@+id/name"
android:layout_
android:layout_
android:hint="Name"
android:inputType="text" />
<Button
android:id="@+id/btnCapture"
android:layout_
android:layout_
android:text="Camera" />
<Button
android:id="@+id/save"
android:layout_
android:layout_
android:text="Save"/>
<ImageView android:id="@+id/imageView1" android:layout_ android:layout_></ImageView>
由于我是 Android 新手,我现在被这个问题困扰了很长时间。任何帮助或提示将不胜感激,谢谢!
【问题讨论】:
【参考方案1】:我了解您的问题。我得到的错误是,您无法将位图获取到下一个活动,您已在编辑活动中将数据设置为图像视图,并且当您打开地图活动时,该数据丢失了,
你需要做的是: 1.将位图从编辑活动传递给地图活动 2.获取位图到地图活动,然后将位图显示到地图上。
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.R.attr.data;
import static android.R.attr.id;
import static android.content.ContentValues.TAG;
import static android.provider.MediaStore.ACTION_IMAGE_CAPTURE;
public class EditActivity extends Activity
public static int count = 0;
static final int REQUEST_TAKE_PHOTO = 1;
private static final String KEY_MARKER_ID = "id";
private static final String KEY_MARKER_TITLE = "title";
private static final String KEY_MARKER_DATE = "date";
private static final String KEY_MARKER_LOC = "location";
private static final String KEY_MARKER_LAT = "latlng";
private static final String KEY_MARKER_NAME = "name";
private static final String KEY_MARKER_PIC = "picture";
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
Bitmap photo;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.editactivity);
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
helper.getReadableDatabase();
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.btnCapture);
photoButton.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
);
final LatLng latlng = getIntent().getParcelableExtra("location");
//final MarkerImage markerImage = getIntent().getParcelableExtra("data");
final EditText title = (EditText) findViewById(R.id.title);
final EditText date = (EditText) findViewById(R.id.date);
final EditText location = (EditText) findViewById(R.id.location);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
final EditText name = (EditText) findViewById(R.id.name);
Button button = (Button) findViewById(R.id.save);
final Button camerabutton = (Button) findViewById(R.id.btnCapture);
final Intent getCameraImage = new Intent(ACTION_IMAGE_CAPTURE);
button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(final View view)
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
MarkerOptions marker = new MarkerOptions().position(latlng)
.icon(BitmapDescriptorFactory.fromBitmap(bmp)
);
if (title.getText() != null)
marker.title(title.getText().toString());
if (date.getText() != null)
marker.getPosition();
Log.d("String Value of Marker:", String.valueOf(marker));
Intent resultIntent = new Intent();
resultIntent.putExtra("marker", marker);
resultIntent.putExtra("picture", getCameraImage);
intent.putExtra("BitmapImage", photo); // passing the bitmap to the next activity . and retrieve it to the next activity
Log.d("Längen-und Breitengrad:", String.valueOf(marker));
setResult(Activity.RESULT_OK, resultIntent);
finish();
);
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
`photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
这里是地图活动
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import gmbh.webagenten.recycling.PostsDatabaseHelper;
import gmbh.webagenten.recycling.SQLiteSampleActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import static android.content.ContentValues.TAG;
import static gmbh.webagenten.recycling.R.attr.title;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
private GoogleMap mMap;
private static final int EDIT_REQUEST = 1;
Bitmap bmp;
@Override
protected void onCreate(Bundle savedInstanceState)
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
// Get singleton instance of database
Intent intent = getIntent();
bmp = (Bitmap) intent.getParcelableExtra("BitmapImage"); // getting the bitmap data from the edit activity.
//PostsDatabaseHelper databaseHelper = PostsDatabaseHelper.getInstance((Context) this);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onMapReady(GoogleMap map)
//Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.id.imageView1);
this.mMap = map;
try
mMap.setMyLocationEnabled(true);
catch (SecurityException e)
LatLng hamburg = new LatLng(53.551085, 9.993682);
mMap.addMarker(new MarkerOptions().position(hamburg).title("Marker in Hamburg")
.icon(BitmapDescriptorFactory.fromBitmap(bmp)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(hamburg));
//PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
//helper.getReadableDatabase();
//Log.d(TAG, "Database in use");
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
@Override
public void onMapClick(final LatLng latLng)
Intent edit = new Intent(MapsActivity.this, EditActivity.class);
edit.putExtra("location", latLng);
Log.d("Längen-und Breitengrad:", String.valueOf(latLng));
MapsActivity.this.startActivityForResult(edit, EDIT_REQUEST);
);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
case (EDIT_REQUEST) :
if (resultCode == Activity.RESULT_OK)
Bundle bundle = data.getExtras();
MarkerOptions markerOptions = data.getParcelableExtra("marker");
MarkerOptions markerImage = data.getParcelableExtra("data");
mMap.addMarker(markerOptions);
//mMap.addMarker(markerImage);
break;
这是更新后的代码,希望对您有所帮助。请检查并告诉我。
【讨论】:
嗨@rajendra,谢谢你的努力 - 但是,代码仍然产生相同的结果,所以它没有按预期工作...... Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon) 应该被相机图像替换,这不起作用。任何进一步的帮助或提示将不胜感激! 嗨,您不必解码位图,而是从编辑活动的意图发送中获取它。意图意图 = getIntent(); bmp = (Bitmap) intent.getParcelableExtra("BitmapImage"); intent.putExtra("BitmapImage", photo); // 将位图传递给下一个活动。并将其检索到下一个活动 感谢您的更新。不幸的是,它不起作用。我收到以下错误消息: java.lang.RuntimeException: 将结果 ResultInfowho=null, request=1, result=-1, data=Intent (has extras) 传递给活动 gmbh.webagenten.recycling/ 失败gmbh.webagenten.recycling.MapsActivity:java.lang.NullPointerException:位图 嗨,我猜你还没有从编辑活动中传递位图数据。以上是关于在两个活动之间使用相机图像处理意图并将其传递给 Google Maps API 上的标记不起作用的主要内容,如果未能解决你的问题,请参考以下文章