Programmatically Add edittext iD - java

I already know how to create edittext programmatically but the problem is they have the same Id, How can I add random Id on each edittext generated

You don't need to set a unique id for each view. Just set different tags for them:
private static String getTag(int index) {
return "MY_TAG_" + index;
}
...
for (int i = 0; i < 3; i++) {
EditText editText = new EditText(this);
editText.setId(android.R.id.edit); // same id
editText.setTag(getTag(i)); // different tag
layout.addView(editText);
}
EditText firstField = layout.findViewWithTag(getTag(0));
System.out.println(firstField);
But, if you still want to, there's a static method View.generateViewId():
int[] fieldIds = new int[3];
for (int i = 0; i < 3; i++) {
fieldIds[i] = View.generateViewId();
EditText editText = new EditText(this);
editText.setId(fieldIds[i]); // different id
layout.addView(editText);
}
EditText firstField = layout.findViewById(fieldIds[0]);
System.out.println(firstField);
I/System.out: android.widget.EditText{ed04adc VFED..CL. ......I. 0,0-0,0 #1020003 android:id/edit}

You can use below code for each id's EditText
View.generateViewId()

Related

how to count filled edit text from multiple edittext

In my app have twenty edit text,but I want to count filled edit text and that data goes in anther activity through an array. Like when I filled 3 edit text from twenty, that 3 edit text data goes next page and that 3 count goes to next page as an int.
this is my 1st java class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
mspin=(Spinner) findViewById(R.id.spinner1);
submit = (Button) findViewById(R.id.btn1);
layout = (LinearLayout) findViewById(R.id.linear);
lay = (LinearLayout) findViewById(R.id.li);
edt=(EditText) findViewById(R.id.ed2);
sc = (ScrollView) findViewById(R.id.sc1);
int no = 20;
allEds = new ArrayList<EditText>();
for (int i=1;i<=no;i++){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
edtAdd = new EditText(SelectActivity.this);
layout.setLayoutParams(params);
allEds.add(edtAdd);
edtAdd.setHint("Enter Name" + i);
edtAdd.setId(i);
layout.addView(edtAdd);
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (allEds.size()<=9) {
Intent data = new Intent(SelectActivity.this, HalfPieChartActivity.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
data.putExtra("size", str); //you don't need to keep this in loop as its same.
data.putExtra("edt", edt.getText().toString());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData" + j, items[j]);
}
startActivity(data);
}
else {
Intent data = new Intent(SelectActivity.this, FullPieChartActivity.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
data.putExtra("size", str);// this is the line where I sent that count
data.putExtra("edt", edt.getText().toString());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData" + j, items[j]);//here is filled data send line
}
startActivity(data);
}
}
});
}
}
When I click submit 20 show in next page as an int.I want to sent that 3data and 3 as an int.
Please help me
As you have asked for sample in comment, i am posting my answer with sample.
In onclicklistener of your submit button you can add following code.
myNoneEmptyEdittextCounter = 0;
for (int i=1;i<=no;i++)
{
myEt = (EditText) findViewById(i);
if(!TextUtils.isEmpty(myEt.getText().toString()))
{
myNoneEmptyEdittextCounter +=1;
}
}
//myNoneEmptyEdittextCounter is count of your filled edittexts
This method will return list of data and its size will give you the int you are looking for which is number of filled items.
In submit button click
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edittextValues().isEmpty()) {
//nothing has been filled
} else {
//items in edittextValues() are your data.
edittextValues().size();//this is your int which is number of edit text filled.
}
}
}
I have mentioned in comments what each step does. Hope this helps.
Method edittextValues()
ArrayList<String> edittextValues() {
ArrayList<String> filledData = new ArrayList<>(); //initialise empty string array.
for (int i=1; i<=20; i++){ //loop through ids from 1 to 20
for (int j = 0; j< layout.getChildCount(); j++) { //loop through all the children of root layout
if(layout.getChildAt(j) instanceof EditText) { //filter EditText
EditText editText = (EditText) layout.getChildAt(j);
if(editText.getId() == i) { // filter the one which u programmatically added
if(!editText.getText().toString().isEmpty()) { // check if its not empty, that's the one you are looking
filledData.add(editText.getText().toString()); //add it to the list
}
}
}
}
}
return filledData; //return string list
}

Setting the context of a textview array

How do i apply a context to a textview array?
TextView[] textView = new TextView[3];
for (int cell = 0; cell < 3; cell++){
textView[cell].setText("-");
}
Apparently, this error gets thrown:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
If this was not a textview array, adding the activity context as a parameter when calling the constructor would render the object not null, solving my issue:
for (int cell = 0; cell < 3; cell++){
TextView textView = new TextView(context);
textView.setText("-");
}
Where, context = getActivity().getApplicationContext()
How do i set the context parameter for the textview array? What i want is dynamic variable names for each textview so i can call the individual textviews respectively.
You should create object before calling method.
Try this:
TextView[] textView = new TextView[3];
for (int cell = 0; cell < 3; cell++) {
textView[cell] = new TextView(context);
textView[cell].setText("-");
}
I hope below code would help you out regarding context for array of views. First you will just create array but before using it you will have to create object using new keyword.
LinearLayout rootview = (LinearLayout) findViewById(R.id.rootview);
ArrayList<String> words= new ArrayList<>();
words.add("One"); words.add("two"); words.add("three"); words.add("four"); words.add("five"); words.add("six"); words.add("seven"); words.add("eight"); words.add("nine"); words.add("ten");
int index=0;
while(index<words.size()){
TextView [] textViews = new TextView[words.size()];
textViews[index] = new TextView(this);
textViews[index].setText(words.get(index));
rootview.addView(textViews[index]);
index++;
}

Android Custom Listview view=null issue

I have an custom listview and textview,checkbox,edittext on it. I want to iterate my listview row and wanna take textview,checkbox and edittext values. When iteration comes up to end of the page cannot take invisible rows widget values and crashing. I have to scroll down my listview automatically i think. How can I fix this issue?
Note: I have 12 rows but it crashs after 6th row cz cannot see 7th row without scrolldown my listview.
This is my code:
public void onSave(View view) {
ArrayList<String> olcum = new ArrayList<String>();
ArrayList<String> orneklemebuyukluk = new ArrayList<String>();
EditText et;
CheckBox chx;
TextView buyukluk;
String nitel="0";
for (int i = 0; i < list_olcum_view.getCount(); i++) {
view = list_olcum_view.getChildAt(i);
et = (EditText) view.findViewById(R.id.edt_olcum);
chx=(CheckBox)view.findViewById(R.id.txt_orneklemenitel);
olcum.add(et.getText().toString());
}
}
Note: I have 12 rows but it crashs after 6th row cz cannot see 7th row without scrolldown my listview.
public void onSave(View view) {
ArrayList<String> olcum = new ArrayList<String>();
ArrayList<String> orneklemebuyukluk = new ArrayList<String>();
EditText et;
CheckBox chx;
TextView buyukluk;
String nitel="0";
for (int i = 0; i < list_olcum_view.getCount(); i++) {
view = list_olcum_view.getChildAt(i);
et = (EditText) view.findViewById(R.id.edt_olcum);
chx=(CheckBox)view.findViewById(R.id.txt_orneklemenitel);
olcum.add(et.getText().toString());
}
}

Android call method inside onClickListener with external parameters

So, I'm developing an app for my graduation final project and in my app I have a layout with an imageView and a textView, to set the content of these elements I receive an ArrayList as a parameter and use the setText(), and it works.
But my Arraylist has more than one element, and my big problem is that I want to change the content of the imageView and the textView when I click in a button.
The way I was thinking was that when I click the button it will increment the value and change the content of the objects for the next element inside the arrayList.
I've faced problems with global variables inside onClickListeners, but I solved them with auxiliar methods, but this time that doesn't work since I need to increment the value of the iteration inside the button event.
Can you guys please help me with suggestions or tell me what I'm I doing wrong?
I hope you understand my problem, and I'm sorry if I didn't explain me well, feel free to ask any questions and request more blocks of code if what I post isn't enough.
Thanks in advance to all you guys, i apreciate all the help you can give me!
To get the data from my db and store it into an arraylist
private ArrayList<Exercises> getExercisesSelectedPlan() {
ArrayList<ProgramExercises> arrayList_programExercises = new ArrayList<();
ArrayList<Exercises> arrayList_exercises = new ArrayList<>();
Button btnNext = (Button) findViewById(R.id.btnFinishAquecimento);
//with the id of the selected plan, select all the exercises from the plan and load them into the layout
int idProgram = getIdPlan();
DatabaseHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
String queryProgramExercises = "SELECT * FROM PROGRAM_EXERCISES WHERE PROGRAM_ID_PROGRAM = " + "'" + idProgram + "'" + " ORDER BY ORDER_EX ASC";
Cursor cursorProgramExercises = db.rawQuery(queryProgramExercises, null);
int numRows = cursorProgramExercises.getCount();
if (numRows > 0) {
cursorProgramExercises.moveToFirst();
while (numRows > 0) {
for (int i = 0; i < cursorProgramExercises.getCount(); i++) {
ProgramExercises nProgramExercises = new ProgramExercises();
nProgramExercises.setIdProgramExercises(cursorProgramExercises.getInt(0));
nProgramExercises.setOrder(cursorProgramExercises.getString(1));
nProgramExercises.setRepetition(cursorProgramExercises.getInt(2));
nProgramExercises.setIdExercises(cursorProgramExercises.getInt(3));
arrayList_programExercises.add(nProgramExercises);
numRows--;
}
}
}
//for each select result from program_exercises i have to select the exercise with the id correspondent to nProgramExercies.getidExercises
for (int i = 0; i < arrayList_programExercises.size(); i++) {
String queryExercises = "SELECT * FROM EXERCISES WHERE ID_EXERCISES = " + "'" + arrayList_programExercises.get(i).getIdExercises() + "'";
Cursor cursorExercises = db.rawQuery(queryExercises, null);
cursorExercises.moveToNext();
if (cursorExercises.getCount() > 0) {
Exercises exercises = new Exercises();
for (int j = 0; j < cursorExercises.getCount(); j++) {
exercises.setIdExercises(cursorExercises.getInt(0));
exercises.setMedia(cursorExercises.getString(1));
exercises.setDesignation(cursorExercises.getString(2));
exercises.setIdExercisesPhase(cursorExercises.getInt(3));
arrayList_exercises.add(exercises);
cursorExercises.moveToNext();
}
cursorExercises.close();
}
}
cursorProgramExercises.close();
db.close();
databaseHelper.close();
}
Where I want to change the content of the textview and increment the iteration when I click btnNext
public void prepareExercise(final ArrayList<Exercises> exercises) {
setContentView(R.layout.activity_execute_ex_warmup);
TextView txtPrepare = (TextView) findViewById(R.id.tvAquecimento);
ImageView imageExercise = (ImageView) findViewById(R.id.ivAquecimento);
Button btnNext = (Button) findViewById(R.id.btnFinishAquecimento);
txtPrepare.setText(exercises.get(1).getDesignation());
imageExercise.setImageResource(R.drawable.imgTest);
for (int i = 0; i < exercises.size(); i++) {
if (exercises.get(i).getIdExercisesPhase() == 1) {
txtPrepare.setText(exercises.get(i).getDesignation());
System.out.println("------ TEST" + exercises.get(i).getDesignation());
}
}
//Click Next Button
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//for (int i = 1; i < exercises.size(); i++) {
//TextView txtPrepare = (TextView) findViewById(R.id.tvAquecimento);
//txtPrepare.setText(exercises.get(finalI).getDesignation());
//}
//executeExercise(); //next Exercise
}
});
}
How I invoke the previous method
prepareExercise(getExercisesSelectedPlan());
Hopefully I'm understanding correctly.
If you just want to update the views each time the button is clicked the easiest way would be just to create a variable and store the position of the array list.
public int listIncrement = 0;
private TextView txtPrepare;
private ImageView imageExercise;
Then in your prepareExercise() method
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listIncrement <= excersises.size()) {
executeExercise(excersises, listIncrement); //next Exercise
listIncrement++;
}
}
});
and then in executeExercise(ArrayList exercises, int position) //guessed method name, can be whatever you like
txtPrepare.setText(exercises.get(position).getDesignation());
imageExercise.setImageResource(R.drawable.imgTest);

Make Button Array Invisible(Make an hint)

I want to make a Hint button, so when I click on it, I want to delete two buttons from the list (answers list). Now I don't know how to do it,ho w to make the for loop on the button array, so I can make this buttons invisible.
public class ClassicMode extends Activity {//מהמשחק עצמו
String pic;//תמונה של הדגל
Button answer1;//תשובות
Button answer2;
Button answer3;
Button answer4;
Button hint;
TextView guess;
TextView numOfGuess;
TextView score;
TextView scorenum;
DatabaseHandler db = new DatabaseHandler(this);
String fn;
Guesses G;
Bitmap bm;
Score s;
Button [] b = new Button[4];
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
score =(TextView)findViewById(R.id.score);
scorenum =(TextView)findViewById(R.id.scorenum);
scorenum.setText(String.valueOf(s.score));
guess =(TextView)findViewById(R.id.guesses);
numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
hint =(Button)findViewById(R.id.hint);
Flags f = new Flags();
Random r = new Random();//הדגל שיבחר לשאלה
int num = r.nextInt(160);//Up
f = db.getFlag(num);//הצגת הדגל הרנדומלי שיצא
fn = f.getName().toString();
pic = f.getImage().toString();
pic_view(pic);//מעבר לפונקציה להשמת התמונה של הדגל במשחק
//מערך ארבע כפתורים כנגד ארבע תשובות
b[0] = (Button)findViewById(R.id.button1);
b[1] = (Button)findViewById(R.id.button2);
b[2] = (Button)findViewById(R.id.button3);
b[3] = (Button)findViewById(R.id.button4);
List<String>Answers=new ArrayList<String>();//מערך תשובות
Answers.add(f.getName().toString());//הוספת התשובה הנכונה
for(int i=1;i<4;i++)
{
num = r.nextInt(200);
String valToAdd1 = db.getFlag(num).getName().toString();
if(!Answers.contains(valToAdd1)){
Answers.add(valToAdd1);
}
}
/*num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());//הוספת 3 תשובות רנדומליות
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());*/
Collections.shuffle(Answers);//ערבוב התשובות
for(int i=0;i<Answers.size();i++)
{
b[i].setText(Answers.get(i));//השמת התשובות מהמהערך למערך הכפתורים
}
}//end of OnCreat
Now what I've done (there is the function check, which check if you answered correctly and the hint which I don't know how to make):
public void check(View v)
{
Log.d("yes", fn);
Button b = (Button)v;
String text = b.getText().toString();
if(text.equals(fn))
{
s.score+=5;
resetQuiz();
}
else
{
s.score-=5;
if(Guesses.numOfGuesses==1)
{
G.setNumOfGuesses(3);
finish();//כאשר מספר הניחושים
return;
}
Guesses.numOfGuesses--;
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
}
}
public void hint(View v)
{
G.numOfGuesses--;
for(int i=0;i<2;i++)
for(int j=0;j<4;j++)
{
if()
}
}
Note: this is {mostly} pseudocode
I suggest keeping two separate lists of your answers. Your Flag object already holds the correct answer. You need a list to keep track of the wrong answers (so we don't have to loop and check against each item every time). You also need a list of all of them together that you can shuffle and display.
I took a little bit of liberty making your variable names longer so they are more clear.
onCreate() {
...
btnHint.setOnClickListener(hintOnClickListener);
...
Flag f = db.getFlag(randomNum); // This is the real question & answer
List<String> wrongAnswers = new ArrayList<String>(3);
List<String> allAnswers = new ArrayList<String>(4);
// Loop 3 times for 3 random wrong answers
for (int i=0; i<=3; i++) {
randNum = r.nextInt(200);
String randWrongAnswer = db.getFlag(randNum).getName().toString();
if (! wrongAnswers.contains(randWrongAnswer)) {
wrongAnswers.add(randWrongAnswer);
}
}
allAnswers.add(f.getName().toString());
allAnswers.addAll(wrongAnswers);
Collection.shuffle(allAnswers);
...
}
I like to declare all my listeners separately further down in the code, to keep the OnCreate method clean and legible.
private OnClickListener hintOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
G.numOfGuesses--;
// Since you shuffled the 'allAnswers' before displaying to the screen,
// we can just pick the first 2 answers from wrongAnswers list
// and it will appear to be random to the user.
for (int i=0; i < buttons.length; i++) {
String buttonText = buttons[i].getText().toString();
if (buttonText.equals(wrongAnswers.get(0))
|| buttonText.equals(wrongAnswers.get(1))) {
buttons[i].setVisibility(View.INVISIBLE);
}
}
}
};
Edit: to add hint logic based on OP's comment.

Categories