我对 android studio 很陌生,对 Java 不太熟悉。
我的问题是,如何使用我在 MainActivity 中创建的函数到 SurfaceView 中?
我会更好地解释我的情况:用户拍照。然后它被保存(我的函数 onPictureTaken)。但用户必须输入图像的名称,以便使用其标识符而不是 currentTimeMillis 进行注册。
在 MainActivity 中,我检索在 EditText 中输入的内容,但我不知道如何传达这两件事。
我如何获取文本:
public void getText()
{
EditText text = (EditText)findViewById(R.id.imageName);
String nomPhoto = text.getText().toString();
if (nomPhoto.trim().equals("")) {
Toast.makeText(this, "Enter the name of the file", Toast.LENGTH_SHORT).show();
return;
}
}
如何保存图片:
@Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
photo = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
//Save pic
if(photo!=null)
{
File file=new File(Environment.getExternalStorageDirectory()+"/dir");
if(!file.isDirectory())
{
file.mkdir();
}
//User must enter the pic name
file = new File(Environment.getExternalStorageDirectory()+"/dir",System.currentTimeMillis()+".jpg");
try
{
FileOutputStream fileOutputStream=new FileOutputStream(file);
photo.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
fileOutputStream.flush();
System.out.println(file);
fileOutputStream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
System.out.println("Pic taken");
monTimer mt=new monTimer();
maCamera.release();
maCamera=null;
mt.start();
}
我尝试了这个,但我遇到了 Java PointerNullException
@Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
photo = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
//Enregistrer photo sur téléphone
if(photo!=null)
{
File file=new File(Environment.getExternalStorageDirectory()+"/dir");
if(!file.isDirectory())
{
file.mkdir();
}
MainActivity obj = new MainActivity();
String tv = obj.storePhotoName();
file = new File(Environment.getExternalStorageDirectory()+"/dir",tv+".jpg");
也许它与处理程序有关,但我真的不知道
谢谢!
最佳答案
您可以通过Intent
将数据从一个 Activity 发送到另一个 Activity
Intent nextActivity = new Intent(getApplicationContext(), nextActivityName.class);
nextActivity.putExtra("key", "data");
startActivity(nextActivity);
现在在下一个 Activity 中,您可以获得此数据
Intent i = getIntent();
String str = i.getStringExtra("key");
确保您在 getStringExtra
方法中使用的 key
值与在 putExtra
方法中传递数据时使用的值相同。
关于java - MainActivity 和 SurfaceView 之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48629602/