[英]return button from the first activity to the second crashes the app
Ok , so this is my problem, I have two activities , both of them are for inputing infromation. 好的,这就是我的问题,我有两个活动,它们都用于输入信息。 the one leads to the other.
一个导致另一个。 when I press the return button from the second activity the app crashes and I don't know why..
当我在第二个活动中按下返回按钮时,应用程序崩溃了,我也不知道为什么。
this is the code for the first activity: 这是第一个活动的代码:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.support.design.widget.Snackbar;
public class Add_Score extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__score);
final Button Next = (Button)findViewById(R.id.buttonNext);
final Intent Add_Comment_Picture = new Intent(this, Add_Comment_Picture.class);
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String score = ((EditText) findViewById(R.id.editText)).getText().toString();
String desc = ((EditText)findViewById(R.id.editTextDesc)).getText().toString();
if(score.compareTo("") != 0 && desc.compareTo("") != 0){
startActivity(Add_Comment_Picture);
Add_Comment_Picture.putExtra("score", score);
Add_Comment_Picture.putExtra("desc" , desc );
startActivity(Add_Comment_Picture);
}
else{
Snackbar.make(v , "Please fill in the score and description" , Snackbar.LENGTH_LONG).show();
}
}
});
}
}
this is the code for the second activity: 这是第二个活动的代码:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Add_Comment_Picture extends AppCompatActivity {
static final int CAM_REQUEST = 1;
static final int RESULT_LOAD_IMAGE = 2;
ImageView imageView;
ImageButton button;
ImageButton buttonGallery;
String mCurrentPhotoPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__comment__picture);
button = (ImageButton) findViewById(R.id.imageButtonCamera);
imageView = (ImageView) findViewById(R.id.imageView);
buttonGallery = (ImageButton) findViewById(R.id.imageButtonGallery_f);
Calendar c = Calendar.getInstance();
String hours = Globals.getTimePadding(c.get(Calendar.HOUR));
String minutes = Globals.getTimePadding(c.get(Calendar.MINUTE));
String time = hours + ":" + minutes;
String value = getIntent().getExtras().getString("score");
String value2 = getIntent().getExtras().getString("desc");
TextView scoreText = (TextView) findViewById(R.id.textViewScore);
scoreText.setText("Score: " + value);
TextView t = (TextView) findViewById(R.id.textViewDatec);
t.setText(time);
TextView descText = (TextView) findViewById(R.id.textViewDesc);
descText.setText(value2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getFile();
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(camera_intent, CAM_REQUEST);
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent_gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent_gallery , RESULT_LOAD_IMAGE);
}
});
}
private String createFileName(){
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return "JPEG_" + timeStamp + "_.jpg";
}
@Override
protected void onStart() {
super.onStart();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasWritePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
int hasReadPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
int hasCameraPermission = checkSelfPermission(Manifest.permission.CAMERA);
List<String> permissions = new ArrayList<String>();
if (hasWritePermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (hasReadPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.CAMERA);
}
if (!permissions.isEmpty()) {
requestPermissions(permissions.toArray(new String[permissions.size()]), 111);
}
}
}
private File getFile() {
File folder = new File("sdcard/data/data/com.yuvaleliav1gmail.foodchain/photos");
if (!folder.exists()) {
folder.mkdir();
}
mCurrentPhotoPath = createFileName();
File image_file = new File(folder,mCurrentPhotoPath);
return image_file;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAM_REQUEST){
copyFile("sdcard/data/data/com.yuvaleliav1gmail.foodchain/photos/" + mCurrentPhotoPath , getFilesDir().toString() + "/" + mCurrentPhotoPath);
File d = new File("sdcard/data/data/com.yuvaleliav1gmail.foodchain/photos/" + mCurrentPhotoPath);
d.delete();
imageView.setImageDrawable(Drawable.createFromPath(getFilesDir().toString() + "/" + mCurrentPhotoPath));
}
if(requestCode == RESULT_LOAD_IMAGE){
if(data != null){
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
mCurrentPhotoPath = createFileName();
copyFile(picturePath, getFilesDir().toString() + "/" + mCurrentPhotoPath);
imageView.setImageDrawable(Drawable.createFromPath(getFilesDir().toString() + "/" + mCurrentPhotoPath));
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 111: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
System.out.println("Permissions --> " + "Permission Granted: " + permissions[i]);
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
System.out.println("Permissions --> " + "Permission Denied: " + permissions[i]);
}
}
}
break;
default: {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
public void copyFile(String path1 , String path2){
InputStream inStream = null;
OutputStream outStream = null;
try{
File file1 =new File(path1);
File file2 =new File(path2);
inStream = new FileInputStream(file1);
outStream = new FileOutputStream(file2); // for override file content
//outStream = new FileOutputStream(file2,<strong>true</strong>); // for append file content
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
if (inStream != null)inStream.close();
if (outStream != null)outStream.close();
System.out.println("File Copied..");
}catch(IOException e){
e.printStackTrace();
}
}
}
this is the logcat when the crush happens: 这是暗恋发生时的日志猫:
05-22 12:46:50.361 8312-8312/com.yuvaleliav1gmail.foodchain E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yuvaleliav1gmail.foodchain, PID: 8312
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yuvaleliav1gmail.foodchain/com.yuvaleliav1gmail.foodchain.Add_Comment_Picture}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.yuvaleliav1gmail.foodchain.Add_Comment_Picture.onCreate(Add_Comment_Picture.java:56)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
You are calling startActivity
twice, once before and once after putting extras. 您要两次调用
startActivity
,一次是在放置Extras之后,一次是在Extras之后。
startActivity(Add_Comment_Picture);
Add_Comment_Picture.putExtra("score", score);
Add_Comment_Picture.putExtra("desc" , desc );
startActivity(Add_Comment_Picture);
This way you're actually starting the activity before you're actually putting extras in the Intent. 通过这种方式,您实际上可以在将其他内容实际放入Intent 之前开始活动。 Just remove the first call and leave it like this:
只需删除第一个电话,然后将其保留为:
Add_Comment_Picture.putExtra("score", score);
Add_Comment_Picture.putExtra("desc" , desc );
startActivity(Add_Comment_Picture);
This is just a piece of advice: It's a general convention to name your variables with a lowercase letter and use camel case ( instead of
Add_Comment_Picture
, you'd call itaddCommentPictureIntent
).这只是一条建议:用小写字母命名变量并使用驼峰式大小写(这不是
Add_Comment_Picture
,而是将其命名为addCommentPictureIntent
)是一种常规约定。 Also concatenating at the end the type it represents is a good way to differentiate the variable when there are many of them.最后,还可以将其表示的类型连接起来,这是区分变量的好方法。 You can read more about conventions online, but they're useful to follow and make the code more readable.
您可以在线阅读有关约定的更多信息,但遵循它们对于使代码更具可读性很有用。
It's NPE
so I suggest once Seeing what-is-a-null-pointer-exception-and-how-do-i-fix-it for better understanding of NPE
. 它是
NPE
因此我建议您一次查看什么是空指针异常以及如何解决它,以更好地了解NPE
。
In your case bundle
is null
that means you are trying to access the String
from a null
object. 在您的情况下,
bundle
为null
意味着您正尝试从null
对象访问String
。 So it's always better habit to check if getIntent().getExtras()
is null
before accessing to prevent crashing like 因此,始终最好习惯在访问之前先检查
getIntent().getExtras()
是否为null
,以防止崩溃
if(getIntent().getExtras() !=null){
String value = getIntent().getExtras().getString("score");
String value2 = getIntent().getExtras().getString("desc");
...
}
OR For advance checking for specific key, you can do like this, 或要预先检查特定密钥,您可以这样做,
Bundle extras = getIntent().getExtras();
if(extras != null){
if (extras.containsKey("score") && extras.containsKey("desc")){
String value = getIntent().getExtras().getString("score");
String value2 = getIntent().getExtras().getString("desc");
...
}
}
use the code bellow( your problem is that you start activity before putting extras): 使用下面的代码(您的问题是您在放入附加内容之前开始活动):
public class Add_Score extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__score);
final Button Next = (Button)findViewById(R.id.buttonNext);
final Intent Add_Comment_Picture = new Intent(this, Add_Comment_Picture.class);
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String score = ((EditText) findViewById(R.id.editText)).getText().toString();
String desc = ((EditText)findViewById(R.id.editTextDesc)).getText().toString();
if(score.compareTo("") != 0 && desc.compareTo("") != 0){
// startActivity(Add_Comment_Picture);
Add_Comment_Picture.putExtra("score", score);
Add_Comment_Picture.putExtra("desc" , desc );
startActivity(Add_Comment_Picture);
}
else{
Snackbar.make(v , "Please fill in the score and description" , Snackbar.LENGTH_LONG).show();
}
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.