while(i < numCourses){
final int index = i;
//Create a Dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.input_dialog);
TextView textView = (TextView) dialog.findViewById(R.id.textView4);
textView.setText("" + i);
dialog.show();
//Button for the dialog.
Button b = (Button) dialog.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Get input Course Numbers, numCourses times
EditText editText = (EditText) dialog.findViewById(R.id.editText2); //EditText
String getInput = editText.getText().toString(); //String input
try {
courseNumbers[index] = Integer.parseInt(getInput);
Toast.makeText(MainActivity.this, "" + courseNumbers[index], Toast.LENGTH_SHORT).show();
}catch (Exception ex){}
//Dismiss dialog
dialog.dismiss();
}
});
i++;
}
This is what my variable int = i shows up in the Dialog, suppose numCourses was 4:
3
2
1
0
My question is why is decrementing backwards, instead of incrementing forward from 0 to 3. And to receive an array of inputs from a dialog, how can I efficiently ask for input, numCourses times? Instead of me having a while loop and incrememnting i, which I feel is not efficient.
Not using loop, after each input has been clicked, then show the next dialog.
public void showCourseDialog(final int i, final int numCourses){
final int index = i;
//Create a Dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.input_dialog);
TextView textView = (TextView) dialog.findViewById(R.id.textView4);
textView.setText("" + i);
dialog.show();
//Button for the dialog.
Button b = (Button) dialog.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Get input Course Numbers, numCourses times
EditText editText = (EditText) dialog.findViewById(R.id.editText2); //EditText
String getInput = editText.getText().toString(); //String input
try {
courseNumbers[index] = Integer.parseInt(getInput);
Toast.makeText(MainActivity.this, "" + courseNumbers[index], Toast.LENGTH_SHORT).show();
}catch (Exception ex){}
//Dismiss dialog
dialog.dismiss();
if(i < numCourses)
showCourseDialog(++i, numCourses);
}
});
}
Related
I have this code but the problem is that this continually showing toast of each string line when I pressed my desired button.
Like this:
Clicked the button once:
Toast shows continually:
A
B
C
What I want is to get string from a single line once I click the button.
Like this:
EditText value:
A
B
C
Result first click:
A only
Result second click:
B only
Result third click:
C only
Like that
Btw this is the code I use:
Button checkButton = (Button) findViewById(R.id.check_Button);
checkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText editBox = (EditText) findViewById(R.id.edit_Text);
String items = editBox.getText().toString();
Scanner scanner = new Scanner(items);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Toast.makeText(getApplicationContext(), line, Toast.LENGTH_SHORT).show();
}
scanner.close();
}
}
);
I know it's hard to understand but please bare with me.
I think you can go for an approach like this.
int clicks = 0;
Button checkButton = (Button) findViewById(R.id.check_Button);
checkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText editBox = (EditText) findViewById(R.id.edit_Text);
String items = editBox.getText().toString();
if (i == 0) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i++;
editBox.setText("");
} else if (i == 1) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i++;
editBox.setText("");
} else if (i==2) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i = 0;
}
}
}
Just enter a value in the editText when the value is reset after a single button click.
int position=0;
EditText editText=findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {
}
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if(charSequence.length()<=0)
{
position=-1;
}
else{
position=0;
}
}
});
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
int length=editText.getText().length();
if(position==-1){
Toast.makeText(getApplicationContext(),"Nothing in EditText box",Toast.LENGTH_LONG).show();
return;
}
if(position==length){
position=0;
}
Toast.makeText(getApplicationContext(),editText.getText().charAt(position),Toast.LENGTH_LONG).show();
position++;
}
});
I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;
I need help trying to fix my code. I thought it was simple (probably is) but I can't get it. I am have a simple adding calculator. It works fine, but if I leave 1 or both Number text fields empty, the program crashes.
I have my if statement, but apparently I am not telling it to do the right thing.
public class MainActivity extends Activity {
Double firstNum, secondNum, answerNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText) findViewById(R.id.txtFirst);
final EditText second = (EditText) findViewById(R.id.txtSecond);
final TextView answer = (TextView) findViewById(R.id.txtAnswer);
Button calc = (Button) findViewById(R.id.btnCalc);
calc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// convert pulled info to double using variable names
firstNum = Double.parseDouble(first.getText().toString());
secondNum = Double.parseDouble(second.getText().toString());
if (first == null || second == null)
{
Toast.makeText(MainActivity.this, "Please Enter value", Toast.LENGTH_SHORT).show();
}
else {
// add numbers
answerNum = (firstNum + secondNum);
//set format
DecimalFormat total = new DecimalFormat ("###,###,###.##");
answer.setText("Answer is " + total.format(answerNum));
}
}
});
}
}
You have exception because of line: Double.parseDouble(second.getText().toString()), it cannot parse empty string to double, so you should add some validation code.
If you want to validate edittext means try this following code it will work fine.
public class MainActivity extends Activity {
double firstNum = 0;
double secondNum = 0, answerNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText) findViewById(R.id.editText1);
final EditText second = (EditText) findViewById(R.id.editText2);
final TextView answer = (TextView) findViewById(R.id.textView1);
Button calc = (Button) findViewById(R.id.button1);
calc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (first.getText().toString().equals("")
|| second.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please Enter value",
Toast.LENGTH_SHORT).show();
} else {
firstNum = Double.parseDouble(first.getText().toString());
secondNum = Double.parseDouble(second.getText().toString());
answerNum = (firstNum + secondNum);
DecimalFormat total = new DecimalFormat("###,###,###.##");
answer.setText("Answer is " + total.format(answerNum));
}
}
});
}
}
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.
I have an ArrayList in which the input of dynamically added EditTexts are referenced. I iterate the ArrayList so that I can get all the values of the EditTexts and add them together. However, I do have one non-dynamically added EditText that is already laid out in my layout.xml.
The problem is that whenever I click my Calculate Button and the only EditText on the screen is the already laid out EditText and it has an input of 1 or any other number, my Calculate Button shows the total input as 0. Whenever I add 1 or more editTexts dynamically, the total input includes the already laid out EditText after I click the Calculate Button.
I need to get the correct total input even if the only input is the non-dynamic editText.
int count = 1;
double gradeValue;
List<EditText> allEd = new ArrayList<EditText>();
List<Spinner> allSp = new ArrayList<Spinner>();
EditText editText1;
EditText editText2;
EditText tempText1;
EditText tempText2;
Spinner spinner1;
Spinner spinnerTemp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonAdd = (Button) findViewById(R.id.button1);
Button buttonDel = (Button) findViewById(R.id.button2);
Button buttonCalc = (Button) findViewById(R.id.button3);
spinner1 = (Spinner) findViewById(R.id.spinner1);
String[] options = new String[13];
options[0] = "A+";
options[1] = "A";
options[2] = "A-";
options[3] = "B+";
options[4] = "B";
options[5] = "B-";
options[6] = "C+";
options[7] = "C";
options[8] = "C-";
options[9] = "D+";
options[10] = "D";
options[11] = "D-";
options[12] = "F";
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, options);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner1.setAdapter(spinnerArrayAdapter);
allEd.add(editText2);
allSp.add(spinner1);
buttonAdd.setOnClickListener(this);
buttonDel.setOnClickListener(this);
buttonCalc.setOnClickListener(this);
}
#SuppressWarnings("deprecation")
public void onClick(View v) {
TableLayout tableLayout1 = (TableLayout) findViewById(R.id.tableLayout1);
switch(v.getId()){
case R.id.button1:
if(count != 16){
count++;
// Create the row only when the add button is clicked
TableRow tempRow = new TableRow(MainActivity.this);
EditText tempText1 = new EditText(MainActivity.this);
EditText tempText2 = new EditText(MainActivity.this);
TextView tempTextView = new TextView(MainActivity.this);
Spinner spinnerTemp = new Spinner(MainActivity.this);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
TextView textView3 = (TextView) findViewById(R.id.textView3);
tempTextView.setText(count + ".");
tempRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tempText1.setLayoutParams(editText1.getLayoutParams());
tempText2.setLayoutParams(editText2.getLayoutParams());
tempTextView.setLayoutParams(textView3.getLayoutParams());
tempText1.setInputType(InputType.TYPE_CLASS_TEXT);
tempText2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
tempText2.setId(count);
spinnerTemp.setLayoutParams(spinner1.getLayoutParams());
spinnerTemp.setId(count);
String options[] = { "A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F" };
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, options);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinnerTemp.setAdapter(spinnerArrayAdapter);
allEd.add(tempText2);
allSp.add(spinnerTemp);
tempRow.addView(tempTextView);
tempRow.addView(tempText1);
tempRow.addView(tempText2);
tempRow.addView(spinnerTemp);
tableLayout1.addView(tempRow);
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); //Read Update
alertDialog.setTitle("Error");
alertDialog.setMessage("You can only have up to 16 rows!");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
break;
case R.id.button3:
int calculation = 0;
for(int i = 0; i < allEd.size(); i++) {
EditText totalUnits = allEd.get(i);
try {
int units = Integer.parseInt(totalUnits.getText().toString());
calculation += units;
}catch (Exception e) {
//ignore
}
}
double grade = 0;
for(int i = 0; i < allSp.size(); i++) {
double gradeValue = calcGradeValue(allSp.get(i).getSelectedItemPosition());
try {
double calculation1 = (gradeValue) * (Integer.parseInt(allEd.get(i).getText().toString()));
grade += calculation1;
}catch (Exception e) {
//ignore
}
}
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); //Read Update
alertDialog.setTitle("Your calculated GPA");
alertDialog.setMessage("Your calculated GPA is: " + (grade));
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
I think you need to take a look at where your adding the tempText2 editText to your list. Check that it isn't as a result of adding the dynamic editTexts.
Look at where you add the following
allEd.add(tempText2);
allEd.add(editText2);
It could be that your only adding the tempText2 as a result of adding a dynamic field. As such when you don't add a dynamic field the arraylist will be empty. resulting in 0. When you do add a dynamic field this will result in the calculation working.
Difficult to say this is it without more code.
I think that maybe u dont initilized value editText2, and u try to add null object to list, but I really cant say anything without any source code.