Reputation: 169
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)
Upvotes: 0
Views: 93
Reputation: 8562
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
.
In your case bundle
is null
that means you are trying to access the String
from a null
object. So it's always better habit to check if getIntent().getExtras()
is null
before accessing to prevent crashing like
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");
...
}
}
Upvotes: 1
Reputation: 3439
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();
}
}
});
}
}
Upvotes: 0
Reputation: 7479
You are calling startActivity
twice, once before and once after putting 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. 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
). 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.
Upvotes: 2