clicking button to go to another screen - crashes - android

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("")

Related

Second AlertDialog list item click based on the first Alertdialog list android

In my android app, I need to generate one Alertdialog with a list of Company name. For example Company 1, Company 2, Company 3. Now if the user cllick company 1, he will get second alertdialog which will show some actions. Like Phone Call, Email, etc. Now I have implemented this two alertdialog in my code. But what I want to do, that for each company there should be different Phone number and email adress. So Far I have tried with same number with all the company. But in real in real if user click company 1, he will get the second alert list of action with phone call, email. if he clicks phone option he will see the phone number company 1, if he clicks company 2, he will get alertoption with phone number of company 2. But I am very new in developing area. I know there is something with Mapping topic, by which I can do it easily but I am not getting actually how to proceed with it. My code is like this
public List<CompanyDetail> setCompanydata(){
int n = 3;
private List<CompanyDetail> companyDetailList = new ArrayList<CompanyDetail>(); //modifier private is not allowed here
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>(); //modifier private is not allowed here
for(int i=0;i<n;i++){
private CompanyDetail comD= new CompanyDetail(); //modifier private is not allowed here
comD.setcompanyPhoneNo(companyPhoneno); //cannot resolve problem companyPhone
comD.setcompanyEmail(compnayEmailId);
companyDetailList.add(comD);
companyContactDetail.add(companyname, companyDetailList);//cannot resolve method 'add(?,java util list..
}
return companyContactDetail; //incompatible type
}
private List<CompanyDetail> companyDetailList;
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>();
companyContactDetail = setCompanydata(); //unknown class company contact deatil
private void showFirstDialogwithList() {
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
builder.setCancelable(true);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("Contact");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.company_name);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this.getActivity(), R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(arrayAdapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
showSecondDialogwithList();
}
if (itemPosition == 1) {
alert.dismiss();
showSecondDialogwithList();
}
if (itemPosition == 2) {
alert.dismiss();
showSecondDialogwithList();
}
}
});
}
private void showSecondDialogwithList() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("+1234667");
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if(isPermissionGranted()){
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
My string arrays are
<string-array name="company_name">
<item>company 1</item>
<item>Company 2</item>
<item>Company 3</item>
</string-array>
<!-- AlertDialog way of Contact array -->
<string-array name="contact_way">
<item>Phone Call</item>
<item>Email</item>
</string-array>
<String-array name="phone">
<item>123456</item>
<item>125658</item>
<item>123451</item>
</String-array>
<String-array name="email">
<item>email1</item>
<item>email2</item>
<item>email2</item>
</String-array>
you can pass the position for the item and test it at your function or you can pass it directly :
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alert.dismiss();
showSecondDialogwithList(position);
}
private void showSecondDialogwithList(int position) {
String phoneNumber;
switch (position) {
case 1:
phoneNumber = "123";
break;
case 2:
phoneNumber = "456";
break;
case 3:
phoneNumber = "789"
}
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("+1234667");
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if (isPermissionGranted()) {
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
To go deep in to logic behind that kind of scenario best way to use *HashMap*.
according to your scenario. i change in your code check it out:
public class CompanyDetail{
String companyPhoneNo;
String companyEmail;
public void setcompanyPhoneNo(String phoneNo){
this.companyPhoneNo = phoneNo;
}
public void setcompanyEmail(String Email){
this.companyEmail = Email;
}
public String getcompanyPhoneNo(){
return companyPhoneNo;
}
public String getcompanyEmail(){
return companyEmail;
}
}
public HashMap<String, List<CompanyDetail>> setCompanydata(){
int n = 3;
private List<CompanyDetail> companyDetailList = new ArrayList<CompanyDetail>();
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>();
for(int i=0;i<n;i++){
CompanyDetail comD= new CompanyDetail();
comD.setcompanyPhoneNo(companyPhoneno);
comD.setcompanyEmail(compnayEmailId);
companyDetailList.add(comD);
companyContactDetail.add(companyname, companyDetailList);
}
return companyContactDetail;
}
private List<CompanyDetail> companyDetailList;
private HashMap<String, List<CompanyDetail>> companyContactDetail;
companyContactDetail = setCompanydata();
private void showFirstDialogwithList() {
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
builder.setCancelable(true);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("Contact");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.company_name);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this.getActivity(), R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(arrayAdapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
}
if (itemPosition == 1) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
showSecondDialogwithList();
}
if (itemPosition == 2) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
showSecondDialogwithList();
}
}
});
}
private void showSecondDialogwithList( String companyName, List<CompanyDetail> companyDetail) {
CompanyDetail obj = companyDetail.get(0);
private String companyPhone = obj.getcompanyPhoneNo();
private String companyEmail = obj.getcompanyEmail();
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(companyPhone);
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if(isPermissionGranted()){
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
It's not a good practice to display two dialogs one by one. Of course you can implement it, like described above, but it will be much better to display separated activity(fragment) with the list(ListView, RecyclerView) of companies and click on each item will show the dialog with needed params. It will look better from design side and users experience.

Android insert LinearLayout Views programmatically in OnCreate not showing

i'm trying to add several LinearLayouts with 2 Buttons and one Spinner. If i add this LinearLayout by clicking a button in the activity it works perfect, but if i want the activity to add this like two or three times in calling the method in the onCreate Method, nothing will shown.
Here's my Code:
private void insert() {
ll = new LinearLayout(this);
spinner = new Spinner(this);
ArrayAdapter<CharSequence> adapter;
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Button badd = new Button(this);
badd.setText("+");
Button bdel = new Button(this);
bdel.setText("-");
ll.addView(bdel);
ll.addView(spinner);
ll.addView(badd);
scrollerLL.addView(ll);
}
EDIT:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_config);
dbHelper = new DatabaseHelper(this);
durchflussmenge = new ArrayList<Double>();
bSave = (Button) findViewById(R.id.bSave);
editV = (EditText)findViewById(R.id.editV);
spinnerDruck = (Spinner)findViewById(R.id.spinnerDruck);
editZB = (EditText)findViewById(R.id.editZB);
labelErg = (TextView)findViewById(R.id.labelErg);
addNozzleList = new ArrayList<LinearLayout>();
spinnerDT = (Spinner)findViewById(R.id.spinnerDT);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.dt_entries, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDT.setAdapter(adapter);
spinnerDT.setPrompt("DT auswählen ...");
spinnerDruck.setAdapter(adapterDruck);
bSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status == 0) {
if (!addNozzleList.isEmpty() && !editV.getText().toString().matches("") && !editZB.getText().toString().matches(""))
initiatePopupWindow();
}
}
});
scrollerLL = (LinearLayout)findViewById(R.id.addNozzleLL);
btnAddNoozle = (Button)findViewById(R.id.btnAddNozzle);
btnAddNoozle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insert();
}
});
spinnerDT.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!addNozzleList.isEmpty()) {
int length = scrollerLL.getChildCount();
scrollerLL.removeViews(1, length - 1);
addNozzleList.clear();
durchflussmenge.clear();
labelErg.setText("0.0");
}
if(spinnerDT.getSelectedItem().toString().equals("ATR")) {
String[] field = CreateConfigActivity.this.getResources().getStringArray(R.array.druck_atr);
adapterDruck.clear();
for(int i = 0; i < field.length; i++)
adapterDruck.add(field[i]);
adapterDruck.notifyDataSetChanged();
spinnerDruck.setSelection(0);
Log.d("SpinnerChange", "ATR");
}else{
String[] field = CreateConfigActivity.this.getResources().getStringArray(R.array.druck_iso);
adapterDruck.clear();
for(int i = 0; i < field.length; i++)
adapterDruck.add(field[i]);
adapterDruck.notifyDataSetChanged();
spinnerDruck.setSelection(0);
Log.d("SpinnerChange", "ISO");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Bundle extras = getIntent().getExtras();
if(extras == null) {
status = 0;
}else {
status = 1;
fillFields(extras.getString("NozzleConfigName"));
}
}
private void fillFields(String nozzleConfigName) {
nozzleConfig = dbHelper.getNozzleConfig(nozzleConfigName);
nozzles = dbHelper.getNozzles(nozzleConfig.getId());
if(!nozzleConfig.getType().equals("ISO"))
spinnerDT.setSelection(1);
editV.setText(nozzleConfig.getKmh()+"");
editZB.setText(nozzleConfig.getBreite()+"");
labelErg.setText(nozzleConfig.getAusbringmenge() + "");
int spinnerDruckPosition = adapterDruck.getPosition(nozzleConfig.getDruck()+"");
spinnerDruck.setSelection(spinnerDruckPosition);
for(Nozzle n:nozzles) {
insert();
findViewById(R.id.createConfigRoot).invalidate();
}
}
private void insert() {
ll = new LinearLayout(this);
spinnerNozzle = new Spinner(this);
ArrayAdapter<CharSequence> adapter;
if(spinnerDT.getSelectedItem().toString().equals("ATR")) {
adapter = ArrayAdapter.createFromResource(this, R.array.nozzle_atr, android.R.layout.simple_spinner_item);
}else{
adapter = ArrayAdapter.createFromResource(this, R.array.nozzle_iso, android.R.layout.simple_spinner_item);
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerNozzle.setAdapter(adapter);
Button badd = new Button(this);
badd.setText("+");
Button bdel = new Button(this);
bdel.setText("-");
spinnerNozzle.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!editV.getText().toString().matches("") && !editZB.getText().toString().matches("")) {
//Toast.makeText(getApplicationContext(), "change", Toast.LENGTH_SHORT).show();
if (spinnerNozzle.getSelectedItem().toString().equals("-005") || spinnerNozzle.getSelectedItem().toString().equals("weiss")) {
calculateAusbringmenge(spinnerNozzle.getSelectedItem().toString(), false);
} else {
// vorheriges Element aus ArrayList löschen
calculateAusbringmenge(spinnerNozzle.getSelectedItem().toString(), true);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ll.addView(bdel);
ll.addView(spinnerNozzle);
ll.addView(badd);
scrollerLL.addView(ll);
addNozzleList.add(ll);
badd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout parent = (LinearLayout) v.getParent();
Spinner spinnerValue = (Spinner) parent.getChildAt(1);
copyNozzle(spinnerValue.getSelectedItemPosition());
}
});
bdel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout parent = (LinearLayout) v.getParent();
scrollerLL.removeView(parent);
Log.d("addNozzleList.size()", parent + "");
addNozzleList.remove(addNozzleList.size() - 1);
Log.d("addNozzleList.size()", addNozzleList.size() + "");
Toast.makeText(getApplicationContext(), "dasda", Toast.LENGTH_SHORT).show();
}
});
}
My Code works. The Views were added right but in another method i deleted them directly after the initialization, so my own fail :P
You need to set LayoutParameters to your LinearLayout as well as Buttons.
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
ll..setLayoutParams(params);
and same for buttons.
LayoutParams BtnParams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
badd.setLayoutParams(BtnParams);
bdel.setLayoutParams(BtnParams);
I hope this will help you out.

Remove item from another activity using button

The problem: I want to remove a item from my listview using a button in another activity.
I have tried several kinds of code, but it just doesn't seem to work.
Right know I use serializable to bundle the object to the other activity.
But I don't know how to remove it, from the other activity.
Can anybody help me with that?
Can I use the button from the second activity, in the first activity to delete the item from the listview?
Class A where I got my ListView
public class ListActivity extends Activity {
ListView list;
Button exit;
SimpleAdapter adapter;
final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
#Override``
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
for (int i = 0; i < title.length; i++) {
Map<String, String> datalist = new HashMap<String, String>();
datalist.put("title", title[i]);
datalist.put("subtitle", subtitle[i]);
data.add(datalist);
}
// getDataInList();
adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, new String[] { "title",
"subtitle" }, new int[] { android.R.id.text1,
android.R.id.text2 });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
Class B where I got my accept button.
When I click accept, the item from the listview in Class A should be removed.
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
int requestCode = 1;
SimpleAdapter adapter;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});``
//Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You should not directly remove the item from the view, but from the data displayed in it.
For example if your ListView is displaying items from an ArrayList, just remove the item in the ArrayList from you Activity B, and call myAdapter.notifyDataSetChanged() when back in the Activity A, which contains the adapter.
You can remove items by accessing to the ArrayList or by overriding the remove() method if you have only access to the adapter (assuming your adapter extends ArrayAdapter).
Also, you may have to override usefull Adapter methods like getCount(), getView()...
Thanks to all.
I found another solution thanks to remove row from another activity
Class A
public class ListActivity extends Activity {
ListView list;
Button exit;
static List<ListItems> items = new ArrayList<ListItems>();
public static int deletePos;
static ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
items = new ArrayList<ListItems>();
for (int i = 0; i < title.length; i++) {
ListItems s = new ListItems(title[i], subtitle[i]);
items.add(s);
}
adapter = new ListAdapter(this, android.R.layout.simple_list_item_2,
items);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
deletePos = position;
adapter.notifyDataSetChanged();
startActivity(intent);
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
Class B
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});
// Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int deletePos = ListActivity.deletePos;
ListActivity.items.remove(deletePos);
ListActivity.adapter.notifyDataSetChanged();
finish();
}
});
}
}

Disabling CheckBox in MultiChoiceItems AlertDialog

I have an AlertDialog which it has dynamic items linked to a Cursor from database , it works fine but i wanted to disable user interaction with that because it's an informational dialog , i've disabled my dialog with :
alert.getListView().setEnabled(false);
but the problem is when Items in the list are bigger than the dialog height , because of disabling it's ListView, Scrolling is disabled too and some items doesn't show up, i've tried some links like : Android : How to disable CheckBox in AlertDialog?
with no success. i've also tried :
builder.setMultiChoiceItems(mDBAdapter.instance.getName(SupervisorGuid)
, SyncDBHelper.instance.SentSupervisors(SupervisorGuid),new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if(isChecked==true)
{
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
else
{
((AlertDialog) dialog).getListView().setItemChecked(which, true);
}
}});
AlertDialog alert = builder.create();
Does anybody know a better way to disable the checkboxes without a Custom dialog?
Thanks in Advance.
this may give you some idea...
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
ArrayList<String> arrayList = new ArrayList<String>();
ArrayList<Boolean> selectedList = new ArrayList<Boolean>();
for (int i = 1; i <= 20; i++) {
arrayList.add("" + i);
selectedList.add(i % 2 == 0);
}
builder.setAdapter(new MyAdapter(arrayList, selectedList), null);
builder.show();
}
public static class MyAdapter extends BaseAdapter {
private ArrayList<String> arrayList;
private ArrayList<Boolean> selectedList;
public MyAdapter(ArrayList<String> arrayList,
ArrayList<Boolean> selectedList) {
this.arrayList = arrayList;
this.selectedList = selectedList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getView(parent.getContext(), position);
}
private RelativeLayout getView(Context context, int position) {
RelativeLayout relativeLayout = new RelativeLayout(context);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
relativeLayout.setLayoutParams(params);
TextView textView = new TextView(context);
textView.setText(arrayList.get(position));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
layoutParams.leftMargin = 30;
textView.setLayoutParams(layoutParams);
relativeLayout.addView(textView);
CheckBox checkBox = new CheckBox(context);
layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.rightMargin = 30;
checkBox.setLayoutParams(layoutParams);
checkBox.setClickable(false);
if (selectedList != null) {
checkBox.setChecked(selectedList.get(position));
}
relativeLayout.addView(checkBox);
return relativeLayout;
}
}
I had the same problem and solved it this way:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
...
builder
.setTitle(...)
.setMultiChoiceItems(cursor, IS_CHECKED, LABEL, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
((AlertDialog)dialog).getListView().setItemChecked(which, /* assign here the original boolean value of the item */);
}
})
...
AlertDialog dialog = builder.create();
dialog.show();
In summary, when you click the item in the list, just set its value back to the original boolean value.
you can define your check box value with boolean array
"checkValues" is our boolean array which defines which check box should tick or which not. check below ex.
builder.setMultiChoiceItems(dialogList, checkedValues)
private fun showDialog() {
val dialogList: Array<String> = days
val checkedValues = BooleanArray(days.size)
checkedValues[viewpager.currentItem] = true
val builder: AlertDialog.Builder = AlertDialog.Builder(activity)
builder.setTitle("You can copy"+dialogList[viewpager.currentItem]+" time slot to:")
builder.setMultiChoiceItems(dialogList, checkedValues)
{ dialog, which, isChecked ->
(dialog as AlertDialog).listView.setItemChecked(yourIndex, true)
}.setPositiveButton("OK") { dialog, id ->
dialog.dismiss()
}.setNegativeButton("Cancel") { dialog, id ->
dialog.dismiss()
}.show()
}

Get the position of view in LinearLayout (Android)

A had a custom ListView recently. Then I had to display all the list items without scrollbar. Following the method to place items in LinearLayout I changed my code but I can't bind onClickListener to new layout. In ListView I used position var to determine what view was touched. But in LinearLayout onClick callback hasn't position parameter.
Here is my BasketActivity.class:
package ru.**.**;
public class BasketActivity extends Activity {
ArrayList<Item> items = new ArrayList<Item>();
SQLiteDatabase database;
Map<String, ?> all;
ItemAdapter adapter;
Item item2delete;
View deletingView;
private SharedPreferences settings;
private SharedPreferences settings2;
private Basket basket;
TextView basketSum;
private int position2delete;
private Map<String, ?> all2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basket);
<..cutted..>
settings = getSharedPreferences("basket", 0);
settings2 = getSharedPreferences("price", 0);
basket = new Basket(settings, settings2);
all = basket.getList();
LinearLayout l1 = (LinearLayout) findViewById(R.id.l1);
MyDBAdapter myDBAdapter = new MyDBAdapter(getBaseContext());
myDBAdapter.open();
Cursor itemCursor = myDBAdapter.getItemsInBasket(all);
while (itemCursor.moveToNext()) {
String[] columns = itemCursor.getColumnNames();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < columns.length; i++) {
sb.append(columns[i]);
}
Item item = new Item();
item.setId(itemCursor.getString(0));
item.setArticul(itemCursor.getString(MyDBSchema.ITEM_ARTICUL));
item.setTitle(itemCursor.getString(MyDBSchema.ITEM_TITLE));
item.setPrice(itemCursor.getInt(MyDBSchema.ITEM_PRICE));
item.setPic80(itemCursor.getString(MyDBSchema.ITEM_PIC80));
item.setPic300(itemCursor.getString(MyDBSchema.ITEM_PIC300));
item.setMessage(itemCursor.getString(MyDBSchema.ITEM_MESSAGE));
item.setColor(itemCursor.getString(MyDBSchema.ITEM_COLOR));
item.setColorpos(itemCursor.getString(MyDBSchema.ITEM_COLORPOS));
items.add(item);
}
itemCursor.close();
myDBAdapter.close();
for (int position=0; position<items.size(); position++) {
LayoutInflater inflater = getLayoutInflater();
View v = inflater.inflate(R.layout.list_basket, null);
final Item i = items.get(position);
if (i != null) {
Item ei = (Item) i;
final TextView title = (TextView) v.findViewById(R.id.title);
if (title != null) title.setText(ei.title);
final TextView articul = (TextView) v.findViewById(R.id.articul);
if (articul != null) articul.setText(ei.articul);
TextView payed = (TextView) v.findViewById(R.id.payed);
if (payed != null) payed.setVisibility(TextView.GONE);
TextView status = (TextView) v.findViewById(R.id.status);
if (status != null) status.setVisibility(TextView.GONE);
Context context = getBaseContext();
ProgressBar p = new ProgressBar(context);
p.setIndeterminate(true);
Drawable d = p.getIndeterminateDrawable();
WebImageView wiv = (WebImageView) v.findViewById(R.id.pic80);
wiv.setImageWithURL(context, ei.pic80, d);
final TextView price = (TextView) v.findViewById(R.id.price);
if (price != null) price.setText(ei.price_valid);
final TextView quant = (TextView) v.findViewById(R.id.quant);
if (quant != null) {
int q = (Integer) all.get(ei.articul);
if (q > 1) {
quant.setText("x "+q+" шт.");
}
}
}
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
deletingView = v;
int position = 0; //The order number of the view should be here!
Item item = (Item) items.get(position);
item2delete = item;
position2delete = position;
AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
builder.setMessage(getString(R.string.suredelete))
.setCancelable(false)
.setPositiveButton(getString(R.string.yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BasketActivity.this.removeItem();
deletingView.setVisibility(View.GONE);
}
})
.setNegativeButton(getString(R.string.no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
l1.addView(v);
}
basketSum = (TextView) findViewById(R.id.basketsum);
basketSum.setText(Html.fromHtml(getString(R.string.basketsum) + ": <b>"
+ basket.getBasketPriceValid() + "</b>"));
}
protected void removeItem() {
basket.remove(item2delete);
Context context = getApplicationContext();
CharSequence text = getText(R.string.item_deleted);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
basketSum.setText(Html.fromHtml(getString(R.string.basketsum) + ": <b>"
+ basket.getBasketPriceValid() + "</b>"));
items.remove(position2delete);
}
}
My question is how to get view's position at onClick(View v)?
You can use the View's tag;
for (int position=0; position<items.size(); position++) {
v.setTag(position);
}
and in the onClick(View v)
public void onClick(View v) {
int position = 0;
if (v.getTag() instanceof Integer) {
position = (Integer) v.getTag();
}
}
Can you have
v.setTag(items.get(position).getId();
and then in onClick
public void onClick(View v) {
int id= v.getTag();
}

Categories

Resources