clearing shared preferences when button clicked - java

So I have had a look at Delete Sharedpreferences on button click this post, and tried the code, but when I ran it on my app, only my textviews disappeared and everything else stayed?
This is the snippet of code: (it's a button on an overflow menu)
else if (id == R.id.action_delete) {
//code to delete list here.
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.clear().apply();
Toast.makeText(getBaseContext(), "List removed.", Toast.LENGTH_SHORT).show();
return true;
}
My full code
public class create 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<>();
private Spinner spinner;
private TextView textview;
private CheckBox checkbox;
List<String> itemList = new ArrayList<>();
LinearLayout verticallayout,horizontalLayout;
public static final String MY_PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(R.id.my_linearLayout).requestFocus();
verticallayout = findViewById(R.id.verticalLayout); //got
//Arrays
ArrayList<String> items = new ArrayList<>();
items.add(String.valueOf(mSpinners)); // add you selected item
mSpinners = new ArrayList<>();
//Initializing Variables Here
mLinearLayout = findViewById(R.id.my_linearLayout);
//verticallayout = findViewById(R.id.verticalLayout);
textview = findViewById(R.id.textview);
checkbox = findViewById(R.id.checkbox);
//TODO getting shared prefs on create
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
try {
JSONArray jsonArray2 = new JSONArray(prefs.getString("key", null));
for (int i = 0; i < jsonArray2.length(); 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);*/
createRow();
final TextView newTextview = makeTextview();
mLinearLayout.addView(newTextview);
mTextviews.add(newTextview);
final int listSize = mViews.size();
//TODO deleting item
horizontalLayout.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(create.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);
// mSpinners.remove(listSize - 1);
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();
}
});
int positionOfSpinner = (int) jsonArray2.get(i);
spinner.setSelection(positionOfSpinner);
}
} catch (Exception e) {
e.printStackTrace();
}
//end of shared pref code
//TODO FAB BUTTON
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);
// 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();
mLinearLayout.addView(newView);
mViews.add(newView);
/* final EditText newEdittext = makeEdittext();
mLinearLayout.addView(newEdittext);
mEdittexts.add(newEdittext);*/
createRow();
final int listSize = mViews.size();
//code for deleting the said item.
horizontalLayout.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(create.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);
mSpinners.remove(listSize - 1);
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);*/
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, do nothing
}
});
}
});
}
//TODO OVERFLOW MENU
#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, AppCompatPreferenceActivity.class);
startActivity(startSettingsActivity);
//start the settings activity here.*/
startActivity(new Intent(create.this, settings.class));
return true;
}
else if (id == R.id.action_delete) {
//code to delete list here.
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.clear().apply();
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;
}
else if (id == R.id.action_gotoview) {
//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);
startActivity(newIntent);
//code to go to view screen, aka intent
return true;
}
return super.onOptionsItemSelected(item);
}
public void createRow(View view){
createRow(); //got
}
private void createRow() { //got
horizontalLayout = new LinearLayout(this);
LinearLayout.LayoutParams horizontalParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalParams.height = 80;
horizontalParams.setMargins(0, 15, 0, 15); // LEFT, TOP, RIGHT, BOTTOM
horizontalLayout.setLayoutParams(horizontalParams);
horizontalLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.addButtons));
makeEdittext();
makeCheckbox();
verticallayout.addView(horizontalLayout, horizontalParams);
}
//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);
checkbox.setLayoutParams(layoutParams);*/
LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
checkParams.setMargins(10, 10, 10, 10);
checkParams.gravity = Gravity.LEFT;
checkbox.setLayoutParams(checkParams);
horizontalLayout.addView(checkbox);
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);
/*LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
editParams.setMargins(10, 10, 10, 10);
editParams.width = 70;
editParams.height = 50;
textview.setLayoutParams(editParams);
horizontalLayout.addView(textview);*/
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(70, 50); // Width , height
edittext.setLayoutParams(lparams);*/
LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
editParams.setMargins(10, 10, 10, 10);
editParams.width = 70;
editParams.height = 50;
edittext.setLayoutParams(editParams);
horizontalLayout.addView(edittext);
edittext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
edittext.setHint("qty");
return edittext;
}
//set the 3d effect to view
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);
view.setLayoutParams(layoutParams);
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 spinnerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
spinnerParams.setMargins(10, 10, 10, 10);
spinnerParams.gravity = Gravity.LEFT;
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
spinnerParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80
spinnerParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240
spinner.setLayoutParams(spinnerParams);
horizontalLayout.addView(spinner);*/
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;
}
}
//on stop, the things are saved into shared prefs
#Override
protected void onStop () {
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
JSONArray jsonArray = new JSONArray();
for(int i = 0; i < mSpinners.size(); i++) {
jsonArray.put(mSpinners.get(i).getSelectedItemPosition());
}
editor.putString("key", jsonArray.toString());
editor.apply();
super.onStop();
}
}

Try this to clear shared preferences:
else if (id == R.id.action_delete) {
//code to delete list here.
getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit().clear().commit();
Toast.makeText(getBaseContext(), "List removed.", Toast.LENGTH_SHORT).show();
return true;
}

Related

Show a list view in a different Activity

Hey I was wondering if this is possible. I'm working on a app that takes user input and creates flashcards. When I click the red button I want it to open a new activity displaying the input as a list. I'm not sure how to get the second activity to read the Edittext and put it into a list display.
When you press the green button, a prompt takes user input and post it to the page. When you click the red button it will take you to a list view of what the user entered. I'm a bit stumped on how to pass the information to the next page to display a list.
enter code here package Main Code ;
TextView QuestionTV;
TextView AnswerTV;
//Buttons of Main Flashcard xml
Button addcardbtn;
Button Answerbtn;
Button nextbtn;
//Input and Buttons from dialog_Flashcard xml
EditText QuestionET;
EditText AnswerET;
Button Submitcardbtn;
Button cancelbtn;
Button deletecard;
//counter for array
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_cards);
addcardbtn = findViewById(R.id.addcardbtn);
Answerbtn = findViewById(R.id.Answerbtn);
nextbtn = findViewById(R.id.nextbtn);
deletecard = findViewById(R.id.deletecard);
//new array
QuestionArray = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, QuestionArray);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, QuestionArray);
AnswerArray = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, AnswerArray);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, AnswerArray);
//Text views
QuestionTV = findViewById(R.id.QuestionTV);
AnswerTV = findViewById(R.id.answerTV);
deletecard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplication(), FlashCard_ListView.class));
}
});
addcardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder flashbuilder = new AlertDialog.Builder(FlashCards.this);
//get layout for the alert box
View fView = getLayoutInflater().inflate(R.layout.dialog_flashcard, null);
//get EditText from the alertbox layout
QuestionET = fView.findViewById(R.id.QuestionET);
AnswerET = fView.findViewById(R.id.AnswerET);
//get buttons from the alertbox layout
Submitcardbtn = (Button) fView.findViewById(R.id.Submitcardbtn);
cancelbtn = fView.findViewById(R.id.cancelbtn);
//make dialog box pop up
flashbuilder.setView(fView);
final AlertDialog dialog = flashbuilder.create();
dialog.show();
//code for the submit button
Submitcardbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!QuestionET.getText().toString().isEmpty() && !AnswerET.getText().toString().isEmpty()){
QuestionArray.add(QuestionET.getText().toString());
AnswerArray.add(AnswerET.getText().toString());
Toast.makeText(FlashCards.this, "Card Created", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
});
//code for cancel button
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
nextbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QuestionTV.setText(QuestionArray.get(count));
AnswerTV.setText(AnswerArray.get(count));
if (count<QuestionArray.size()-1 || count<AnswerArray.size()-1){
count++;
AnswerTV.setVisibility(View.INVISIBLE);
}else if(count == QuestionArray.size()-1){
count = 0;
AnswerTV.setVisibility(View.INVISIBLE);
}
}
});
Answerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AnswerTV.setVisibility(View.VISIBLE);
}
});
}
});
}
}
First Activity code
ArrayList<String> QuestionArray = new ArrayList<>();
QuestionArray.add(QuestionET.getText().toString());
ArrayList<String> AnswerArray = new ArrayList<>();
AnswerArray.add(AnswerET.getText().toString());
Intent i = new Intent(FlashCards.this, FlashCard_ListView.class);
i.putExtra("Questions", QuestionArray);
i.putExtra("Answers", AnswerArray);
startActivity(i);
Second Activity Code
Intent i = getIntent();
ArrayList<String> QuestionArray = i.getStringArrayListExtra("Questions");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, QuestionArray);
QuestionListView.setAdapter(adapter);
ArrayList<String> AnswerArray = i.getStringArrayListExtra("Answers");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, AnswerArray);
AnswersListView.setAdapter(adapter);
I Figured It out thanks!

Setting different text of a textview from an arraylist

I have a textview created programmatically in a loop. On a click of a button i want to fill each textview created with different values from the array how do i achieve this. Here is what happens when the button is clicked. Thanks for the help.
btnPnar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText et : editTextCollection)
{
gottenText = et.getText().toString();
inputList.add(gottenText);
Collections.shuffle(inputList);
}
// Creating alert Dialog with one Button
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,R.style.DialogeTheme);
// Setting Dialog Title
alertDialog.setTitle("PNAR");
// Setting Dialog Message
alertDialog.setMessage("Enter Amount of Numbers to Pick");
final EditText input; input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setTextColor(Color.parseColor("#f06292"));
input.setInputType(2);
alertDialog.setView(input);
alertDialog.setPositiveButton("DONE",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
pnarGotten = Integer.parseInt(input.getText().toString());
Collections.shuffle(inputList);
for (int n =0; n<pnarGotten; n++) {
TextView textView = new TextView(MainActivity.this);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.setText(inputList.get(0));
textView.setText(inputList.get(1));
listLayout.addView(textView);
}
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.create();
alertDialog.show();
}
});
UPDATE
This is what i added to the code inside the for loop but it shows only one output
for (int n =0; n<pnarGotten; n++) {
textViewForPnar = new TextView(MainActivity.this);
textViewForPnar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textViewForPnar.setGravity(Gravity.CENTER);
textViewForPnar.setTextColor(Color.WHITE);
while (iterator.hasNext())
{
textViewForPnar.setText(iterator.next());
}
listLayout.addView(textViewForPnar);
}
You should use Iterator object of your inputList collection to retvieve elements from it:
Iterator<String> iterator = inputList.iterator();
while (iterator.hasNext())
{
textView.setText(iterator.next());
}
Just simply replace your for loop with this code
for (int n = 0; n < pnarGotten; n++)
{
TextView textView = new TextView(MainActivity.this);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.setText(inputList.get(n));
listLayout.addView(textView);
}

Setting Button text programmatically is automatically going to last Index

So I'm working on an Android app, and trying to add buttons that will have click-triggered Dialogs programmatically.
When I add the OnClickListener to these buttons, I'm either getting the text from the last Button added, an error claiming that there is an IOOBException when calling tv1.setText(...) - invalid index 7, size is 7, or just nothing passed. Does anybody have any idea how I can set each Button to create a new Dialog with unique information for each button?
Snippet of code that's posing the problem:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
prefs = getSharedPreferences("carter.streakly", Context.MODE_PRIVATE);
editor = prefs.edit();
db = new DatabaseHelper(this);
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
res = db.getAllData();
if(res.getCount() ==0) {
//show message
showMessage("Error", "Nothing found");
return;
}
streakArrayList = new ArrayList<>();
int counter = 0;
while (res.moveToNext()){
streakArrayList.add(new Streak(Integer.parseInt(res.getString(0)), res.getString(1), res.getString(2), res.getString(3), Integer.parseInt(res.getString(4))));
counter++;
}
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(200, 200);
btnParams.setMargins(200, 30, 80, 30);
LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
tvParams.setMargins(100, 0, 0, 0);
i = 0;
while (i < counter){
if(i%2==0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
mTableRow.addView(ll);
Button btn = new Button(this);
btn.setText(""+streakArrayList.get(i).getDaysKept());
btn.setId(i);
btn.setBackground(getResources().getDrawable(R.drawable.round_button));
btn.setLayoutParams(btnParams);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dialog dialog = new Dialog(AllStreaks.this);
dialog.setContentView(R.layout.activity_enlarged);
tv1 = (TextView) dialog.findViewById(R.id.activity_enlarge_icon);
tv1.setText(streakArrayList.get(i-1).getActivityName());
dialog.show();
/*
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
intent.putExtra("passName", streakArrayList.get(view.getId()).getActivityName());
startActivity(intent);*/
}
});
ll.addView(btn);
TextView tv = new TextView(this);
tv.setText(streakArrayList.get(i).getActivityName());
tv.setId(i);
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setTextSize(20);
tv.setLayoutParams(tvParams);
ll.addView(tv);
i++;
}
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
There are many problems with your code.
First of all, you're using a global instance of both your TableRow and LinearLayout. This means you overwrite them on every iteration of your loop, so in the end only the values from the last iteration will be visible.
You're giving the same ID to both your Button and your TextView, they should be unique.
Using the counter variable is completely unnecessary, you could just use a for loop to iterate through your streakArrayList.
Something like this:
for (Streak streak : streakArrayList) {
TableRow mTableRow = new TableRow(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final String activityName = streak.getActivityName();
Button btn = new Button(this);
btn.setText("" + streak.getDaysKept());
btn.setId(aUniqueId);
btn.setBackground(getResources().getDrawable(R.drawable.round_button));
btn.setLayoutParams(btnParams);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dialog dialog = new Dialog(AllStreaks.this);
dialog.setContentView(R.layout.activity_enlarged);
tv1 = (TextView) dialog.findViewById(R.id.activity_enlarge_icon);
tv1.setText(activityName);
dialog.show();
}
});
TextView tv = new TextView(this);
tv.setText(activityName);
tv.setId(anotherUniqueId);
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setTextSize(20);
tv.setLayoutParams(tvParams);
ll.addView(btn);
ll.addView(tv);
mTableRow.addView(ll);
mTableLayout.addView(mTableRow);
}

Storing Dialogbox EditText into database

So I have a dialog box, where EditText is enabled, and when someone keys in something, and clicks on the add button, their text gets added into the database. Here are my "mainactivity" which is named IndivItem.java, codes.
public class IndivItem extends Activity {
TextView name, price;
Button descB, revB;
ImageView converse;
ImageButton fav, buy, compare;
TableLayout table_layout;
ReviewController revcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_indiv_item);
revcon = new ReviewController(this);
price = (TextView) findViewById(R.id.picPrice1);
name = (TextView) findViewById(R.id.text1);
descB = (Button) findViewById(R.id.desc);
revB = (Button) findViewById(R.id.review);
converse = (ImageView) findViewById(R.id.shoee1);
fav = (ImageButton) findViewById(R.id.fv1);
buy = (ImageButton) findViewById(R.id.co1);
compare = (ImageButton) findViewById(R.id.cp1);
table_layout = (TableLayout) findViewById(R.id.tableLayout1);
BuildTable();
revB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
IndivItem.this);
// Setting Dialog Title
alertDialog.setTitle("Review");
// Setting Dialog Message
alertDialog.setMessage("Add a Review");
final EditText input = new EditText(IndivItem.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog
.setView(input)
.setNegativeButton("Cancel",
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();
}
})
.setCancelable(false)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
new MyAsync().execute();
// toast saying review added
Toast.makeText(getApplicationContext(),
"Review Added!",
Toast.LENGTH_SHORT).show();
Intent home = new Intent(
getApplicationContext(),
IndivItem.class);
startActivity(home);
}
// close dialog
});
// show alert
alertDialog.show();
}
});
fav.setOnHoverListener(new OnHoverListener() {
#Override
public boolean onHover(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(IndivItem.this, "Add to Favorites",
Toast.LENGTH_SHORT).show();
return false;
}
});
compare.setOnHoverListener(new OnHoverListener() {
#Override
public boolean onHover(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(IndivItem.this, "Add to Compare List",
Toast.LENGTH_SHORT).show();
return false;
}
});
}
private void BuildTable() {
// TODO Auto-generated method stub
revcon.open();
Cursor c = revcon.readEntry();
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
// outer for loop
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(IndivItem.this);
row.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++) {
TextView tv = new TextView(IndivItem.this);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
table_layout.addView(row);
}
revcon.close();
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
String review = input.getText().toString();
return null;
revcon.open();
revcon.createEntry(review);
// BuildTable();
return null;
}}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
And what happens is this line : String review = input.getText().toString();,
Gives me an error, that says error cannot resolved. I have no clue how to link the codes ): or what I'm doing wrong, please enlighten me,thanks!

Button.performClick() doesn't work

I need to creat a linearLayout containing some views when clicking on a button , thsi button is triggerd by an action made in another activity ,so i used a performClick , but it seems that doesn't work ; here is my code :
Button click = new Button(rootView.getContext());
SharedPreferences participant;
Editor editor;
SharedPreferences visible;
Editor vis;
participant = rootView.getContext().getSharedPreferences("participant", rootView.getContext().MODE_PRIVATE);
visible = rootView.getContext().getSharedPreferences("visible", rootView.getContext().MODE_PRIVATE);
editor = participant.edit();
final String name= participant.getString("key", "toto");
final String view = participant.getString("view","non");
if(view.equalsIgnoreCase("yes")) click.performClick();
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
// Creating a new LinearLayout
final LinearLayout ln = new LinearLayout(v.getContext());
// Setting the orientation to horizontal
ln.setOrientation(LinearLayout.HORIZONTAL);
formbis.addView(ln);
TextView tv1 = new TextView(v.getContext());
tv1.setText(name);
tv1.setTextSize(14);
tv1.setTypeface(null, Typeface.BOLD);
tv1.setPadding(0, 15, 0, 10);
tv1.setLayoutParams(new LayoutParams(
500,
LayoutParams.WRAP_CONTENT));
ln.addView(tv1);
final ImageButton edit = new ImageButton(v.getContext());
Drawable checked = getResources().getDrawable( R.drawable.content_edit );
edit.setImageDrawable(checked);
edit.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
edit.setBackgroundColor(Color.WHITE);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
i = new Intent(v.getContext(), EditParticipantActivity.class);
startActivity(i);
}
});
ln.addView(edit);
final ImageButton delete = new ImageButton(v.getContext());
Drawable deleted = getResources().getDrawable( R.drawable.content_discard );
delete.setImageDrawable(deleted);
delete.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
delete.setBackgroundColor(Color.WHITE);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(v.getContext(),
"Deleted ", Toast.LENGTH_LONG).show();
formbis.removeView(ln);
}
});
ln.addView(delete);
ln.setVisibility(View.GONE);
if(view.equalsIgnoreCase("yes"))ln.setVisibility(View.VISIBLE);
}
});
EDIT
Here (another Activity ) I set the value to yes so that the linearLayout gets added to the view of the first activity
Button members = (Button) findViewById(R.id.submit);
members.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
name = firstname.getText().toString();
editor.putString("key", name);
editor.commit();
editor.putString("view", "yes");
editor.commit();
i = new Intent(v.getContext(), ManageActivity.class);
startActivity(i);
//finish();
}
});
Define the onClickListener first.
Then call the if(view.equalsIgnoreCase("yes")) click.performClick(); line after defining the click.onClickListner code.

Categories