Blank Screen showing up after Image Selected from Gallery - android

I am trying to get an image into the ImageView but whenever I click a picture on the Gallery the app shows a blank screen and closes down.
This ImageView is in a fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_auction_add, container, false);
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
dateTimeAction(v);
return v;
}
private void imageSelectAction(View v) {
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_image = v.findViewById(R.id.auction_add_imageView);
choosePicture();
}
private void choosePicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
if (data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
auction_add_image.setImageURI(selectedImageUri);
}
}
}
}
The Inital Declaration
public class auction_add extends Fragment {
private static final int SELECT_PICTURE = 10;
private static final int PERMISSION_CODE = 11;
ImageButton auction_add_imageViewButton;
//References to all Auction Add Page EditText
EditText auction_add_itemNameTxt;
EditText auction_add_descriptionTxt;
EditText auction_add_initialPriceTxt;
EditText auction_add_startTimeTxt;
EditText auction_add_endTimeTxt;
//Reference to ImageView
private ImageView auction_add_image;
final Calendar myCalendar = Calendar.getInstance();
Would Appreciate the help thanks!
Edit:
Followed is the error on the Run tab of Android Studio
W/System: A resource failed to call close.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.projectcrest, PID: 5618
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=242868079, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:31 flg=0x1 }} to activity {com.example.projectcrest/com.example.projectcrest.pages.LandingPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at com.example.projectcrest.fragments.auction_add.onActivityResult(auction_add.java:155)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2905)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2885)
at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:377)
at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:336)
at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:624)
at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
at android.app.Activity.dispatchActivityResult(Activity.java:8310)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 5618 SIG: 9

By looking into the exception it seems that the App is crashing in #onActivityResult function at line auction_add_image.setImageURI(selectedImageUri); due to NPE (Null Pointer Exception). This expection/crash is caused since the auction_add_image object has null value instead of an ImageView.
After taking an close look into your code, I think the issue has occured due to following code:
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
Note that in #onClick function you are passing view v on which you are going to perform the #findViewById operation. Here the passed view v refers to the auction_add_imageViewButton instead of the v you have captured above.
I would suggest to modify the code as below (just rename the v variable in #onClick function):
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View buttonView) {
imageSelectAction(v);
}
});
This way the variable name collision could be avoided and the error would be resolved.
Also, in case this does not solve your problem, then please check whether the #findViewById is returning an ImageView instead of null. In case the Id provided to #findViewById is not present on the screen or in the child views of view (on which the #findViewById) is being performed then the #findViewById will return null value.
Also, check whether you have assigned null value to auction_add_image in anywhere your code.

Related

Android - referencing a string in strings.xml in a .java file

i have this code in MainActivity.java:
String passName = new String(getString(R.string.name));
where name is a string in strings.xml:
<string name="name">My name</string>
it does not give me an error, but the app keeps crashing, how can i do this properly?
basically i want to save my name as a string variable in MainActivity.java, but store the actual text in strings.xml
i originally had:
String passName = new String("my name");
and i was able to successfully pass it to the second activity, but i want the text to be stored in strings.xml, not the .java file
edit: i have provided more of my code for context:
public class MainActivity extends AppCompatActivity {
Button button;
//code that will eventually point to my name in strings.xml
String passName = new String("my name");
//String passName = getResources().getString(R.string.name);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code that senses when the button is clicked
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//code that executes when the button is clicked
Toast.makeText(getApplicationContext(),"Moving to second activity...",Toast.LENGTH_SHORT).show();
//code that passes my name to the second activity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", passName);
startActivity(intent);
}
});
}
}
as for a crash log, there doesn't seem to be one. when i launch the app it opens and then immediately closes again.
the message it gives me is this:
01/19 15:21:11: Launching 'app' on Pixel 4 XL API 30 (test).
Install successfully finished in 388 ms.
$ adb shell am start -n "my.name.n0000.lab_n0000/my.name.n0000.lab_n0000.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
edit: i have added the proper logcat dialogue:
2023-01-19 15:32:41.587 7562-7562/my.name.n00000.lab_n00000 E/AndroidRuntime: FATAL EXCEPTION: main
Process: my.name.n00000.lab_n00000, PID: 7562
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{my.name.n00000.lab_n00000/my.name.n00000.lab_n00000.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:97)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:134)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:128)
at androidx.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:612)
at my.name.n00000.lab_n00000.MainActivity.<init>(MainActivity.java:17)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2023-01-19 15:32:41.615 7562-7562/my.name.n00000.lab_n00000 I/Process: Sending signal. PID: 7562 SIG: 9
There is a lifecycle involved when creating activities. Some things should not be accessed before the onCreate method is called. So you should be able to declare passName prior and then inside onCreate, you can initialise it.
public class MainActivity extends AppCompatActivity {
Button button;
String passName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code that senses when the button is clicked
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//code that executes when the button is clicked
Toast.makeText(getApplicationContext(),"Moving to second activity...",Toast.LENGTH_SHORT).show();
//code that passes my name to the second activity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", passName);
startActivity(intent);
}
});
passName = getResources().getString(R.string.name);
}
}
You can read more about the activity lifecycle here
And in particular in this paragraph, it talks about instantiating class scope variables.
For example, your implementation of onCreate() might bind data to lists, associate the activity with a ViewModel, and instantiate some class-scope variables.

Nullpointer on getIntent().getExtras();

code in RegisterActivity1:
Bundle extras = new Bundle();
...
case R.id.continue_button:
extras.putString("email",eMail_eingabe.getText().toString().trim());
extras.putString("pw1", passwort_1_eingabe.getText().toString().trim());
extras.putString("pw2", passwort_2_eingabe.getText().toString().trim());
i.putExtras(extras);
this.startActivity(i);
break;
code in RegisterActivity2:
Bundle extras = getIntent().getExtras(); //Nullpointer oocurs here
semail = extras.getString("email");
spw1 = extras.getString("pw1");
spw2 = extras.getString("pw2");
I'm trying to pass email and password from activity 1 to activity 2, but nothing I have tried so far seems to be working. I always get a Nullpointer Exception here:
Bundle extras = getIntent().getExtras();
Any tips on how to fix this?
Here is the full method from Activity1, in case it has something to do with the override method...
#Override
public void onClick(View view) {
String email = eMail_eingabe.getText().toString().trim();
String password = passwort_1_eingabe.getText().toString().trim();
if (eMail_eingabe.getText().toString().isEmpty()) {
//eMail_eingabe.setError("Bitte email eingeben");
eMail_eingabe.setText("Bitte email eingeben");
eMail_eingabe.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
eMail_eingabe.setError("Bitte eine gültige E-Mail eingeben");
eMail_eingabe.requestFocus();
return;
}
if (password.length() < 6) {
passwort_1_eingabe.setError("Bitte mindestens 6 Zeichen eingeben");
passwort_1_eingabe.requestFocus();
return;
} else if (passwort_1_eingabe.getText().toString().isEmpty()) {
passwort_1_eingabe.setError("Bitte passwort eingeben");
passwort_1_eingabe.requestFocus();
return;
} else if (passwort_2_eingabe.getText().toString().isEmpty()) {
passwort_2_eingabe.setError("Bitte passwort eingeben");
passwort_2_eingabe.requestFocus();
return;
}
if (!passwort_1_eingabe.getText().toString().equalsIgnoreCase(passwort_2_eingabe.getText().toString())) {
passwort_2_eingabe.setError("Passwort stimmt nicht überein");
passwort_2_eingabe.requestFocus();
return;
}
switch (view.getId()) {
case R.id.continue_button:
extras.putString("email", eMail_eingabe.getText().toString().trim());
extras.putString("pw1", passwort_1_eingabe.getText().toString().trim());
extras.putString("pw2", passwort_2_eingabe.getText().toString().trim());
i.putExtras(extras);
this.startActivity(i);
break;
}
}
Exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hoimi, PID: 7812
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hoimi/com.example.hoimi.student.Register2_Student_Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.example.hoimi.student.Register2_Student_Activity.<init>(Register2_Student_Activity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3340)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199) 
at android.os.Handler.dispatchMessage(Handler.java:112) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7625) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 
Bundle extras = getIntent().getExtras();
had to be called in the onCreate method, I called it before so it didn't work.
Someone gave the right answer, but deleted his post later (because he got 2 downvotes??)
Anyways, thanks alot.
Problem is not because of getExtras() its because of getIntent(). Check your getIntent() with null and use further.
Your code should be something like
if(getIntent() != null) {
Bundle extras = getIntent().getExtras(); //Nullpointer oocurs here
semail = extras.getString("email");
spw1 = extras.getString("pw1");
spw2 = extras.getString("pw2");
}
Good luck.
when you call getIntent(), it returns the intent that you created in previous Activity.
public Intent getIntent ()
Return the intent that started this activity.
Activity documentation
so in second activity, your intent is null
in onCreate initiate your intent

I am getting an error when I delete a row from room database

In my application I have a detail view of that opens whenever user clicks on a recyclerview item.
in the detail view there is a delete button that deletes item by id.
whenever I delete a row of data I get the below error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.almaneakhaled.coutdeplat, PID: 19844
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.almaneakhaled.coutdeplat.rawmaterialsdata.RawMaterialsEntity.getRawMaterialName()' on a null object reference
at com.almaneakhaled.coutdeplat.itemview.MaterialItemView.lambda$onCreate$0$MaterialItemView(MaterialItemView.java:81)
at com.almaneakhaled.coutdeplat.itemview.-$$Lambda$MaterialItemView$_tUa0kDVoDvYdVg5rSyCjITsVqg.onChanged(Unknown Source:4)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:149)
at androidx.lifecycle.LiveData.setValue(LiveData.java:307)
at androidx.lifecycle.LiveData$1.run(LiveData.java:91)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
This my code for the detail activity:
public class MaterialItemView extends AppCompatActivity {
//define textviews to load strings from room for the intended ID
TextView mMaterialName;
TextView mMaterialBrand;
TextView mMaterialWeight;
TextView mMaterialUnitWeight;
TextView mMaterialUnitCost;
TextView mMaterialCostPerGm;
TextView mMaterialAvailableQuantity;
TextView mMaterialTotalCost;
TextView mMaterialSupplierName;
TextView mMaterialSupplierEmail;
TextView mMaterialSupplierPhone;
int mId;
RawMaterialViewModel mMaterialViewModel;
private static final int UPDATE_MATERIAL_ACTIVITY_REQUEST_CODE = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.material_item_view);
//connect each textView with its corresponding ID in the Layout material_item_view
mMaterialName = findViewById(R.id.material_name_view);
mMaterialBrand = findViewById(R.id.material_brand_view);
mMaterialWeight = findViewById(R.id.material_weight_view);
mMaterialUnitWeight = findViewById(R.id.material_weight_unit_view);
mMaterialUnitCost = findViewById(R.id.material_unit_cost_view);
mMaterialCostPerGm = findViewById(R.id.material_cost_per_gm_view);
mMaterialAvailableQuantity = findViewById(R.id.material_quantity_view);
mMaterialTotalCost = findViewById(R.id.material_total_cost_view);
mMaterialSupplierName = findViewById(R.id.material_supplier_name_view);
mMaterialSupplierEmail = findViewById(R.id.material_supplier_email_view);
mMaterialSupplierPhone = findViewById(R.id.material_supplier_phone_view);
//get the intent sent from the previous activity
Intent intent = getIntent();
//check if the intent is null
if (intent != null && intent.hasExtra("ID")) {
mId = intent.getIntExtra("ID", -1);
// TODO: get material details based on material id
// Set up the materialViewModel
mMaterialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
mMaterialViewModel.findMaterialById(mId).observe(this, rawMaterialsEntity -> {
mMaterialName.setText(rawMaterialsEntity.getRawMaterialName());
mMaterialBrand.setText(rawMaterialsEntity.getRawMaterialBrand());
mMaterialWeight.setText(String.valueOf(rawMaterialsEntity.getUnitWeight()));
mMaterialUnitWeight.setText(rawMaterialsEntity.getUOM());
mMaterialUnitCost.setText(String.valueOf(rawMaterialsEntity.getUnitCost()));
mMaterialCostPerGm.setText(String.valueOf(rawMaterialsEntity.getCostPerGm()));
mMaterialAvailableQuantity.setText(String.valueOf(rawMaterialsEntity.getRawMaterialQuantity()));
mMaterialTotalCost.setText(String.valueOf(rawMaterialsEntity.getTotalCost()));
mMaterialSupplierName.setText(rawMaterialsEntity.getSupplierName());
mMaterialSupplierEmail.setText(rawMaterialsEntity.getSupplierEmail());
mMaterialSupplierPhone.setText(rawMaterialsEntity.getSupplierPhone());
});
}
else {
mMaterialName.setText(R.string.material_name_view_na);
mMaterialBrand.setText(R.string.material_brand_view_na);
mMaterialWeight.setText(R.string.material_weight_view_na);
mMaterialUnitWeight.setText(R.string.material_uom_view_na);
mMaterialUnitCost.setText(R.string.material_cost_view_na);
mMaterialCostPerGm.setText(R.string.material_cost_per_gm_view_na);
mMaterialAvailableQuantity.setText(R.string.material_quantity_view_na);
mMaterialTotalCost.setText(R.string.material_total_cost_view_na);
mMaterialSupplierName.setText(R.string.material_s_name_view_na);
mMaterialSupplierEmail.setText(R.string.material_s_email_view_na);
mMaterialSupplierPhone.setText(R.string.material_s_phone_view_na);
}
//define the control buttons
ImageButton cancelButton = findViewById(R.id.materials_cancel_button_view);
ImageButton editButton = findViewById(R.id.materials_edit_button);
ImageButton deleteButton = findViewById(R.id.materials_delete_button);
ImageButton emailButton = findViewById(R.id.materials_email_button);
ImageButton callButton = findViewById(R.id.materials_call_button);
cancelButton.setOnClickListener(view -> finish());
editButton.setOnClickListener(view -> {
Intent intent1 = new Intent(getBaseContext() ,RawMaterialsEditor.class);
intent1.putExtra("ID", mId);
startActivityForResult(intent1, UPDATE_MATERIAL_ACTIVITY_REQUEST_CODE);
});
deleteButton.setOnClickListener(view -> {
mMaterialViewModel.deleteMaterial(mId);
Intent intent1 = new Intent(this, MainActivity.class);
finish();
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UPDATE_MATERIAL_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
RawMaterialsEntity material = new RawMaterialsEntity(Integer.valueOf(data.
getStringExtra(RawMaterialsEditor.EXTRA_REPLY_id)) ,data
.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_BRAND),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_WEIGHT)),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_COST)),
Integer.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_QUANTITY)),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_EMAIL),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_PHONE),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_UOM));
mMaterialViewModel.updateMaterial(material);
mMaterialViewModel.costPerGm();
mMaterialViewModel.totalCost();
}
else {
Toast.makeText(
this.getApplicationContext(),
R.string.editor_insert_rm_failed,
Toast.LENGTH_LONG).show();
}
}
}
Kindly help me in fixing this error, I debugged the app it looks like that if ended the viewModel lifecycle manually it will fix the problem, but I do not know how to do that.
Solved the error by wrapping textviews data loaders with an if statement to check if the entity object is not null.
mMaterialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
mMaterialViewModel.findMaterialById(mId).observe(this, rawMaterialsEntity -> {
if (rawMaterialsEntity != null) {
mMaterialName.setText(rawMaterialsEntity.getRawMaterialName());
mMaterialBrand.setText(rawMaterialsEntity.getRawMaterialBrand());
mMaterialWeight.setText(String.valueOf(rawMaterialsEntity.getUnitWeight()));
mMaterialUnitWeight.setText(rawMaterialsEntity.getUOM());
mMaterialUnitCost.setText(String.valueOf(rawMaterialsEntity.getUnitCost()));
mMaterialCostPerGm.setText(String.valueOf(rawMaterialsEntity.getCostPerGm()));
mMaterialAvailableQuantity.setText(String.valueOf(rawMaterialsEntity.getRawMaterialQuantity()));
mMaterialTotalCost.setText(String.valueOf(rawMaterialsEntity.getTotalCost()));
mMaterialSupplierName.setText(rawMaterialsEntity.getSupplierName());
mMaterialSupplierEmail.setText(rawMaterialsEntity.getSupplierEmail());
mMaterialSupplierPhone.setText(rawMaterialsEntity.getSupplierPhone());
}

Set an image on imageview using arraylist strings and strings

Brief Description: This is a speech to text app, if the word they spoken is also a word in the database file then it will also have an image of that word spoken.
So I attempted to use imageResource to set the image but it failed, as it is using an ArrayList and a String for the first part of the imageResoruce function. which is assumed to be causing the error message as it crashes when i open the application.
Main.java
public class Main extends Activity {
private static final int VR_Request = 100;
private final String pathname = ".png"; //path name of an image file stored in the drawable folder
TextView speechInput;
TextView matchOrNot;
String[] wordBank; //
ArrayList<String> wordBANK;
ImageButton speechBtn;
ImageView image;
Resources res = getResources();
int resID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reverse_pictionary);
speechInput = (TextView) findViewById(R.id.english_word);
matchOrNot = (TextView) findViewById(R.id.matchOrNot);
wordBank = getResources().getStringArray(R.array.Words);
speechBtn = (ImageButton) findViewById(R.id.mic_pic_button);
wordBANK = new ArrayList<String>(Arrays.asList(wordBank));
image = (ImageView) findViewById(R.id.imageOfword);
}
public void onMic(View view) {
promptSpeechInput();
}
public void promptSpeechInput() {
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == VR_Request && resultCode == RESULT_OK) {
ArrayList<String> result = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(wordBANK.contains(result.get(0).toLowerCase())){
speechInput.setText(result.get(0).toUpperCase());
matchOrNot.setText("MATCH");
resID = res.getIdentifier(result.get(0).toLowerCase()+pathname, "drawable", getPackageName());
image.setImageResource(resID);
}else {
speechInput.setText(result.get(0));
matchOrNot.setText("NO MATCH");
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
RunTime Error Message:
08-10 21:07:37.678 2344-2344/com.example.speechtotext E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.speechtotext, PID: 2344
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.speechtotext/com.example.speechtotext.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at com.example.speechtotext.Main.<init>(Main.java:38)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Any Ideas? Thank you in advance!
Move the code :
Resources res = getResources();
into the onCreate() method.
You can not use getResources() before the activity created.

NullPointerException when user choose the background from gallery [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Good Day, I would like to allow user to change background in my app. Try to make it, but face with that problem:
12-09 06:22:15.874 20413-20413/com.vadimsleonovs.horoscope E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vadimsleonovs.horoscope, PID: 20413
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/20 flg=0x1 }} to activity {com.vadimsleonovs.horoscope/com.vadimsleonovs.horoscope.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setBackground(android.graphics.drawable.Drawable)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setBackground(android.graphics.drawable.Drawable)' on a null object reference
at com.vadimsleonovs.horoscope.activities.SettingsActivity.onActivityResult(SettingsActivity.java:76)
at android.app.Activity.dispatchActivityResult(Activity.java:6135)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582) 
at android.app.ActivityThread.access$1300(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
The code is that:
public class SettingsActivity extends AppCompatActivity {
Button mBcgBtn;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mBcgBtn = (Button) findViewById(R.id.bcg_clr_btn);
mBcgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}catch(NullPointerException e){
e.printStackTrace();
}
LinearLayout mHomeLayout = (LinearLayout) findViewById(R.id.activity_home);
LinearLayout mDetailsPageLayout = (LinearLayout) findViewById(R.id.activity_details_page);
Drawable d = new BitmapDrawable(getResources(), BitmapFactory.decodeFile(picturePath));
mHomeLayout.setBackground(d);
}
}
}
Also, I added write external storage permission, and this code works perfectly in "blank project", but in my project not working at all.
It says mHomeLayout is null. ie, There is no LinearLayout with id activity_home in activity_settings layout.
So what you need to do is save the selected drawable path in storage preferences from Settings Activity. And load it when you open the other activity which has the Linearlayout with id activity_home. And then set it as it's background.
I hope that's your problem.

Categories

Resources