Pointing to a looped textview and Button - java

I want to make a program where it will looped a text view and 2 button from database,
and I want to make when user click one of the button, certain textview and button will disappear,
I tried this code, but the one which disappear only the last inputted textview and button,
How can I make a pointer or something that refer to certain textview or button that I want to make it gone/disappear?
Here is my code :
private void doActionWithDatabase() {
// TODO Auto-generated method stub
myDatabase.open();
countInvitation = myDatabase.countHowManyInvitation(username);
String groupName[] = myDatabase.fetchGroupNameInvitation(username);
String groupId[] = myDatabase.fetchGroupIdInvitation(username);
/*
* String data = myDatabase.getDataFromInvitation();
* invGroupName.setText(data);
*/
for (int i = 0; i < countInvitation; i++) {
// invGroupName.setText("Invitation to join " + groupName[i]);
test1 = new TextView(this);
test1.setText("Invitation to join " + groupName[i]);
test1.setTag(i);
bAccept = new Button(this);
bAccept.setText("Accept yeh");
bAccept.setTag(groupId[i]);
bAccept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button clickedButton = (Button) v;
String tempForGroupId = (String) clickedButton.getTag();
Toast.makeText(getApplicationContext(),
tempForGroupId+" " +username, Toast.LENGTH_LONG).show();
test1.setVisibility(View.GONE);
bAccept.setVisibility(View.GONE);
bReject.setVisibility(View.GONE);
/* myDatabase.open();
myDatabase.addGroupMember(tempForGroupId, username);
myDatabase.deleteInvitation(tempForGroupId, username);
myDatabase.close();*/
}
});
bReject = new Button(this);
bReject.setText("Reject");
bReject.setTag(groupId[i]);
bReject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button clickedButton = (Button) v;
String tempForGroupId = (String) clickedButton.getTag();
Toast.makeText(getApplicationContext(),
tempForGroupId+" " +username, Toast.LENGTH_LONG).show();
/* myDatabase.open();
myDatabase.deleteInvitation(tempForGroupId, username);
myDatabase.close();*/
}
});
layout.addView(test1);
layout.addView(bAccept);
layout.addView(bReject);
}
}

you should define your TextView and Button variable inside your for loop
something like
for (int i = 0; i < countInvitation; i++) {
final TextView test1 = new TextView(this);
final Button bAccept = new Button(this);
bAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test1.setVisibility(View.GONE);
}
});
final Button bReject = new Button(this);
}

Related

I have 5 choices in a test. I have a csv database. When I press on one of the buttons, I want the Text on the button to change to the next header

I have 5 choices in a test. I have a csv database which I read the headers and answers from. When I press on one of the buttons, I want the Text on the button to change to the next header. I want to use a "for" loop for that. How will I keep the same layout, but change the text on the buttons in this for loop?
public class MainActivity extends AppCompatActivity {
int say,may=0;
Button a,b,c,d,e;
private List<WeatherSample> weatherSamples=new ArrayList<>();
String[][] deneme=new String[20][7];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button asikki = (Button) findViewById(R.id.asikki);
final Button bsikki = (Button) findViewById(R.id.bsikki);
final Button csikki = (Button) findViewById(R.id.csikki);
final Button dsikki = (Button) findViewById(R.id.dsikki);
final Button esikki = (Button) findViewById(R.id.esikki);
String line = "";
a = (Button) findViewById(R.id.asikki);
b = (Button) findViewById(R.id.bsikki);
c = (Button) findViewById(R.id.csikki);
d = (Button) findViewById(R.id.dsikki);
e = (Button) findViewById(R.id.esikki);
InputStream is = getResources().openRawResource(R.raw.data);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
try {
// step over header line
reader.readLine();
while ((line = reader.readLine()) != null) {
may++;
String sira = Integer.toString(may);
String[] tokens = line.split(",");
WeatherSample sample = new WeatherSample();
deneme[may][0] = tokens[0];
deneme[may][1] = tokens[1];
deneme[may][2] = tokens[2];
deneme[may][3] = tokens[3];
deneme[may][4] = tokens[4];
deneme[may][5] = tokens[5];
deneme[may][6] = tokens[6];
}
} catch (IOException e) {
e.printStackTrace();
}
for (int say=0;say<10;say++){
a.setText("A) " + deneme[1][0]);
b.setText("B) " + deneme[1][1]);
c.setText("C) " + deneme[1][2]);
d.setText("D) " + deneme[1][3]);
e.setText("E) " + deneme[1][4]);
asikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
asikki.setText("bilgin");
asikki.setBackgroundColor(Color.BLACK);
asikki.setTextColor(Color.WHITE);
}
});
bsikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bsikki.setText("bilgin");
bsikki.setBackgroundColor(Color.BLACK);
bsikki.setTextColor(Color.WHITE);
}
});
csikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
csikki.setText("bilgin");
csikki.setBackgroundColor(Color.BLACK);
csikki.setTextColor(Color.WHITE);
}
});
dsikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dsikki.setText("bilgin");
dsikki.setBackgroundColor(Color.BLACK);
dsikki.setTextColor(Color.WHITE);
}
});
esikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
esikki.setText("bilgin");
esikki.setBackgroundColor(Color.BLACK);
esikki.setTextColor(Color.WHITE);
}
});
}
}
for loop is something to be executed immediately, it doesn't wait, you only need the listener
asikki.setText(deneme[0][0]);
asikki.setBackgroundColor(Color.BLACK);
asikki.setTextColor(Color.WHITE);
asikki.setOnClickListener(new View.OnClickListener() {
int say = 1;
public void onClick(View v) {
// TODO check say isn't out of bound
asikki.setText("A) " +deneme[say++][0]);
}
});
Thanks to #Happy, Now I have the following lines in my code:
int say = 1;
asikki.setText(deneme[0][0]);
asikki.setBackgroundColor(Color.BLACK);
asikki.setTextColor(Color.WHITE);
asikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
say++;
asikki.setText("A) " +deneme[say][1]);
bsikki.setText("B) " +deneme[say][2]);
csikki.setText("C) " +deneme[say][3]);
dsikki.setText("D) " +deneme[say][4]);
esikki.setText("E) " +deneme[say][5]);
}
});

Looping through an array of edittexts and getting the texts of each

I have an autogenerated list of edittexts gotten from the user input. What i want to do is shuffle the edittexts when the shuffle button is clicked or get the texts and set them to different edittexts. What i tried doing is to get the texts of each edittext adding it to an arraylist and shuffling it and then recreating the layout with the shuffled list. But that in itself is giving me errors. When the shuffle button is clicked it gives me this error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
Thanks For the help
`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnForCreate = (Button) findViewById(R.id.btnCreateTxt);
editTextForInputToCreate = (EditText) findViewById(R.id.textForInputToCreate);
listLayout = (LinearLayout) findViewById(R.id.listLayout);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnShuffleTxt = (Button) findViewById(R.id.btnShuffleTxt);
editTextForInputToCreate.animate().translationX(-1000f);
btnForCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bringTextInputBackOnScreen();
}
});
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTextForInputToCreate.getText().toString().length() >= 0) {
try {
listLayout.removeAllViews();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
length = Integer.parseInt(editTextForInputToCreate.getText().toString());
for (i = 0; i < length; i++) {
editTextCollection = new EditText[length];
editText = new EditText(MainActivity.this);
editText.setId(i + 1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Input" + " " + (i + 1));
listLayout.addView(editText);
editTextCollection[i] = editText;
}
}
});
btnShuffleTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText gottenEditText:editTextCollection)
{
String gottenTexts = gottenEditText.getText().toString();
list.add(gottenTexts);
}
Collections.shuffle(list);
}
});
}
private void bringTextInputBackOnScreen()
{
editTextForInputToCreate.animate().translationXBy(1000f).setDuration(2000);
}
`
Please make some corrections in your EditTextCollection.
editTextCollection = new EditText[length];// initialization outside the loop
for (i = 0; i < length; i++) {
editText = new EditText(MainActivity.this);
editText.setId(i + 1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Input" + " " + (i + 1));
listLayout.addView(editText);
editTextCollection[i] = editText;
}
btnShuffleTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText gottenEditText:editTextCollection)
{
String gottenTexts = gottenEditText.getText().toString();
list.add(gottenTexts);
}
Collections.shuffle(list);
for (EditText gottenEditText:editTextCollection)
{
gottenEditText.setText(list.get(editTextCollection.indexOf(gottenEditText)));
}
}
});

Calculate total checkboxes ticked and perform calculation (Android Java)

I have checkboxes created dynamically using shared preferences. The label for each checkbox is stored in array.xml. How can I calculate the total number of checkboxes that are ticked and store the total in a variable and further use it for another calculation -- (total/totalCheckboxes)*100?
Here's a snippet of the Java class:-
public class CheckBoxSharedPreferences extends Activity {
ListView myList;
Button getChoice, clearAll, button1;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyUserChoice";
ArrayList<String> selectedItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList = (ListView) findViewById(R.id.list);
getChoice = (Button) findViewById(R.id.getchoice);
clearAll = (Button) findViewById(R.id.clearall);
button1 = (Button) findViewById(R.id.button1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
// code snippet to retrieve array values in ArrayAdapter
getResources().getStringArray(R.array.Questionnaire));
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(MyPREFERENCES)) {
LoadSelections();
}
getChoice.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
int cntChoice = myList.getCount();
SparseBooleanArray sparseBooleanArray = myList
.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString()
+ "\n";
System.out.println("Checking list while adding:"
+ myList.getItemAtPosition(i).toString());
SaveSelections();
}
}
Toast.makeText(CheckBoxSharedPreferences.this, selected,
Toast.LENGTH_LONG).show();
}
});
//listener for clear all button
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClearSelections();
}
});
//listener for button1 (that transfers the activity to another intent
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(CheckBoxSharedPreferences.this,
result.class);
startActivity(intent);
}
});
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the
// user
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES.toString(), savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.myList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.myList.getItemAtPosition(i);
} else {
savedItems += this.myList.getItemAtPosition(i);
}
}
}
return savedItems;
}
private void LoadSelections() {
// if the selections were previously saved load them
if (sharedpreferences.contains(MyPREFERENCES.toString())) {
String savedItems = sharedpreferences.getString(
MyPREFERENCES.toString(), "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter().getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
Toast.makeText(getApplicationContext(),
"Current Item: " + currentItem, Toast.LENGTH_LONG)
.show();
} else {
myList.setItemChecked(i, false);
}
}
}
}
and the array.xml:-
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="Questionnaire">
<item>abc</item>
<item>jkm</item>
<item>xyz</item>
<item>abc2</item>
<item>jkm2</item>
<item>xyz2</item>
<item>abc3</item>
<item>jkm3</item>
<item>xyz3</item>
</resources>
Thanks in advance!
Use this code where you want to get the total number of checked items and perform the calculation
int checkedCount = myList.getCheckedItemCount();
int totalCount = myList.getAdapter().getCount();
int calculatedValue = (totalCount/checkedCount) * 100;

cannot be resolved or is not a field with some EditTexts

Ok so i have the following situation : I create some Editexts dynamically and i want to add another row of Editexts when one of the EditTexts from the last row is clicked.
I tried doing it the following way :
When the last row of EditTexts is created,i assign each of them an id
et.setId(997);
et.setId(998);
et.setId(999);
I declared each of them ;
public EditText camp1;
public EditText camp2;
public EditText camp3;
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
And when i try to do this
case R.id.camp1:
inside a switch i get "camp1 cannot be resolved or is not a field"
What am i doing wrong ?
Is there a better way to detect when the last Edittext is clicked and create a new one ?
EDIT:
public class MainActivity extends Activity implements OnClickListener,
TextWatcher {
public Button paginanoua;
// public Button calculeaza;
public Button produsnou;
public EditText camp1;
public EditText camp2;
public EditText camp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
produsnou();
paginanoua = (Button) findViewById(R.id.paginanoua);
// calculeaza = (Button) findViewById(R.id.calculeaza);
produsnou = (Button) findViewById(R.id.produsnou);
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
paginanoua.setOnClickListener(this);
// calculeaza.setOnClickListener(this);
produsnou.setOnClickListener(this);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
}
public void onClick(View view) {
switch(view.getId())
{
case R.id.paginanoua:
ShowDialog();
case R.id.produsnou:
produsnou();
case R.id.997:///error
produsnou();
}
}
private void ShowDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Pagina noua..");
dialogBuilder.setMessage("Sigur doriti o pagina noua?");
dialogBuilder.setPositiveButton("Da",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Am inceput o lista noua", Toast.LENGTH_SHORT)
.show();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
dialogBuilder.setNegativeButton("Nu",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Ramanem la lista curenta", Toast.LENGTH_SHORT)
.show();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
List<EditText> allpret = new ArrayList<EditText>();
List<EditText> allcant = new ArrayList<EditText>();
List<Float> alltotal = new ArrayList<Float>();
float totaltest = 0;
public void produsnou() {
LinearLayout l1 = (LinearLayout) findViewById(R.id.layout1);
EditText et = new EditText(this);
et.setHint("Produs");
l1.addView(et);
et.addTextChangedListener(this);
et.setId(997);
LinearLayout l2 = (LinearLayout) findViewById(R.id.layout2);
EditText et2 = new EditText(this);
et2.setHint("Cantitate");
et2.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
et2.setId(998);
allcant.add(et2);
l2.addView(et2);
et2.addTextChangedListener(this);
LinearLayout l3 = (LinearLayout) findViewById(R.id.layout3);
EditText et3 = new EditText(this);
et3.setHint("Pret");
et3.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
l3.addView(et3);
et3.setId(999);
allpret.add(et3);
et3.addTextChangedListener(this);
}
float temp = 0;
public void calculeaza() {
totaltest = 0;
String[] cant = new String[allcant.size()];
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
if (cant[j].matches("")) {
Toast.makeText(this,
"Ati omis cantitatea de pe pozitia " + (j + 1),
Toast.LENGTH_SHORT).show();
cant[j] = Float.toString(0);
}
}
String[] pret = new String[allcant.size()];
for (int k = 0; k < allpret.size(); k++) {
pret[k] = allpret.get(k).getText().toString();
if (pret[k].matches("")) {
Toast.makeText(this,
"Ati omis pretul de pe pozitia " + (k + 1),
Toast.LENGTH_SHORT).show();
pret[k] = Float.toString(0);
}
}
for (int l = 0; l < allpret.size(); l++) {
Float temp = Float.parseFloat(cant[l]) * Float.parseFloat(pret[l]);
alltotal.add(temp);
totaltest = totaltest + temp;
// totaluri[l] = temp ; }
TextView totalf = (TextView) findViewById(R.id.total);
totalf.setText(String.format("Total: %.2f", totaltest));
}
}
// Float[] totaluri = new Float[allcant.size()];
public void reload(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
calculeaza();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
calculeaza();
}
}
All you care about is the last editText, right? Just give the last editText an onClickListener that creates another editText. Then give the new editText the onClickListener and remove it from the the previous "last one".
like this:
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(new myListener());
...
//put this private class in the same activity as the stuff above
private class myListener implements View.OnClickListener {
#Override
public void onClick(View view) {
EditText editText = new EditText(YourActivityName.this);
editText.setOnClickListener(new myListener());
//TODO put it in your viewGroup
//Give the old EditText your standard onClickListener
view.setOnClickListener(YourActivityName.this);
//To change body of implemented methods use File | Settings | File Templates.
}
}
setId() does not add any variables to the R.id class because setId() executes at run-time, but R is generated at compile-time. Since you are creating dynamic views, you need to rethink your onClick() method. You might want to consider using a ListView to help you. You can also set up the three TextViews using a separate XML file, such as row.xml.

How to get onClickListener for Android array of buttons to work

I have created a dynamic array of buttons that come from sqllite database. For the life of me I cannot get a click listener set up to address each button individually. I have been searching for 3 hours with no success at all.
Any help would be appreciated. Don't worry about the database crap, it's just the listener.
imports...
public class CreatePlayList extends Activity {
ScrollView scrollleft, scrollright;
LinearLayout songsright, songsleft;
TextView testtext;
String[][] allsongs;
int numofsongs, i;
Button b1[];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.createplaylist);
scrollleft = (ScrollView) findViewById(R.id.scrollleft);
scrollright = (ScrollView) findViewById(R.id.scrollright);
songsright = (LinearLayout) findViewById(R.id.layRight);
songsleft = (LinearLayout) findViewById(R.id.layLeft);
LyricDb connect = new LyricDb(CreatePlayList.this);
connect.open();
numofsongs = connect.getNumSongs();
b1 = new Button[(numofsongs)];
allsongs = new String[numofsongs][2];
allsongs = connect.getSongArray();
connect.close();
testtext = new TextView(this);
testtext.setText("Test");
songsleft.addView(testtext);
for (i = 0; i < allsongs.length; i++) {
b1[i] = new Button(this);
b1[i].setText(allsongs[i][1]);
songsright.addView(b1[i]);
}
b1[19].setText("test 123");
createClic();
}
public void createClic(){
for (i = 0; i < (allsongs.length - 1); i++) {
b1[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
testtext.setText(b1[i].getText());
}
});
}
}
}
Dump the 'i' declared at class level. Replace method with this (the "Button theButton" needs to stay 'final').
public void createClic()
{
for (int i = 0; i < (allsongs.length - 1); i++)
{
final Button theButton = b1[i];
theButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
testtext.setText(theButton.getText());
}
});
}
}
First implement OnClickListener in your Activity and call setOnClickListener() method to all of your buttons when you are creating it.
b[i].setOnClickListener(this);
and also set id with each button
b[i].setId(i);
//and override this method
#Override
public void onClick(View v)
{
//here check which button called
if(v.getId==1)
{
//its Button 1 do what ever u want
}
if(v.getId==2)
{
//its Button 2 do what ever u want its Button 2
}
......
}
Try it once...
b1[i] = new Button[allsongs.length];
for (i = 0; i < allsongs.length; i++) {
b1[i].setText(allsongs[i][1]);
songsright.addView(b1[i]);
}

Categories