on my main activity screen, I have a button which takes me to another screen. but when I click that my app crashes and I get an error.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.app.appname/com.app.appname.view}:
java.lang.NullPointerException
The blue underline is at view.java at this line:
ArrayList spinnerArrayList =
bundle.getIntegerArrayList("arraylist");
Here is my full view.java code:
public class view extends AppCompatActivity {
private LinearLayout mLinearLayout;
private ArrayList<SearchableSpinner> mSpinners;
private List<AppCompatButton> mButtons = new ArrayList<>();
private List<CheckBox> mCheckboxes = new ArrayList<>();
private List<TextView> mTextviews = new ArrayList<>();
private List<EditText> mEdittexts = new ArrayList<>();
private List<View> mViews = new ArrayList<>();
private Map<String, String> numberItemValues = new HashMap<>();
List<String> itemList = new ArrayList<>();
private Spinner spinner;
private TextView textview;
private CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GlobalClass globalClass = (GlobalClass) this.getApplicationContext();
textview = findViewById(R.id.textview);
checkbox = findViewById(R.id.checkbox);
ArrayList<String> items = new ArrayList<>();
items.add(String.valueOf(mSpinners)); // add you selected item
globalClass.setItems(items);
mSpinners = new ArrayList<>();
mLinearLayout = findViewById(R.id.my_linearLayout);
findViewById(R.id.my_linearLayout).requestFocus();
Intent gotIntent = getIntent();
Bundle bundle = getIntent().getBundleExtra("extraBundle");
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
//creating a for loop, to create the number of spinners in the spinnerarray list size
for(int i = 0; i < spinnerArrayList.size(); i++) {
final Spinner spinner = makeSpinner();
mLinearLayout.addView(spinner);
final View newView = makeView();
//Add a new view
mLinearLayout.addView(newView);
mViews.add(newView);
final EditText newEdittext = makeEdittext();
mLinearLayout.addView(newEdittext);
mEdittexts.add(newEdittext);
final CheckBox newCheckbox = makeCheckbox();
mLinearLayout.addView(newCheckbox);
//TODO add checkbox to your list
mCheckboxes.add(newCheckbox);
final TextView newTextview = makeTextview();
mLinearLayout.addView(newTextview);
mTextviews.add(newTextview);
newCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// makes the set disappear when checkbox is ticked.
newCheckbox.setVisibility(View.VISIBLE);
spinner.setVisibility(View.VISIBLE);
newView.setVisibility(View.VISIBLE);
newEdittext.setVisibility(View.VISIBLE);
newTextview.setVisibility(View.VISIBLE);
//textview.setVisibility(View.VISIBLE);
newCheckbox.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newCheckbox.setVisibility(View.GONE);
}
});
spinner.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
spinner.setVisibility(View.GONE);
}
});
newView.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newView.setVisibility(View.GONE);
}
});
newEdittext.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newEdittext.setVisibility(View.GONE);
}
});
newTextview.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newTextview.setVisibility(View.GONE);
}
});
}
});
//TODO Add the spinner on item selected listener to get selected items
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String currentItem = itemList.get(position);
String aisleNumber = numberItemValues.get(currentItem);
//TODO you can use the above aisle number to add to your text view
//mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
newTextview.setText(aisleNumber);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// code here
}
});
final int listSize = mViews.size();
//code for deleting the said item.
newView.setOnClickListener(new View.OnClickListener() {
//start
#Override
public void onClick(View view) {
//when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.
final View.OnClickListener context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(view.this);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
if (listSize > 0) {
mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
mSpinners.get(listSize - 1).setVisibility(View.GONE);
mViews.get(listSize - 1).setVisibility(View.GONE);
mTextviews.get(listSize - 1).setVisibility(View.GONE);
mEdittexts.get(listSize - 1).setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
//setting spinner selection values
int positionOfSpinner = spinnerArrayList.get(i);
spinner.setSelection(positionOfSpinner);
}
//code for the add button to add more items
FloatingActionButton floatingActionButton =
(FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();
spinner = findViewById(R.id.spinner);
mLinearLayout.setVisibility(View.VISIBLE);
// Handle ze click.
final Spinner spinner = makeSpinner();
mLinearLayout.addView(spinner);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) spinner.getLayoutParams();
layoutParams.setMargins(5, 100, 10, 0); //top 70
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
layoutParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80
layoutParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240
spinner.setLayoutParams(layoutParams);
final View newView = makeView();
//Add a new view
mLinearLayout.addView(newView);
mViews.add(newView);
final EditText newEdittext = makeEdittext();
mLinearLayout.addView(newEdittext);
mEdittexts.add(newEdittext);
final int listSize = mViews.size();
//code for deleting the said item.
//code for deleting the said item.
newView.setOnClickListener(new View.OnClickListener() {
//start
#Override
public void onClick(View view) {
//when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.
final View.OnClickListener context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(view.this);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
//final int listSize = mViews.size();
if (listSize > 0) {
mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
mSpinners.get(listSize - 1).setVisibility(View.GONE);
mViews.get(listSize - 1).setVisibility(View.GONE);
mTextviews.get(listSize - 1).setVisibility(View.GONE);
mEdittexts.get(listSize - 1).setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
//Add a new checkbox
final CheckBox newCheckbox = makeCheckbox();
mLinearLayout.addView(newCheckbox);
//TODO add checkbox to your list
mCheckboxes.add(newCheckbox);
newCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// makes the set disappear when checkbox is ticked.
newCheckbox.setVisibility(View.VISIBLE);
spinner.setVisibility(View.VISIBLE);
newView.setVisibility(View.VISIBLE);
newEdittext.setVisibility(View.VISIBLE);
//textview.setVisibility(View.VISIBLE);
newCheckbox.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newCheckbox.setVisibility(View.GONE);
}
});
spinner.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
spinner.setVisibility(View.GONE);
}
});
newView.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newView.setVisibility(View.GONE);
}
});
newEdittext.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newEdittext.setVisibility(View.GONE);
}
});
/* textview.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
textview.setVisibility(View.GONE);
}
});*/
}
});
final TextView newTextview = makeTextview();
mLinearLayout.addView(newTextview);
mTextviews.add(newTextview);
//TODO Add the spinner on item selected listener to get selected items
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String currentItem = itemList.get(position);
String aisleNumber = numberItemValues.get(currentItem);
//TODO you can use the above aisle number to add to your text view
//mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
newTextview.setText(aisleNumber);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// code here
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent startSettingsActivity = new Intent(this, settings.class);
startActivity(startSettingsActivity);
//start the settings activity here.
return true;
}
/* else if (id == R.id.action_delete) {
for(int j=0; j<mCheckboxes.size(); j++){
mCheckboxes.get(j).setVisibility(View.GONE);
}
for(int j=0; j<mSpinners.size(); j++){
mSpinners.get(j).setVisibility(View.GONE);
}
for(int j=0; j<mViews.size(); j++){
mViews.get(j).setVisibility(View.GONE);
}
for(int j=0; j<mTextviews.size(); j++){
mTextviews.get(j).setVisibility(View.GONE);
}
for(int j=0; j<mEdittexts.size(); j++){
mEdittexts.get(j).setVisibility(View.GONE);
}
Toast.makeText(getBaseContext(), "List removed.", Toast.LENGTH_SHORT).show();
return true;
}*/
else if (id ==R.id.action_help) {
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Help");
builder.setMessage("To use this app, first go to Create your Shopping List.\n" +
"Here, you can add items to your list. Once you have added all items, you can click the menu at the top right corner (or if it doesnt appear press your menu button beside your home button on your device, then click View your List.\n" +
"This will take you to the screen where you can view you shopping list with the items in aisle order to make your shop much easier.\n" +
"You can still add items at this point. Press the white background of each item to delete the item if you wish.");
// add a button
builder.setPositiveButton("OK", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
//use a relative layout and specify which ones are to layout_toRightOf and layout_below
//DUPLICATING ITEMS WHEN FAB IS PRESSED//
private CheckBox makeCheckbox() {
//Create new Checkbox
CheckBox checkbox = new CheckBox(this);
// Setup layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
//setup relative layout for the positioning of the objects
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams((int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)), (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)));
relativeParams.addRule(RelativeLayout.RIGHT_OF, R.id.textview);
checkbox.setLayoutParams(relativeParams);
// RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(relativeParams.addRule(RelativeLayout.RIGHT_OF, R.id.textview));
checkbox.setLayoutParams(layoutParams);
return checkbox;
}
private TextView makeTextview() {
//create new textview
TextView textview = new TextView(this);
//setup layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(layoutParams);
textview.setTextSize(30);
return textview;
}
private EditText makeEdittext() {
//create new edittext
EditText edittext = new EditText(this);
//setup layout
final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(50, 50); // Width , height
edittext.setLayoutParams(lparams);
edittext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
edittext.setHint("qty");
return edittext;
}
private View makeView() {
//create new View
View view = new View(this);
view.setBackgroundColor(Color.parseColor("#ffffff"));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100);
new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, 50);
//LinearLayout.LayoutParams.MATCH_PARENT,
// LinearLayout.LayoutParams.WRAP_CONTENT);
view.setClickable(true);
view.setLayoutParams(layoutParams);
//setup layout
return view;
}
private Spinner makeSpinner() {
//opens csv
InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
//TODO I made this variable global, declared it at the very top of this file
itemList = csvFile.read();
//Create new spinner
// SearchableSpinner spinner = (SearchableSpinner) new Spinner(this, Spinner.MODE_DROPDOWN);
SearchableSpinner spinner = new SearchableSpinner(this);
// Setup layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
spinner.setLayoutParams(layoutParams);
MyListAdapter adapter = new MyListAdapter(this, R.layout.listrow, R.id.txtid, itemList);
spinner.setAdapter(adapter);
//Add it to your list of spinners so you can retrieve their data when you click the getSpinner button
mSpinners.add(spinner);
return spinner;
}
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
//TODO I edited this part so that you'd add the values in our new hash map variable
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}}
the create.java intent part
//takes the size of the list of spinners, for reference
ArrayList<Integer> spinnerList = new ArrayList<>();
for(int i = 0; i < mSpinners.size(); i++) {
spinnerList.add(mSpinners.get(i).getSelectedItemPosition());
}
Bundle newBundle = new Bundle();
newBundle.putIntegerArrayList("arraylist", spinnerList);
Intent newIntent = new Intent(create.this, viewscreen.class);
newIntent.putExtra("extraBundle", newBundle);
Can you use put arraylist value like
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);
And get arraylist value use like below code
Bundle extras = getIntent().getExtras();
extras.getParcelableArrayList("arraylist");
Check codes in main activity button click method, ensure put bundle and data correctly.
and in view activity, suggest writing like this:
Bundle bundle = getIntent().getBundleExtra("extraBundle");
if (bundle!=null) {
if(bundle.containsKey("arraylist") {
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
//do something
}
} else {
//log error info
}
Intent gotIntent = getIntent();
Bundle bundle = getIntent().getBundleExtra("extraBundle");
please print bundle. because the bundle is null then an exception is created
for example:-
send data:-
String[] _string=new String[2];
_string[0]="MONDAY";
_string[1]="TUESDAY";
Intent _intent = new Intent(this, second.class);
Bundle bundle = new Bundle();
_intent .putExtra("strings", myStrings);
_intent .putExtras(bundle);
startActivity(_intent );
receive data:-
Intent i = getIntent();
Bundle extras=i.getExtras();
if(extras != null) //this line is necessary for getting any value
{
String[] _Values = i.getStringArrayExtra("strings");
Toast.makeText(this, "value="+_Values [0]+""+_Values [1], Toast.LENGTH_SHORT).show();
}
Try checking for null value. Maybe the intent is null or the bundle you passed into it is null
Intent gotIntent = getIntent();
if ((gotIntent != null) && (gotIntent.getBundleExtra("extraBundle") != null)) {
Bundle bundle = gotIntent.getBundleExtra("extraBundle");
if(bundle.containsKey("arraylist") {
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
}
}
Try getting the bundle as shown below:-
Intent gotIntent = getIntent();
Bundle bundle = gotIntent.getExtras();
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
The methodgetBundleExtra("String") gets the bundle named String. While getExtras() gets a bundle with all of the items placed into the array.Place your bundle with putExtra(Bundle bundle, String tag) , so that the getBundleExtra(String tag) will return that value.
To check for null ,
if(gotIntent != null && gotIntent.hasExtra("bundleExtras")){
Bundle bundle = gotIntent.getExtras();
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
}
Make sure you have initialise your activity in your manifest
and use directly like this
ArrayList<Integer> list = getIntent.getIntegerArrayListExtra("")
I have an application with a listview and a button on screen that opens a dialog box. Dialog box has one EditText field where user can input text and click Add. onClickListener for Add button makes a async call and passes text to api. Problem is EditText value is not being saved. I cant even get it to show in the Log. Im sure Im missing something simple. Your help is imprecated. Here is the code.
SignInActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Log.v("SignInActivity","Activity has began");
final DancerAdapter adapter = new DancerAdapter(this,oneDancerArrayList,1);
Log.v("SignInActivity","DancerAdapter");
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
getGirlList();
nameInput = (EditText) findViewById(R.id.cr_room_name);
loginDancer = (Button) findViewById(R.id.addDancer);
loginDancer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment newFragment = new AddDancerDialog();
newFragment.show(getFragmentManager(), "newDancer");
}
});
static public class AddDancerDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(R.layout.signin_dialog);
LayoutInflater inflater = LayoutInflater.from(getContext());
final View dialogview = inflater.inflate(R.layout.signin_dialog, null);
//final EditText dancerName = (EditText)dialogview.findViewById(R.id.etDancerName);
builder.setMessage("Login New Dancer")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final ProgressBar newProgress = (ProgressBar)dialogview.findViewById(R.id.progressBar);
final EditText dancerName = (EditText)dialogview.findViewById(R.id.etDancerName);
String nameSubmit = dancerName.getText().toString();
Log.v("SignInActivity-Dialog",nameSubmit);
newProgress.setVisibility(View.VISIBLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("action", "addDancer");
params.put("name",nameSubmit);
Log.v("SignInActivity-Dialog", "Add Dancer Function");
Log.v("SignInActivity-Dialog",dancerName.getText().toString());
client.post("http://peekatu.com/apiweb/girlList.php", params,
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.v("response", response);
responseString2 = response;
//parseDancerList(response);
Log.v("SignInActivity",response);
}
#Override
public void onFailure(Throwable error, String content) {
Log.v("response", "response failed network error");
//waitncall(true);
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
}
Problem is here:
Here you set a view to dialog
builder.setView(R.layout.signin_dialog);
Then, you search a EditText in this view:
LayoutInflater inflater = LayoutInflater.from(getContext());
final View dialogview = inflater.inflate(R.layout.signin_dialog, null);
final EditText dancerName = (EditText)dialogview.findViewById(R.id.etDancerName);
That dialogView was inflated but it is not the view that was added to
dialog. They are different..
I think you can fix as follows:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = LayoutInflater.from(getContext());
final View dialogview = inflater.inflate(R.layout.signin_dialog, null);
builder.setView(dialogview);
...
}
I'm just trying to show an android Dialog but my activity crash every times.
i want to show a dialog which contains 2 EditText fields and 2 buttons.
I'm trying like this, what am i doing wrong or may be there is an easiest way to do that?
public class OsmRoadTaskActivity extends Activity {
Button Chercher, Annuler;
EditText startpoint, endpoint;
Context ctx;
#SuppressLint("CutPasteId")
#SuppressWarnings("unused")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this.getApplicationContext();
setContentView(R.layout.activity_main);
Chercher = (Button) findViewById(R.id.chercher);
Annuler = (Button) findViewById(R.id.annuler);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final AlertDialog alertd = alert.create();
alert.setTitle("Itineraire");
LayoutInflater inflater = this.getLayoutInflater();
View layout = inflater.inflate(R.layout.activity_main, null, false);
/*
* final EditText startpoint = new EditText(OsmRoadTaskActivity.this);
* LinearLayout.LayoutParams lp = new
* LinearLayout.LayoutParams(LinearLayout
* .LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
* startpoint.setLayoutParams(lp); alert.setView(startpoint);
*/
// final EditText startpoint =
// (EditText)layout.findViewById(R.id.endpoint);
final EditText startpoint = new EditText(this);
final EditText endpoint = (EditText) layout.findViewById(R.id.endpoint);
alert.setView(endpoint);
alert.setView(startpoint);
alert.setView(layout);
alert.setView(Annuler);
alert.setView(Chercher);
alert.setPositiveButton("Chercher",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new OsmRoadTask(ctx, startpoint.getText(), endpoint
.getText()).execute();
}
});
alert.setNegativeButton("Annuler",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
alertd.dismiss();
}
});
alert.show();
}
}
Create the AlertDialog object after initializing the builder.
public class OsmRoadTaskActivity extends Activity {
Button Chercher, Annuler;
EditText startpoint, endpoint;
Context ctx;
#SuppressLint("CutPasteId")
#SuppressWarnings("unused")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this.getApplicationContext();
setContentView(R.layout.activity_main);
Chercher = (Button) findViewById(R.id.chercher);
Annuler = (Button) findViewById(R.id.annuler);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Itineraire");
LayoutInflater inflater = this.getLayoutInflater();
View layout = inflater.inflate(R.layout.activity_main, null, false);
/*
* final EditText startpoint = new EditText(OsmRoadTaskActivity.this);
* LinearLayout.LayoutParams lp = new
* LinearLayout.LayoutParams(LinearLayout
* .LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
* startpoint.setLayoutParams(lp); alert.setView(startpoint);
*/
// final EditText startpoint =
// (EditText)layout.findViewById(R.id.endpoint);
final EditText startpoint = new EditText(this);
final EditText endpoint = (EditText) layout.findViewById(R.id.endpoint);
alert.setView(endpoint);
alert.setView(startpoint);
alert.setView(layout);
alert.setView(Annuler);
alert.setView(Chercher);
alert.setPositiveButton("Chercher",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new OsmRoadTask(ctx, startpoint.getText(), endpoint
.getText()).execute();
}
});
alert.setNegativeButton("Annuler",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
alertd.dismiss();
}
});
final AlertDialog alertd = alert.create();
alertd.show();
}
}
I want to display a popupWindow in android
I did the following:
public class MyPopUp extends PopupWindow {
private View view;
private Context context;
public MyPopUp (Context context)
{
super(context);
this.context = context;
View myView = new myView(context);
this.setContentView(myView );
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
}
public void showPopUp(){
view = new View(context);
this.showAtLocation(view, Gravity.CENTER, 0, 0);
}
}
There is an exception on this line
this.showAtLocation(view, Gravity.CENTER, 0, 0);
02-02 09:13:31.456: ERROR/AndroidRuntime(458): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.popup.mypopup/com.popup.mypopup.Android_2_Activity}: java.lang.NullPointerException
when showPopUp is called
try this
public MyPopUp (Context context){
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custome_dialog);
Button dialogCancel = (Button) dialog
.findViewById(R.id.btnCancelPassword);
Button dialogSubmit = (Button) dialog
.findViewById(R.id.btnSubmitPassword);
dialogSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialogCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
Build a dialog I'd like add a listener, but the app crashes.What is wrong?
private void Info(){
textview = (TextView) findViewById(R.id.textView1);
LayoutInflater li = LayoutInflater.from(this);
View view = li.inflate(R.layout.info, null);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view).create().show();
buttonInfo = (Button)findViewById(R.id.buttonInfo);
buttonInfo.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
}
});
replace
buttonInfo = (Button) view.findViewById(R.id.buttonInfo);
by
buttonInfo = (Button) findViewById(R.id.buttonInfo);
final code
private void Info(){
textview = (TextView) findViewById(R.id.textView1);
LayoutInflater li = LayoutInflater.from(this);
View view = li.inflate(R.layout.info, null);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view).create().show();
buttonInfo = (Button) view.findViewById(R.id.buttonInfo);
buttonInfo.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
}
});
I guess that the button is inside your dialog's layout.
If it's the case, try to replace
buttonInfo = (Button)findViewById(R.id.buttonInfo);
by
buttonInfo = (Button) view.findViewById(R.id.buttonInfo);
And you need to store the created AlertDialog (instead of the Builder) if you want to dismiss it after:
final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).show();
buttonInfo = (Button) findViewById(R.id.buttonInfo);
buttonInfo.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
dialog.dismiss();
}
});