Button.performClick() doesn't work - java

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.

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!

Dialog dismiss not working inside adapter

I have a modal(dialog) with a edit text inside and a send button, what i'm trying to do is simply send the content inside the edit text when the button is clicked, the thing is, sending the content is working, but when i call mydialog.dismiss(); it doesn't work. It is using an instance of another class to call a method retrofit, and inside the "done" and "not done" buttons i have the "enviar"(send) button which is the one i'm trying to close the modal with.
Here is the adapter code:
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent){
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(sContext).inflate(R.layout.item_tasks, parent,false);
final Tasks presenteTask = taskData.get(position);
TextView taskTitle = (TextView) listItem.findViewById(R.id.tasksTitle);
taskTitle.setText(presenteTask.getTitle());
EditText taskColor = (EditText) listItem.findViewById(R.id.taskColor);
if(presenteTask.getHexaColor().isEmpty()){
HexaColor = "#FFFFFF";
}
else{
HexaColor = presenteTask.getHexaColor();
taskColor.setBackgroundColor(Color.parseColor(HexaColor));
}
TextView taskTime = (TextView) listItem.findViewById(R.id.taskTime);
taskTime.setText(presenteTask.getTimeStart().toString().substring(0,5));
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false);
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final EditText comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
final Calendario calendario = new Calendario();
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
return listItem;
}
}
Thank you very much!
Firstly you have to make your dialog un-cancelable, so that outside click doesn't dismiss it using tasksModal.setCancelable(false);
Secondly no need to repeat code to create dialog inside done/undone button click. So, remove it and move it to TasksAdapter constructor.
Thirdly You are not dismissing your dialog inside done button click. So, add this tasksModal.dismiss();
Check and try with below code:
EditText comentarios;
Calendario calendario;
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false); //make it un cancelable
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
calendario = new Calendario();
}
-------------------------------------------------------------
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(!comentario.equals("")){
tasksModal.dismiss(); //dismiss here
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
else{
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
else{
tasksModal.dismiss();
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
}
});
tasksModal.show();
}
});

Get data from each dynamically created EditText

Dynamically created EditTexts by Add button, and also I have assigned them unique ID's using setId(), Now what I want to do is to get values from the dynamically created EditTexts when the user taps a button, then store all of them as Sharedpreferences
This is the code
Thank you guys
ADDED CODES
List<EditText> allEds = new ArrayList<EditText>();
Button btnSave, btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layoutmain = (LinearLayout) findViewById(R.id.layoutmain);
btnAdd = (Button) findViewById(R.id.btnadd);
btnSave = (Button) findViewById(R.id.btnsave);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText ed = new EditText(ActivityOptions.this);
ed.setId(ed.generateViewId());
ed.setTag(allEds.size());
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layoutmain.addView(ed);
// Add also to the allEds
allEds.add(ed);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
EditText ed = new EditText(ActivityOptions.this);
#Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
for (EditText ed : allEds) {
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
}
editor.commit();
}
});
Intent intent = new Intent(this, MainActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString());
}
intent.putExtra("Text", (Serializable) allTexts);
}
}
While creating every new EditText, you generate ids by setId() but I don't see how these are going to be useful in your code.
Instead set the tag of the EditText like this:
ed.setTag(allEds.size());
and add it to the list:
allEds.add(ed);
Now in each EditText's tag you have stored its ordinal number (zero based) in the list and when you want to store its value in SharedPreferences you can do:
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("key" + et.getTag().toString(), ed.getText().toString());
editor.commit();
or by using a loop through all the items in the list:
for (EditText ed : allEds) {
editor.putString("key" + et.getTag().toString(), ed.getText().toString());
}
editor.commit();
This way you stored all the text values of the EditTexts with keys like:
"key0", "key1", "key2",...
Edit
Of you want to open another activity and pass the list to it:
Intent intent = new Intent(this, AnotherActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString())
}
intent.putExtra("Text", (Serializable) allTexts);
and in the other activity's onCreate():
ArrayList<String> list = (ArrayList<String>) getIntent().getSerializableExtra("Texts");
Edit2
Replace the code in btnSave.setOnClickListener() and the lines below, with this code:
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
for (EditText ed : allEds) {
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
}
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString());
}
intent.putExtra("Text", (Serializable) allTexts);
startActivity(intent);
}
});
You forgot to add the EditText's to your list, so the save button will know about them and get their inputs.
After that you need to specify the save button (which I believe you did, but I cannot see a reference of it in your code).
Lastly just implement the logic for the save button in its onClick() (save in SharedPreferences).
List<EditText> allEds = new ArrayList<EditText>();
Button btnSave,btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layoutmain = (LinearLayout)findViewById(R.id.layoutmain);
btnAdd = (Button) findViewById(R.id.btnadd);
btnSave = (Button) findViewById(R.id.btnsave);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText ed = new EditText(MainActivity.this);
ed.setId(ed.generateViewId());
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layoutmain.addView(ed);
// Add also to the allEds
allEds.add(ed);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
for (EditText ed : allEds) {
editor.putString("saved_text_key", ed.getText().toString());
editor.commit();
}
}
});
}

Pass Data from Dialog to new Activity

I am trying pass data from my dialog box to a new Activity. So basically what i want to do for example in my Dialog box i have Name: John, when i click on my okay button it opens a new activity but i want that John to be set in my edit box on my new activity:
Here is my Activity where my Dialog box code is:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/** To change selected state view */
view.setSelected(true);
HashMap<String, Object> obj = (HashMap<String, Object>) ADAhere.getItem(position);
String SlectedName = (String) obj.get("NAME");
String SlectedPrice = (String) obj.get("PRICE");
String SlectedSize = (String) obj.get("SIZE");
String SlectedRange = (String) obj.get("RANGE");
String SlectedSupp = (String) obj.get("SUPPLIER");
// Toast.makeText(getActivity().getApplicationContext(), SlectedName, Toast.LENGTH_SHORT).show();
final Dialog dialog = new Dialog(getActivity());
dialog.getWindow();
//dialog.setTitle("Confirm your Vote");
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.diaglog);
final TextView VName = (TextView) dialog.findViewById(R.id.Name);
final TextView VRange = (TextView) dialog.findViewById(R.id.Range);
final TextView VSUPPLIER = (TextView) dialog.findViewById(R.id.Supplier);
final TextView VSIZE = (TextView) dialog.findViewById(R.id.Size);
final TextView VPrice = (TextView) dialog.findViewById(R.id.Price);
VName.setText(SlectedName);
VRange.setText(SlectedRange);
VSUPPLIER.setText(SlectedSupp);
VSIZE.setText(SlectedSize);
VPrice.setText(SlectedPrice);
dialog.show();
Button cancelBtn = (Button) dialog.findViewById(R.id.cancel_btn);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
Button UpdateBtn = (Button) dialog.findViewById(R.id.btn_update);
UpdateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
}
});
Button deleteBtn = (Button) dialog.findViewById(R.id.btn_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
}
});
dialog.show();
}
});
so i want to pass VName.setText(SlectedName); to a new activity:
name1.setText(dialogactivityname);
Pass in as an extra:
instead of:
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
you should pass in the name
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
i.putExtra("string", SlectedName);
startActivity(i);
Then, on your Upvalence activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
Bundle arguments = this.getIntent().getExtras();
String yourString = arguments.getString("string");
}

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);
}

Categories