"java.lang.IllegalArgumentException: view must not be null" Program Closes when navigated - android-studio

The app closes whenever I navigate to ProfileActivity.
FATAL EXCEPTION: main Process: hfad.com.hallofmemesprototype, PID:
19092 java.lang.RuntimeException: Unable to start activity
ComponentInfo{hfad.com.hallofmemesprototype/hfad.com.hallofmemesprototype.Profile.ProfileActivity}:
java.lang.IllegalArgumentException: view must not be null
Here's the "ProfileActivity" code.
public class ProfileActivity extends AppCompatActivity {
private static final int ACTIVITY_NUM = 3;
private Context mContext = ProfileActivity.this;
private ProgressBar mProgressBar;
private ImageView profilePhoto;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setupBottomNavigationView();
setupToolbar();
setupActivityWidgets();
setProfileImage();
}
private void setProfileImage(){
String imgURL = "www.androidzone.org/wp-content/uploads/2013/02/android-musical2.jpg";
UniversalImageLoader.setImage( imgURL, profilePhoto, mProgressBar, "https://");
}
private void setupActivityWidgets(){
mProgressBar = findViewById(R.id.profileProgressBar);
mProgressBar.setVisibility(View.GONE);
profilePhoto = findViewById(R.id.profile_photo);
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.profileToolBar);
setSupportActionBar(toolbar);
ImageView profileMenu = findViewById(R.id.profileMenu);
profileMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, AccountSettingsActivity.class);
startActivity(intent);
}
});
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView() {
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.bottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}

You must check that all the views that you are getting using findViewById() really exist into the activity_profile.xml layout.
One or more views doesn´t really exist, and you have a null value gettin the reference.
findViewById(R.id.profileProgressBar);
findViewById(R.id.profile_photo);
findViewById(R.id.profileToolBar);
findViewById(R.id.profileMenu);
findViewById(R.id.bottomNavViewBar);
initially you are not getting any error tryin to find the references of this views because they are really exist but in another layout but not in activity_profile.xml that you are loading via setContentView() in your Activity.

This type of exception rise at the time of the wrong variable declaration and
initialization.
Try this
replace your weighs declare and initialize val with var.
If you have to use java
final TextView helloTextView = (TextView)findViewById(R.id.text_view_id);
For Kotlin
val helloTextView = findViewById(R.id.text_view_id) as TextView
you can refer this link for more details

Related

use Onclick in extends PagerAdapter

Hi I’m trying to create a horizontal slide where each horizontal page will have a button that will call a Dialog but onClick is not working in extends Pageradapter can anyone tell me what I’m doing wrong?
I gave the name onClickApprove to onClick that I want you to call Dialog. This Dialog is calling an Activity with a Ratingbar to make an assessment.
Thank you.
public class SliderAdapterUsado extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
BottomSheetDialog dialog;
Button show;
public SliderAdapterUsado(Context context){
this.context = context;
}
public String[] slide_rota ={
"Titulo1",
"Titulo2"
};
public String[] slide_nome={
"Descrção do titulo 1",
"Descrção do titulo 2"
};
#Override
public int getCount(){
return slide_rota.length;
}
#Override
public boolean isViewFromObject(View view, Object object){
return view == (LinearLayout) object;
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_usados, container, false);
TextView slideHeading = view.findViewById(R.id.slide_rota);
TextView slideDescricao = view.findViewById(R.id.slide_nome);
slideHeading.setText(slide_rota[position]);
slideDescricao.setText(slide_nome[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout)object);
}
public void onClickAvaliar(View view) {
show = view.findViewById(R.id.show);
dialog = new BottomSheetDialog(dialog.getContext());
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog();
dialog.show();
}
});
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
private void createDialog(){
View view = layoutInflater.inflate(R.layout.activity_rating, null, false);
Button FeedBack = view.findViewById(R.id.FeedBack);
FeedBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.setContentView(view);
}
}
Please read the documentation.
Note this in particular (emphasis mine):
To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
The expectation is that the value set on the onClick xml attribute will be a method on the hosting Activity. Yours is in the adapter. That's why it doesn't work.
So either move that method to the hosting activity, or just handle the click event explicitly:
...
TextView slideHeading = view.findViewById(R.id.slide_rota);
TextView slideDescricao = view.findViewById(R.id.slide_nome);
Button slideButton = view.findViewById(R.id.slide_button);
slideButton.setOnClickListener (...)
...

Cannot create dialog inside a fragment

I am trying to create a dialog inside a fragment.when I am trying to press on the button and enter the dialog the app collaspe.
I guess the code is not right can you please help me with that?
Here is my code:
private void openDialog(){
Dialog dialog=new Dialog(getContext());
//AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
LayoutInflater layoutInflater=this.getLayoutInflater();
View custom_dialog=getActivity().getLayoutInflater().inflate(R.layout.geo_dialog,null);
dialog.setContentView(custom_dialog);
// add_geofence_radius= custom_dialog.findViewById(R.id.radius_size);
save_btn=custom_dialog.findViewById(R.id.save_btn);
cancel_btn=custom_dialog.findViewById(R.id.cancel_btn);
/* save_btn.setOnClickListener(new View.OnClickListener() {
#Override
}
});
*/
/*cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
*/
// dialog.setTitle("hello");
dialog.show();
}
The best way to show dialog in android is to use "DialogFragments" since they are aware of the lifecycle of the view it is attached on (ie. fragments/activities).
Here is an examples provided in Android docs:
public class PurchaseConfirmationDialogFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
return new AlertDialog.Builder(requireContext())
.setMessage(getString(R.string.order_confirmation))
.setPositiveButton(getString(R.string.ok), (dialog, which) -> {} )
.create();
}
public static String TAG = "PurchaseConfirmationDialog";
}
To show the dialog use:
new PurchaseConfirmationDialogFragment().show(
getChildFragmentManager(), PurchaseConfirmationDialog.TAG);
For more reference on dialogFragments, checkout : Create a DialogFragment

setLayout not inflating correct xml layout?

been alright so far. I try to use docs or find my issues.
However my mainActivity has 4 buttons. These buttons depending on which view is clicked passes the R.id.button. I pass this value into an intent which Activity2 uses bundle to get id integer. I then setContentView using this.
However im having issues getting correct view to inflate now, it seems like its loading an old layout. My aim is to inflate 3 separate layout on Activity2 depending which button was clicked.
I know my other other button does inflate another activity and get proper xml layout.
Why are my other 3 buttons not inflating on Activity2 properly?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button pizza;
Button hamburger;
Button icecream;
Button history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pizza = findViewById(R.id.buttonPizza);
hamburger = findViewById(R.id.buttonBurger);
icecream = findViewById(R.id.buttonIceCream);
history = findViewById(R.id.buttonHistroy);
pizza.setOnClickListener(this);
hamburger.setOnClickListener(this);
icecream.setOnClickListener(this);
history.setOnClickListener(this);
}
#Override
public void onClick(View v){
int idView = v.getId();
switch(v.getId()) {
case R.id.buttonBurger : startOrderActivity(R.layout.burger_layout);
makeToast(idView);
break;
case R.id.buttonPizza : startOrderActivity(R.layout.pizza_layout);
makeToast(idView);
break;
case R.id.buttonIceCream : startOrderActivity(R.layout.icecream_layout);
makeToast(idView);
break;
case R.id.buttonHistroy : startOrderActivity(R.layout.history_layout);
makeToast(idView);
break;
}
}
private void startOrderActivity(int id){
if(id != R.layout.history_layout) {
Intent intentOrder = new Intent(this, MakeOrderActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
else {
Intent intentOrder = new Intent(this, OrderHistoryActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
}
public void makeToast(int id){
String txt = String.valueOf(id);
Toast newToast = Toast.makeText(getApplicationContext(),txt,Toast.LENGTH_LONG);
newToast.show();
}
}
public class MakeOrderActivity extends AppCompatActivity {
Button placeOrderButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getIntent().getExtras();
int layoutNum = data.getInt("layout");
setContentView(layoutNum);
placeOrderButton = findViewById(R.id.placeOrder);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
public void onCheckboxClicked(View view){
}
}
Answer is to create a View which is created by getInflator.
https://stackoverflow.com/a/17070408/8443090

Activity switch and Async Android

I have 2 activities: MainActivity which is associated with main.xml layout (app "Home" screen) and AboutActivity which is associated with about.xml layout (app "About" screen).
While in AboutActivity, an Async task within MainActivity still tries to access main.xml. My app to stop working as a result.
Is there any way I can?
"pause" the Async task within MainActivity and "resume" them when
the user switches back from AboutActivity
or still access main.xml in the background while in AboutActivity
Additional information:
MainActivity is the launch activity. AboutActivity extends MainActivity. Users can go to "About" screen/ switch to AboutActivity using the option menu.
The Async task within MainActivity put the user's current location into a textview. about.xml only contains static text. AboutActivity does nothing but show about.xml.
AboutActivity:
public class AboutActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
}
}
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
//make asynctask wait for debugger
//android.os.Debug.waitForDebugger();
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d(DEBUG,e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
TextView curLoc = (TextView) findViewById(R.id.CurrentLocation);
curLoc.setText(result);
}
}
}
AsyncTask not pause so we can store the data temporary when task complete and while start background activity than show data on textView.
I've solved the problem. It was a partly a variable scope problem and partly due the fact that I cannot use findViewById() there, it always return null
curLoc is null in onPostExecute in the AsyncTask.
I removed the following:
TextView curLoc = (TextView) findViewById(R.id.CurrentLocation);
and declared curLoc as a attribute of the class MainActivity
private TextView curLoc;
and also put in onCreate()
curLoc = (TextView) findViewById(R.id.CurrentLocation);

How add custom dynamic layout in a dialog box?

i am new to android java programming. I am adding a custom dynamic layout to a dialog box. i have 2 classes , Mainactivity.java and Getval.java
The Mainactivity.java create a dialoge and Getval generates dynamic layout at run time.
Every thing works good but when it tried to call Getval.java's method, it gives an exception. here is the code of both classes.
The g.setval(); in Mainactivity.java cause problem.
:::::Mainactivity.java:::::
public class MainActivity extends Activity {
private Button button;
public Getval g=new Getval();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.buttonShowCustomDialog);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//set up dialog
g.setval();
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.attributewin);
dialog.setTitle("Attribute Window");
dialog.setCancelable(true);
dialog.show();
}
});
::::Getval::::
public class Getval extends Activity{
String names[]={"test","chaeck","kajsdhasj","dlasdig"};
String values[]={"test","chaeck","kajsdhasj","dlasdig"};
String test[]={"Attribut","Value"};
public void setval(){
TableLayout tl = (TableLayout) findViewById(R.id.tly);
Button b=new Button(this);
for (int i = 0; i < names.length; i++) {
//Row
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
//TextViews
TextView tv0 = new TextView(this);
tv0.setText(names[i]);
tv0.setMaxWidth(75);
TextView tv1 = new TextView(this);
tv1.setText(values[i]);
tv1.setMaxWidth(150);
View line = new View(this);
line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
line.setBackgroundColor(Color.BLACK);
//Setting Views
tr.addView(tv0);
tr.addView(tv1);
tl.addView(tr);
tl.addView(line);
}
//Button Row
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
tr.setGravity(0x11);
b.setId(100);
b.setText("Return");
b.setGravity(0x11);
tr.addView(b);
tl.addView(tr);
}
}
Looking over this without seeing your xml or complete code (or exception that is thrown), I would be willing to guess that you are trying to inflate/modify a view (R.id.tly) from an activity other than the one where it was originally inflated from (MainActivity).
Generally speaking, you can't do this without doing some tricks with cross activity handlers or other methods. Perhaps change your code to inflate the views (R.id.tly) in MainActivity (and in your dialog if it is inside of R.layout.attributewin), do your processing in Getval, return them to MainActivity so it can populate the views.
But again, this is just a guess, since I don't see your xml or exception.

Resources