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.
Related
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 am making android app for college. App is about fitness(tracking kcal,workouts...). i have stuck on part where i want to notifyDatasetChange for my adapter. On my Activity i have 2 list views(first is showing exercises and second is showing selected exercises for todays workout). I made easily first ListView to update when user "create" new type of exercise for itself because Arraylist and called from current activity ,but for second ListView i made Dialog in its adapter class and i want on closing that dialog to update ListView. Here is my code and classes:
public class MyWorkoutActivity extends AppCompatActivity {
ListView lv;
ListView lvsess;
Button create;
#Override
public void onBackPressed(){
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_workout);
create=(Button) findViewById(R.id.btn_addexercise);
WorkoutDay workoutDay = SugarRecord.findById(WorkoutDay.class, (long) 1);
List<WorkoutDay> workoutDayArrayList = new ArrayList<>();
if(workoutDay.getWorkouts()!="") {
String[] workouts = workoutDay.getWorkouts().split(":");
String[] sets = workoutDay.getSets().split(":");
String[] reps = workoutDay.getReps().split(":");
String[] kgs = workoutDay.getKgs().split(":");
String[] duration = workoutDay.getDuration().split(":");
for (int i = 0; i < workouts.length; i++) {
workoutDayArrayList.add(new WorkoutDay(workouts[i],sets[i],reps[i],kgs[i],duration[i]));
}
}
final ArrayList<WorkoutDay> ddd = new ArrayList<>();
ddd.addAll(workoutDayArrayList);
List<Exercise> exerciseList = Exercise.listAll(Exercise.class);
final ArrayList<Exercise> exerciseArrayList= new ArrayList<>();
exerciseArrayList.addAll(exerciseList);
lv=(ListView) findViewById(R.id.lv_exercises);
lvsess=(ListView)findViewById(R.id.lv_currentsess);
final SessionAdapter sessionAdapter = new SessionAdapter(this,ddd);
final ExerciseAdapter exerciseAdapter= new ExerciseAdapter (this,exerciseArrayList);
lv.setAdapter(exerciseAdapter);
lvsess.setAdapter(sessionAdapter);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> cathegories = new ArrayList<String>();
cathegories.add("Chest");
cathegories.add("Biceps");
cathegories.add("Triceps");
cathegories.add("Legs");
cathegories.add("Core");
cathegories.add("Abdomens");
cathegories.add("Cardio");
cathegories.add("Free style");
final Dialog addyourown= new Dialog(MyWorkoutActivity.this);
addyourown.setTitle("Add your exercise");
addyourown.setContentView(R.layout.addyourownex);
Button btn = (Button)addyourown.findViewById(R.id.btn_dialog_add);
final EditText et = (EditText)addyourown.findViewById(R.id.et_dialog_insertname);
final Spinner spinner = (Spinner)addyourown.findViewById(R.id.sp_cath);
ArrayAdapter<String> adapter ;
adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,cathegories);
spinner.setAdapter(adapter);
addyourown.show();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(et.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"EMPTY INPUT",Toast.LENGTH_SHORT).show();
}else {
Exercise exercise = new Exercise(et.getText().toString(), spinner.getSelectedItem().toString());
exercise.save();
exerciseArrayList.add(exercise);
exerciseAdapter.notifyDataSetChanged();
addyourown.cancel();
}
}
});
}
});
}
and my adapter class with dialog
public class ExerciseAdapter extends ArrayAdapter<Exercise> {
public Dialog newDialog;
public ExerciseAdapter(#NonNull Context context, ArrayList<Exercise> exercises) {
super(context,0,exercises);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
final Exercise exercise = getItem(position);
if(convertView==null){
convertView= LayoutInflater.from(getContext()).inflate(R.layout.exercises_layout,parent,false);
}
TextView name = (TextView)convertView.findViewById(R.id.tv_exercise);
ImageButton ib= (ImageButton)convertView.findViewById(R.id.ib_plus);
name.setText(exercise.getName());
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newDialog = new Dialog(v.getRootView().getContext());
if(exercise.getCathegory().equals("Cardio")) {
newDialog.setContentView(R.layout.cardio_layout);
final EditText duration = (EditText)newDialog.findViewById(R.id.et_duration);
Button bt = (Button) newDialog.findViewById(R.id.btn_carconfirm);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(duration.getText().toString().equals("")){
Toast.makeText(getContext(),"EMPTY INPUT",Toast.LENGTH_SHORT).show();
}else {
WorkoutDay workoutDay = SugarRecord.findById(WorkoutDay.class,(long)1);
workoutDay.extendCardio(exercise.getName(),duration.getText().toString());
workoutDay.save();
newDialog.cancel();
}
}
});
} else {
newDialog.setContentView(R.layout.instervalue_exercises);
final EditText sets = (EditText)newDialog.findViewById(R.id.et_series);
final EditText reps = (EditText)newDialog.findViewById(R.id.et_reps) ;
final EditText kgs = (EditText)newDialog.findViewById(R.id.et_kg);
Button bt = (Button) newDialog.findViewById(R.id.btn_confirm);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sets.getText().toString().equals("") || reps.getText().toString().equals("") || kgs.getText().toString().equals("")){
Toast.makeText(getContext(),"EMPTY INPUT",Toast.LENGTH_SHORT).show();
}else {
WorkoutDay workoutDay = SugarRecord.findById(WorkoutDay.class,(long)1);
workoutDay.extendExercise(exercise.getName(),sets.getText().toString(),reps.getText().toString(),kgs.getText().toString());
workoutDay.save();
newDialog.cancel();
}
}
});
}
newDialog.show();
}
});
return convertView;}
String key,k[];
int index;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tarsos_dsp);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.key, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
for(int i =0;i<=11;i++)
{
k = getResources().getStringArray(R.array.key);
if(key.equals(k[i].toString()))
{
spinner.setSelection(i);
}
}
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
index = arg0.getSelectedItemPosition();
// storing string resources into Array
k = getResources().getStringArray(R.array.key);
Toast.makeText(getBaseContext(), "You have selected key : " +k[index],
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// do nothing
}
});
Thaat tht = new Thaat();
Bundle extras = getIntent().getExtras();
if(extras !=null) {
key= extras.getString("key");
Toast.makeText(getApplicationContext(), key, Toast.LENGTH_SHORT).show();
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
dispatcher.addAudioProcessor(new PitchProcessor(PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult pitchDetectionResult, AudioEvent audioEvent) {
final float pitchInHz = pitchDetectionResult.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView text = (TextView) findViewById(R.id.textView1);
TextView d =(TextView) findViewById(R.id.textView2);
}
}
If I add it void run it still gives error, how do I add the spinner with a default value coming from the last activity using intent
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();
}
});
}
}
How would I use shared preferences to store the state of my checkbox for the next time the app is opened? I'm using a custom adapter so am guessing it has to be placed inside that but I'm not quite sure.
My Adapter:
public class MobileArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
public MobileArrayAdapter(Context context, String[] values) {
super(context, R.layout.list_adapter, values);
this.context = context;
this.values = values;
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false);
}
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_adapter,
parent, false);
}
// in your code you search for the CheckBox with the id checkBox1 2 times so I assumed that you are referring to the same view.
CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1);
cBox.setTextColor(0xFFFFFFFF);
cBox.setText(values[position]);
cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
itemChecked.set(position, true);
// do some operations here
} else {
itemChecked.set(position, false);
// do some operations here
}
}
});
cBox.setChecked(itemChecked.get(position));
return rowView;
}
}
My main Activity:
public class TheKevinAndEricaBoxActivity extends Activity {
/** Called when the activity is first created. */
private String[] myString;
private String list;
private String[] myString2;
private String list2;
private static final Random rgenerator = new Random();
private static final Random rgenerator2 = new Random();
MediaPlayer mp;
final Context mContext = this;
final Context context = this;
private Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
addListenerOnButton();
myString = res.getStringArray(R.array.myArray);
list = myString[rgenerator.nextInt(myString.length)];
myString2 = res.getStringArray(R.array.myArray2);
list2 = myString2[rgenerator.nextInt(myString2.length)];
}
public void addListenerOnButton() {
final Context context2 = this;
ImageButton ibg = (ImageButton) findViewById(R.id.buttongallery);
ibg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context2, App2Activity.class);
startActivityForResult(intent, 0);
}
});
ImageButton ib = (ImageButton) findViewById(R.id.imagebutton1);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View erica) {
AlertDialog.Builder b = new AlertDialog.Builder(
TheKevinAndEricaBoxActivity.this);
b.setMessage(myString[rgenerator.nextInt(myString.length)]);
b.setTitle(R.string.title1);
b.setIcon(R.drawable.menuiconerica);
b.setPositiveButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
Dialog d = b.create();
d.show();
}
});
ImageButton ib2 = (ImageButton) findViewById(R.id.imagebutton2);
ib2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View kevin) {
AlertDialog.Builder b = new AlertDialog.Builder(
TheKevinAndEricaBoxActivity.this);
b.setMessage(myString2[rgenerator2.nextInt(myString2.length)]);
b.setTitle(R.string.title2);
b.setIcon(R.drawable.menuiconkevin);
b.setPositiveButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
Dialog d = b.create();
d.show();
}
});
ImageButton Ib3 = (ImageButton) findViewById(R.id.imagebutton3);
Ib3.setOnClickListener(new View.OnClickListener() {
public void onClick(View lemonclick) {
mp = MediaPlayer.create(getApplicationContext(),R.raw.lemonspeech);
mp.start();
}
});
button = (Button) findViewById(R.id.button01);
// add button listener
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.list);
dialog.setTitle("The List");
// set the custom dialog components - text, image and button
//TextView text = (TextView) dialog.findViewById(R.id.TextView01);
//text.setText("Did you not read the button? :P i'm not finshed on this yet XD");
ListView listView = (ListView) findViewById(R.id.myList);
String[] values = new String[] { "value1", "value2", };
MobileArrayAdapter mAdapter = new MobileArrayAdapter(getBaseContext(), values);
ListView mListView = (ListView) dialog.findViewById(R.id.myList);
mListView.setAdapter(mAdapter);
Button dialogButton = (Button) dialog.findViewById(R.id.Button01);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
In the OnCLickListener for your Button add this:
//...
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.list);
dialog.setTitle("The List");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefsEditor = prefs.edit();
String currentlyStored = prefs.getString("checked_list", null);
int[] savedStatus = null;
if (currentlyStored != null) {
String[] tmp = currentlyStored.split(",");
savedStatus = new int[tmp.length];
for (int i = 0; i < tmp.length; i++) {
savedStatus[i] = Integer.parseInt(tmp[i]);
}
}
adapter = new MobileArrayAdapter(this, soundnames, savedStatus);
ListView mListView = (ListView) dialog.findViewById(R.id.myList);
mListView.setAdapter(mAdapter);
//...
where:
private SharedPreferences prefs;
private SharedPreferences.Editor prefsEditor;
private MobileArrayAdapter adapter;
are fields in your class with the ListView(the adapter field will hold your adapter object that you set on the list).
Modify the constructor of your custom adapter like this:
public MobileArrayAdapter(Context context, String[] values,
int[] oldStatus) {
super(context, R.layout.adapters_simpleplay_row, values);
this.context = context;
this.values = values;
// make every CheckBox unchecked and then loop through oldStatus(if
// not null)
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false);
}
if (oldStatus != null) {
for (int j = 0; j < oldStatus.length; j++) {
itemChecked.set(oldStatus[j], true);
}
}
}
Also add the following method in your custom adapter MobileArrayAdapter:
public ArrayList<Boolean> getCheckedStatus() {
return itemChecked;
}
Last in the listener for your dialogButton add this:
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String toStore = "";
ArrayList<Boolean> status = adapter.getCheckedStatus();
for (int i = 0; i < status.size(); i++) {
if (status.get(i)) {
toStore += i + ",";
}
}
prefsEditor.putString("checked_list", toStore.equals("") ? null
: toStore.substring(0, toStore.length() - 1));
prefsEditor.commit();
dialog.dismiss();
}
});
To save selections make a method saveSelections and call it in onPause() and onDestroy(), or create a Button to do the same for you...
Edit:
Since you are using a ListView which is MultipleChoice I suppose you can do this in onCreate...
listView = (ListView) findViewById(R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
android.R.id.text1, names));
Create these three methods outside onCreate()
private void LoadSelections() {
SharedPreferences sp = getPreferences(MODE_PRIVATE);
if (sp.contains(LOAD_LIST)) {
String savedItems = sp.getString(LOAD_LIST, "");
this.selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.listView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) listView.getAdapter().getItem(i);
if (this.selectedItems.contains(currentItem)) {
this.listView.setItemChecked(i, true);
}
}
}
}
public void SaveSelections() {
SharedPreferences sp = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sp.edit();
String savedItems = getSavedItems();
prefEditor.putString(LOAD_LIST, savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = listView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (listView.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + listView.getItemAtPosition(i);
} else {
savedItems += listView.getItemAtPosition(i);
}
}
}
return savedItems;
}
Then in onPause(), do this:
#Override
protected void onPause() {
SaveSelections();
super.onPause();
}
Then finally in onCreate call this..
LoadSelections();
You can make a string of 0 & 1 and store it using shared preference. The number of checkboxes (or the number of view) you are using will be the length of string. You save it accordingly.
Eg:
String s[]="0000000000";
for (i=0;i<s.length();i++)
if (checkboxAtLocation(i)==true) //checkboxAtLocation() will return a boolean variable on basis of its checked or not
s[i]=1;
Now store this string.
On starting activity again, use this string to set the checkbox.
This is bit complex to implement but most efficient way as per my knowledge.
I hope it solves your doubt.