I am having an issue where I can not sort out the NullPointerException (NPE) that I am getting.
Here is my MainActivity code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
String bccode = result.getContents();
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Intent sendBarCode= new Intent(MainActivity.this, showdata.class);
sendBarCode.putExtra("barccode", bccode);
startActivity(sendBarCode);
startActivity(new Intent(MainActivity.this, showdata.class));
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
And my class that receives it showdata.class:
public String barcode = getIntent().getStringExtra("barccode");
The exact error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
This particular NPE has me a bit perplexed as I have followed all the instructions I can find online.
So, you're calling startActivity twice, once with the data and once with a new Intent which will not have any data..
Protect from NPE
final Intent intent = getIntent();
if (intent != null) {
...
}
else {
Log.d(TAG, "No intent");
}
TRY This out in the showdata class.
public String barcode = null;
Intent i = getIntent();
barcode =i.getStringExtra("barccode");
Related
I am new to Android and I am making an Battery Alert Application in which their is a point where user select Ringtone and i save the Path of that Ringtone in Shared Preference as a string and getting that ringtone in my Service class in Media player. I am Getting the Path in Toast but still i am having null object reference in my MediaPlayer Object i don't understand what i am doing Wrong. Here my Code
This is My class where i am calling my RingtoneManager
final Uri currentTone=
RingtoneManager.getActualDefaultRingtoneUri(Setting.this,
RingtoneManager.TYPE_ALARM);
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentTone);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
startActivityForResult(intent, 999);`
And then calling it onActivityResult Method and saving the Path in Shared Preference the Path in Toast look like this "internal/audio/media/39"
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 999 && resultCode == RESULT_OK) {
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
Toast.makeText(Setting.this, "" + uri.getPath(), Toast.LENGTH_SHORT).show();
SharedPreferences tune2 = getSharedPreferences("tuneforlow", 0);
SharedPreferences.Editor editortune2 = tune2.edit();
editortune2.putString("lowpath", uri.getPath().toString());
editortune2.commit();
}`
After that calling the Shared Preference in my Service Class
public static MediaPlayer alertsound;
public void onCreate() {
super.onCreate();
SharedPreferences t2 =getSharedPreferences("tuneforlow", Activity.MODE_PRIVATE);
String tune2 = t2.getString("lowpath","");
Toast.makeText(this, ""+tune2, Toast.LENGTH_SHORT).show();
Uri url = Uri.parse(tune2);
if(tune2.equals("")) {
Toast.makeText(this, "Not " +url, Toast.LENGTH_SHORT).show();
alertsound = MediaPlayer.create(getApplicationContext(), Settings.System.CONTENT_URI);
}else{
Toast.makeText(this, "yes" +url, Toast.LENGTH_SHORT).show();
alertsound = MediaPlayer.create(getApplicationContext(), url);
}
alertsound.setLooping(true);
}`
I am Getting the Error in alertsound as null object reference but i am getting the path in Toast.
This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
((ImageView) findViewById(R.id.quick_start_cropped_image)).setImageURI(result.getUri());
Toast.makeText(
this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG)
.show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
When I take a picture my app crashes. The exception on my phone is:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=203, result=-1, data=Intent { act=inline-
data (has extras) }} to activity
{com.example.michael.matcalc/com.example.michael.matcalc.Crop}:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri
com.theartofdev.edmodo.cropper.CropImage$ActivityResult.getUri()' on a
null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4355)
...
I think that something goes wrong with the data. It crashes at this line:
((ImageView) findViewById(R.id.quick_start_cropped_image)).setImageURI(result.getUri());
The library I use is this: https://github.com/ArthurHub/Android-Image-Cropper
I would appreciate if somebody could help me.
This is because you're incorrectly using the library. You need to use the following code:
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
instead of:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
It is because when you're calling Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); you're not specifically tell the Crop library to handle the image.
I have tried a couple of different solutions already given but none works as everything seems to work fine in another activity that I am returning a result from, here is the code.
My Main activity where City activity is called:
//this method gets called on a button click and it works as other activity shows up
public void getCity(View v){
Intent intent = new Intent(getApplicationContext(), City.class);
startActivityForResult(intent,1);
}
//receiving the data the first data is ok but the second one is null although doing the same thing in both files
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode == RESULT_OK && data != null && requestCode==0){
initializeUI(data.getExtras());
}
if(resultCode == RESULT_OK && data != null && requestCode==1){
//data is null here
}
super.onActivityResult(requestCode, resultCode, data);
}
My City Activity
public void addInput(View v){
Bundle bundle = new Bundle();
EditText cityBox = (EditText) findViewById(R.id.cityInput);
String cityName = cityBox.getText().toString();
Intent resultIntent = new Intent();
try {
EditText longBox = (EditText) findViewById(R.id.longitudeInput);
String longitude = longBox.getText().toString();
double longi = Double.parseDouble(longitude);
bundle.putDouble("LONGITUDE", longi);
EditText latBox = (EditText) findViewById(R.id.latitudeInput);
String latitude = latBox.getText().toString();
double lati = Double.parseDouble(latitude);
bundle.putDouble("LATITUDE", lati);
} catch (NumberFormatException e){
}
bundle.putString("CITY_NAME", cityName);
resultIntent.putExtra("DATA",bundle);
setResult(RESULT_OK, resultIntent);
finish(); //calling finish just in case tried without finish aswell
onBackPressed(); //calling onBackPressed tried without it as well doesn't work
}
Any help would be appreciated.
try this:
Then, in B, I do:
Intent intent = getIntent();
intent.putExtra("Date",dateSelected);
setResult(RESULT_OK, intent);
finish();
And, in A:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode==RESULT_OK && requestCode==1){
Bundle MBuddle = data.getExtras();
String MMessage = MBuddle .getString("Date");
}
}
the problem i have found in your code is use of wrong requestCode you are passing 1 as result code in startActivityForResult and in onActivityResult you are checking requestCode==0 means intializeUI etc. All you need to do is use this below code.
if(resultCode == RESULT_OK && data != null && requestCode==1){
//everything works fine
initializeUI(data.getExtras());
}
hope this will help you.
I recently faced same issue in my case. What i was doing wrong was that i was using startActivity() by mistake with startActivityForResult() then in child activity i was calling onBackPress() and finish() before setting the result. I can suggest you that you make sure you set the result before finish() the activity and make sure you're starting activity with startActivityForResult().
Here is snippet from my code.
setResult(RESULT_OK, getIntent().putExtra("country", "some result"));
And i made sure the above written code get excuted before onBackPressed() and onFinish() and it worked for me.
Hope this will help you.
I am having some issues with ZXing's barcode scanner in my android application. I asked a question here yesterday that explains a null pointer error that I was having. The issue was solved and just showed that the cursor wasnt retrieving any information back.
My issues is that I know query is correct and I know the code is correct because I have tested it out without the scanner separately and it all works fine. Is it possible that I am calling to the database wrong in the barcode scanner intent or is there a certain way that I should be doing it?
Any help or guidance would be great!
onActivity Result
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
//get the extras that are returned from the intent
barcode_number = intent.getStringExtra("SCAN_RESULT");
String bNumber = barcode_number.toString();
//Code to add scanned item to DB, needs barcode data before can be ruin
final Cursor barInformation = adapter.barcodeInfo(barcode_number);
barInformation.moveToFirst();
String itemName = barInformation.getString(barInformation.getColumnIndex("barcode_item_name"));
Toast toast = Toast.makeText(this, "Barcode Number:" + itemName ,Toast.LENGTH_SHORT);
toast.show();
}
}
}
Query
public Cursor barcodeInfo(String number){
// Safe check to make sure db and number is not null
if(db == null || number == null){
return null;
}
return db.rawQuery("select _id, barcode_item_name, barcode_measurement, barcode_unit from barcode where barcode_number = ?", new String[]{number});
}
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference
02-12 11:15:07.544 12808-12808/com.example.rory.prototypev2 E/AndroidRuntime: at com.example.rory.prototypev2.DBMain.barcodeInfo(DBMain.java:437)
02-12 11:15:07.544 12808-12808/com.example.rory.prototypev2 E/AndroidRuntime: at com.example.rory.prototypev2.scanner.onActivityResult(scanner.java:77)
Try like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE: {
if (resultCode != RESULT_CANCELED) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
String strData = scanResult.getContents(); // use this
} else {
Toast.makeText(this, "Error message", Toast.LENGTH_LONG).show();
}
break;
}
}
}
I have fixed the issue. My problem was that I wasnt opening the database before I was calling the functions and thus the function was a null object. The correct code is as below.
adapter.open(); // I was missing this line
Cursor c = adapter.barcodeInfo(bNumber);
c.moveToPosition(-1);
while(c.moveToNext())
{
name = c.getString(c.getColumnIndex("barcode_item_name"));
measurement = c.getInt(c.getColumnIndex("barcode_measurement"));
unit = c.getString(c.getColumnIndex("barcode_unit"));
Toast toast = Toast.makeText(this, "Adding" + name + "to Kitchen", Toast.LENGTH_SHORT);
toast.show();
}
I have an object called Contact which contains an arraylist of type Transactions.
I pass the selected contact (from a listview in activity1) to activity2 using intent and startActivityForResult.
In the second activity I create a new Transaction object and add it to the passed Contact's arraylist of transactions, return it using setResult and retrieve it using onActivityResult
My problem is that the original Contact object doesn't get the new Transaction.
Sending intent:
Intent intent = new Intent(this, AddTransactionActivity.class);
intent.putExtra("contact", selectedContact);
startActivityForResult(intent, 1);
recieving intent:
Bundle b = getIntent().getExtras();
if(b != null) {
recievedContact = (Contact)b.getParcelable("contact");
}
Sending back result:
recievedContact.addTransaction(transaction);
Intent intent = new Intent(this, Contacts_activity.class);
intent.putExtra("contact", recievedContact);
setResult(Activity.RESULT_OK, intent);
finish();
startActivity(intent);
Retrieving result:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1) {
if(resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
if(b != null) {
selectedContact = (Contact)b.getParcelable("contact");
}
} else if (resultCode == 0) {
}
}
}
edit: I put a Log.v("result test", "success"); in onActivityResult(), it doesnt show in logcat so it seems my onActivityResult method is never called.