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
}
Related
in this program, I want to show on screen radio buttons with rooms name
buttonList = new RadioButton[roomNames.length];
btGroup = (RadioGroup) findViewById(R.id.roomList);
RadioGroup.LayoutParams rprms;
for(int i = 0; i < roomNames.length; i++)
{
//buttonList[i] = new RadioButton(this);
RadioButton tempBT = new RadioButton(this);
System.out.println("room name number :"+ i + roomNames[i]);
rprms= new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
//tempBT.setText(roomNames[i].subSequence(0,roomNames[i].length()));
//tempBT.setTextColor(0);
tempBT.setId(i);
buttonList[i] = tempBT;
btGroup.addView(tempBT, rprms);
//buttonList[i].setText(roomNames[i].subSequence(0,roomNames[i].length()));
//buttonList[i].setTextColor(0);
//btGroup.addView(buttonList[i], rprms);
}
for (int f = 0; f < btGroup.getChildCount(); f++) {
((RadioButton) btGroup.getChildAt(f)).setText(roomNames[f].subSequence(0,roomNames[f].length()));
((RadioButton) btGroup.getChildAt(f)).setTextColor(0);
}
//saving the chosen room name
btGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup arg0, int selectedId) {
for(int j = 0; j < buttonList.length; j++)
{
if(btGroup.getCheckedRadioButtonId() == buttonList[j].getId())
{
roomNameSelected = roomNames[j];
}
}
}
});
but when I run this program I see the radio buttons but there is no text inside
Instead of
setTextColor(0);
Try
setTextColor(Color.BLACK);
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);
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.
I have alertdialog with listview and listview header with "check all" and "uncheck all" button and listview footer with "Done" button. Listview is CHOICE_MODE_MULTIPLE with arrayList value EavesList. EavesList will be cross checked with another arrayList selectedItems to show those items as checked. the issue i am facing is Listview shows correct value but shows previous item as checked.
Here's my code:
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Select Category List");
final ListView modeList = new ListView(getActivity());
LayoutInflater inflater = LayoutInflater.from(getActivity());
View rootView = inflater.inflate(
R.layout.listview_header_eavesdrop, null);
modeList.addHeaderView(rootView);
Button btnDone = new Button(getActivity());
btnDone.setText("Done");
btnDone.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
final ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_multiple_choice,
android.R.id.text1, EavesList);
modeList.addFooterView(btnDone);
modeList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
modeList.setAdapter(modeAdapter);
if (selectedItems.size() != 0) {
for (int i = 0; i < EavesList.size(); i++) {
if (selectedItems.size() != 0) {
// modeList.setItemChecked(2, true);
for (int j = 0; j < selectedItems.size(); j++) {
if (EavesList.get(i).contains(
selectedItems.get(j))) {
modeList.setItemChecked(i, true);
Log.e("Selected Item ",
"there Values true "
+ selectedItems.get(j));
j = selectedItems.size() + 2;
}
}
} else {
Log.e("Selected Item ", "No Values");
}
}
} else {
for (int i = 0; i < EavesList.size(); i++) {
if (category.size() != 0) {
for (int j = 0; j < category.size(); j++) {
if (EavesList_id.get(i).contains(category.get(j))) {
modeList.setItemChecked(i, true);
Log.e("List " + EavesList_id.get(i), ""+ category.get(j));
Log.e("Selected category Item ",
"there Values true "
+ category.get(j));
} else {
if (j == category.size()) {
modeList.setItemChecked(i, false);
Log.e("Selected category Item ",
"there Values false "
+ category.get(j));
}
}
}
} else {
Log.e("Selected Item ", "No Values");
}
}
}
builder.setView(modeList);
final Dialog dialog = builder.create();
btnDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectedItems.clear();
eavesdropping.setText("");
SparseBooleanArray checked = modeList
.getCheckedItemPositions();
selected_community_id = new String[checked.size()];
String[] evas_id;
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add(EavesList.get(position));
selected_community_id[i] = EavesList_id
.get(position);
}
for (int i = 0; i < selected_community_id.length; i++) {
eavesdropping_hide.append(selected_community_id[i]);
if (i != selected_community_id.length ) {
eavesdropping_hide.append(",");
}
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
eavesdropping.append(outputStrArr[i]);
eavesdropping.append(" | ");
}
dialog.dismiss();
}
});
dialog.show();
P.S: Listview shows proper content but the checked item of listview is always one previous item is always checked and the item to be checked is unchecked.
Why don't try this method on your submit button click
SparseBooleanArray sparseBooleanArray = list.getCheckedItemPositions();
List<String> lstCheck= new ArrayList<String>();
for (int i = 0; i < list.getCount(); i++) {
if (sparseBooleanArray.get(i) == true) {
lstCheck.add(list.getItemAtPosition(i).toString());
}
}
Now as lstCheck will result in only the checked values compare it with your EavesList and find those items that do not exist and you will also have you non-selected values
Use the following: (it is pseudo code):
ArrayList<String> data;
ArrayList<String> checkboxes;
.....
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
if(chockBoxes.containds(data.get(position))){
chockBoxes.remove(data.get(position));
}else{
chockBoxes.add(data.get(position))
}
}
});
...
now in your adapter getView():
if(checkBoxes.contains(data.get(position))){
checkBox.setChecked(true);
}else{
checkBox.setChecked(false);
}
I made a program that computes the geometric mean and my program is already working but i have some sort of errors. Whenever i click the btnCalculate with an empty input in my inputValues my program stops working. how am I going to deal with this error? Thanks:)
final AutoCompleteTextView inputValues = (AutoCompleteTextView) findViewById(R.id.txt_input);
final TextView txtTotalNum = (TextView) findViewById(R.id.txt_totalNumber);
final TextView GeoMean= (TextView) findViewById(R.id.txt_GeoMean);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
});
Button btnclear = (Button)findViewById(R.id.btnclear);
btnclear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
inputValues.setText("");
txtTotalNum.setText("");
GeoMean.setText("");
}
You are getting errors because your code is trying to split on empty strings or null and then accessing values[] that really have no index at all. Just check if the string fetched by the EditText has a length>0.
#Override
public void onClick(View agr0) {
String fetchedValues = ( inputValues.getText().toString());
if(fetchedValues.length>0)
{
String []values = fetchedValues.split(",");
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
else
{
//alert the user that the field is empty
}
}
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
if(values !=NULL){
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
// try this
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
if(inputValues.getText().toString().length()>0){
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
});
Your program stops at
convertedValues[a] =Integer.parseInt(values[a]);
because for an empty input the split array has no values, so its length is 0. And when you try to access values[0]you get an ArrayIndexOutOfBoundsException.
Just check if the input is emty, before splitting it.
if(!inputValues.getText().toString().equals("")){
... // do your stuff
} else {
// show a message
}