How to get id value from programmatically created Edittext - android

calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mul=0;
sum=0;
for(j=0;j<=a-1;j++){
Log.d("TAG","a ko value inside calc "+a);
et_grade_grabber=(EditText) findViewById(grade[j]);
int grade= Integer.parseInt(et_grade_grabber.getText().toString());
Log.d("TAG","Grade Value of Grade"+j+ " is "+grade);
et_credit_grabber=(EditText) findViewById(credit[j]);
int credit=Integer.parseInt(et_credit_grabber.getText().toString());
Log.d("TAG","Credit Value of Credit "+j+" is "+credit);
tot_credit= credit+tot_credit;
Log.d("TAG","Total Credit = "+tot_credit);
mul=credit*grade;
sum= sum + mul;
Log.d("Sum Inside Loop ",""+sum);
}
Log.d("TAG","Sum"+sum);
Toast.makeText(getApplicationContext(),""+sum,Toast.LENGTH_SHORT).show();
sgpa= sum/tot_credit;
tv_sgpa= new TextView(MainActivity.this);
tv_sgpa.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,TableLayout.LayoutParams.WRAP_CONTENT));
tv_sgpa.setText("Your SGPA is "+sgpa);
tv_sgpa.setTextSize(40);
LinearLayout ll_sgpa = new LinearLayout(MainActivity.this);
ll_sgpa.setLayoutParams(new ActionBar.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
ll_sgpa.addView(tv_sgpa);
LinearLayout linear = (LinearLayout) findViewById(R.id.ll_spga);
linear.addView(ll_sgpa);
}
});
}
I have successfully create EditText fields using a for(i=0;i<4-1;i++) loop from java file and assign id by setid(Array[i]) inside a loop.
Now again I have retrive the values by method getText().toString() inside a loop for(j=0;j<4-1;j++)
When I input the values in edit text everything works fine except it only retrieves the first value of edit text to all array.

If I understood your question correctly, you should use
for(int i = 0; i < arrayOfEditTexts.size(); i++){
//if you need only some of Ids, just check conditions with `if`statement. example:
if(!((EditText)arrayOfEditTexts.get(i)).getText().toString().equalsIgnoreCase("")){
arrayOfEditTexts.get(i).getId(); // and do whatever you want
}
}

Related

How to save the updated value of an array back to the firestore database?

for (QueryDocumentSnapshot snapshot : Objects.requireNonNull(task.getResult())) {
String value1 = snapshot.getString("QuestionName");
q_tv1.setText("Question: "+value1);
ArrayList<String> description = (ArrayList<String>) snapshot.get("Description");
Log.d(Tag,"output for des: "+description);
List<String> noOfOptions = (List<String>) snapshot.get("Options");
Log.d(Tag,"output for option: "+noOfOptions);
ArrayList<String> finalCount=(ArrayList<String>) snapshot.get("CountValue");
int size=noOfOptions.size();
Log.d(Tag,"size: "+finalCount);
for(i=0;i<=size-1;i++)
{
String op=noOfOptions.get(i);
String n=finalCount.get(i);
CardView cardview=new CardView(PublicVote.this);
LayoutParams layoutparams = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
LayoutParams layoutparams2 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
cardview.setLayoutParams(layoutparams);
cardview.setRadius(25);
layoutparams.setMargins(10,10,10,10);
layoutparams2.setMargins(10,100,100,100);
cardview.setPadding(25, 25, 25, 25);
cardview.setCardBackgroundColor(Color.TRANSPARENT);
cardview.setBackgroundTintList(ColorStateList.valueOf(Color.YELLOW));
cardview.setMaxCardElevation(30);
cardview.setMaxCardElevation(6);
TextView textview = new TextView(PublicVote.this);
textview.setLayoutParams(layoutparams);
textview.append("o " +noOfOptions.get(i));
textview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25);
textview.setTextColor(Color.BLACK);
textview.setPadding(25,25,25,25);
textview.setGravity(Gravity.LEFT);
textview.setLayoutParams(layoutparams);
TextView textview1 = new TextView(PublicVote.this);
textview1.setLayoutParams(layoutparams);
textview1.append("Description: "+description.get(i));
textview1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25);
textview1.setTextColor(Color.BLACK);
textview1.setPadding(25,25,25,25);
textview1.setGravity(Gravity.LEFT);
textview1.setLayoutParams(layoutparams2);
cardview.addView(textview);
cardview.addView(textview1);
l1.addView(cardview);
cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(PublicVote.this, n, Toast.LENGTH_SHORT).show();
n1 = Integer.parseInt(String.valueOf(n));
n1 = n1 + 1;
Log.d(Tag,"i->>: "+n1);
}
});
}
}
This is my code above here my n1 is the countValue which is updated everytime the user clicks the cardview it keeps on incrementing. Now I want to save this incremented value i.e. the countValue (n1 here)back to the database which is given below.
Now here the options 121 and 122 have count value 10 and 5 respectively which gets incremented by 1 when any one option is clicked, lets say 121 is clicked so new value is 11 and 5(remains the same). This 11 and 5 needs to be updated back to the database, need help with this!
Hum, I suggest to set the settings in the XML layout instead of the setting in the class, it's more easy to visualize. If I understood should be like this, unless is another variable.
If the variable n1 is counting the numbers
Log.d(Tag,"n1->>: "+ n1);
Try todo this:
Log.d(Tag,"n1->>: "+ (n1 + 1));
or setting the number outside the operation
n1 = n1 + 1;
This way every time they click on is going to set the number +1, try to do what i said about the settings in the xml.
you can use the two atomic operations in Cloud Firestore:
Transactions or Batch Writes on your snapshot and the document.
Update data with transactions when button click event is called.
Use Batch Writes at some point of interval.
Check this link for reference.
You can add your write back to firestore action inside onClick method as below.
cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(PublicVote.this, n, Toast.LENGTH_SHORT).show();
n1 = Integer.parseInt(String.valueOf(n));
n1 = n1 + 1;
Log.d(Tag,"i->>: "+n1);
//update database
//add your update code here.
}
});
You can find more on [Firebase] Cloud Firestore — Add, Set, Update, Delete, Get data

Android: How to get rid of EditText with null value using loop

First of all, here is my code:
startRandomizing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> values = new ArrayList<>();
int idList[] = new int[]{R.id.textBox1,R.id.textBox2,R.id.textBox3,
R.id.textBox4,R.id.textBox5,R.id.textBox6};
for(int id : idList){
if (findViewById(id) != null) {
values.add(((EditText) findViewById(id)).getText().toString());
}
}
String[] myItems = values.toArray(new String[values.size()]);
What I want to do is get rid of all the null values so that the length (myItems.length) of the array will depend on the value inside the text boxes 1 - 6.
(E.x - I have a string "Hello" in textBox1 and "World" in textBox2, and the rest empty. My desired output for myItems.length should be 2 since the remaining textBoxes do not have a value.)
This code outputs 6 (counts all the text boxes). Where have I gone wrong?
Change your code in the for loop as follows:
String s = ((EditText) findViewById(id)).getText().toString();
if(!TextUtils.isEmpty(s)){
values.add(s);
}

Random call name in Android

How to make a 'random call' name in List in database sqlite. How can I call one by one without repeating its value. My layout is one textview, If I click the name it will change. Thank you.
Untested, but should be fine:
Query your database, then use the returned Cursor to populate a LinkedList with whatever options you would like.
LinkedList list = new LinkedList();
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
list.add(cursor.getString(etc...);
}
}
Create a Random object, and use it to select and remove a random element from list each time:
Random rnd = new Random();
//The below section could be repeated on, for instance, a button click.
int randomValue = rnd.nextInt(list.size());
String result = list.get(randomValue);
list.remove(randomValue);
Each time an element is removed, the LinkedList will adjust in size to accommodate it, so no results will be repeated.
#PPartisan not working.
I add button to test the result from textview. 1 row only detected when I pressed back and back to activity the result is the same value. I clicked the button did not work.
rnd = new Random();
randomValue = rnd.nextInt(list.size());
result =list.get(randomValue).toString();
list.remove(randomValue);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
tv.setText(result);
}
});

Properly implementing/initializing lots of new variables, taken from RadioGroups and Spinners

I am developing a simple questionnaire-like app which includes lots of radio buttons joined into groups and spinners. I have multiple activities (6); some of them having RBs and some Spinners to let the user answer the questions.
The following step, which I have trouble with, is how to fetch lots of selections (of all the radio buttons/choices) and possibly do that in a for loop (so I don't have to initialize each new variable 30+ times in a row for just one activity). I've already assigned IDs to all of the views, but am having a hard time how to actually fetch the selection, initialize a new var corresponding to the selection (let's say radio button 1 in radio group 1 gives me a new variable with a value of 1) and then make the variables available to all of the activities (should I use global when initializing?).
My failed attempt on generating 10 variables for the first "page"
public void goTo2(View v) {
checkRB();
Intent intent1 = new Intent(Vprasalnik1.this, Vprasalnik2.class);
startActivity(intent1);
finish();
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
RadioButton "vRB" + i; //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Put variables into array like a
int size = 9;
RadioButton[] views = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
views[i] = (RadioButton)findViewByID(...);//For example
}
}
Or make a structure :
public class Choise
{
int mRadioButtonChoise;
int mSpinnerChoise;
}
And use something like this:
...
Choise c = new Choise();
c.mRadioButtonChoise = yourRadioButtonID;
c.mSpinnerChoise = youtSpinnerChoiseID;
...
Using a variable to identify a resource:
RadioButton[] rb = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
int id = context.getResources().getIdentifier("vRB" + i, "id", context.getPackageName())
rb[i] = (RadioButton)findViewByID(id);
}
}
If you have an array of RadioButtons then you can get all the values at the same time, however initializing them will have to be manual.
RadioButton rb[];
boolean rbc[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rbc=new boolean[200];
rb=new RadioButton[200]();
rb[0]=(RadioButton)findViewById(R.id.rb1);
rb[1]=(RadioButton)findViewById(R.id.rb2);
rb[2]=(RadioButton)findViewById(R.id.rb3);
rb[3]=(RadioButton)findViewById(R.id.rb4);
// many more.
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
rbc[i]=rb.isChecked(); //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Then before starting your intent add all relevant data to it.
So I've managed to cramp up the radio buttons activity, so that it finally works. If anyone is interested - I've used tags in xml code to properly assign values (1, 2 and 3 for each group of buttons) and managed to get an output in my testToast. At least I didn't have to initialize all of the variables manually - I've been saving the values into an ArrayList and then appended to them via StringBuilder.
Thanks to everyone who tried to help - it turned out I've needed a bit more research, testing and teasing my half-awake brain.
btn = (Button) findViewById(R.id.v3_btn1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 1; i <= 36; i++)
{
tmpRGid = "radioGroup_v3q" + i;
tmp2RGid = getResources().getIdentifier(tmpRGid, "id", getPackageName());
RGid = (RadioGroup) findViewById(tmp2RGid);
selectedOption = RGid.getCheckedRadioButtonId();
RBid = (RadioButton) findViewById(selectedOption);
addToIDList.add((String)RBid.getTag());
}
String testToast = "";
StringBuilder builder = new StringBuilder();
builder.append("Vaša izbira (");
for (int z=0; z < addToIDList.size(); z++) {
testToast = addToIDList.get(z);
builder.append(testToast + ", ");
}
builder.setLength(builder.length() - 2);
builder.append(") je bila shranjena.");
Toast.makeText(Vprasalnik3.this, builder, Toast.LENGTH_LONG).show();

Dynamic Button Onclick Listener

I am trying to create dynamic buttons. When clicking a button it should go to the specified url assigned to the text of the button.
For testing, first I tried to get that ID, if it is equal it prints the value of i. But whenever I clicked any one button, instead of telling that particular i value, it enters into whole loop, and prints all the values of i starting from 1 to 19 (the number of buttons that are dynamically created)
And after printing all values from 1 to 19, the program is getting force closed saying Null pointer exception.
I even tried by placing the handler code outside onCreate(), but I'm still getting the same error.
for ( i = 0; i <itemList.getTitle().size()-1; i++) {
title[i] = new TextView(this);
title[i].setTextColor( -16711936 );
title[i].setTextSize(18);
title[i].setText("Title = "+itemList.getTitle().get(i));
description[i] = new TextView(this);
description[i].setTextColor(-16776961);
description[i].setText("Description = "+itemList.getDescription().get(i)+"......");
more[i]=new Button(this);
more[i].setText(itemList.getLink().get(i));
layout.addView(title[i]);
System.out.println("Title view is set");
layout.addView(description[i]);
//System.out.println("Description view is set");
layout.addView(more[i]);
more[i].setOnClickListener(listener);
}
private OnClickListener listener=new OnClickListener(){
public void onClick(View arg) {
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
//System.out.println("Vlaue of I in onclick"+i);
//Uri uri=Uri.parse(itemList.getLink().get(i));
//startActivity(new Intent(Intent.ACTION_VIEW,uri));
//Toast.makeText(getApplicationContext(), "This button is clicked"+i+more[i].getText()+itemList.getLink().get(i),Toast.LENGTH_LONG).show();
}
}
You can use setTag() and getTag() method of View to identify different button.
for (i = 0; i < itemList.getTitle().size()-1; i++) {
...
more[i].setTag(i); // Use index of itemList as the tag
}
In onClick:
int index = (Integer)arg.getTag();
you can also set the id of button
more[i].setid(i);
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
As you can see here, i is still in your for loop.
Put the System.out.println("Value of i onclick is"+i); outside of your for loop and it should work
PS: format your code, it's easier to read that way and you'll notice small mistakes like these more easily
I think this will help you..
set button tag also dynamic like
more[i].setId(i);
and also changed condition like
if (more[i].getId() == i) {
index = i;
}
hope this will help you...

Categories

Resources