get value from edit text within a loop - android

I have a question, as I can get all the data that has been inserted into the edit text? the edit text is on a loop, I need a way to get those values ​​and work with them, try using an array but I get errors. could help me? any idea? Help!
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final Button generate = (Button) findViewById(R.id.generate);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}

You can create multiple edittext by using array.
public class MainActivity extends Activity{
EditText[] sample_et;
int numberOfControlsToGenerate = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
LinearLayout root_layout = (LinearLayout)findViewById(R.id.root);
sample_et = new EditText[numberOfControlsToGenerate];
//numberOfControlsToGenerate is decleres statically you can get the count from edit text
for(int i = 0; i < count; i++ ){
sample_et[i] = new EditText(this);
root_layout.addView(sample_et[i]);
}
}
}

Add setTag when you create dynamic EditText
add line in addEditText(LinearLayout container) method
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
editTextToAdd.setTag(editTextToAdd); //Add this Line
container.addView(editTextToAdd);
}
Write code onClick listener on any Button
getvalue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < container.getChildCount(); i++) {
if(container.getChildAt(i) instanceof EditText) {
EditText et = (EditText) container.getChildAt(i).getTag();
if(et != null) {
Log.i("<Tag Name>", et.getText().toString());
}
}
}
}
});

Related

Referencing an input :(

i was wondering if anyone could tell me how to use my input/EditText as the value for the max value (line 15, where the .nextInt(1000) is) for this random number generator. I've tried looking up how to do it and asked. Any help is greatly appreciated!
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.textView1);
Button pushMe = (Button) findViewById(R.id.button1);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
// TODO Auto-generated method stub
Random randGen = new Random();
int rando = randGen.nextInt(1000) + 1;
randText = Integer.toString(rando);
textOne.setText(randText);
}
});
}
If you have an EditText in your layout with android:id="#+id/editText1", then this would be one way:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.textView1);
final EditText editText = (EditText) findViewById(R.id.editText1);
Button pushMe = (Button) findViewById(R.id.button1);
pushMe.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Random randGen = new Random();
String randText = "";
int max = 0;
String input = editText.getText().toString();
try
{
max = Integer.parseInt(input);
int rando = randGen.nextInt(max) + 1;
randText = Integer.toString(rando);
}
catch (IllegalArgumentException e)
{
randText = "Invalid input";
}
textOne.setText(randText);
}
}
);
}
Please note that catch (IllegalArgumentException e) will catch both the IllegalArgumentException that Random.nextInt() can throw, as well as the NumberFormatException that Integer.parseInt() can throw.

Android ObserveableScrollView to load more (loading issue)

I am fetching information from the website in JSON Format and displaying that info into my app using AsynTask. The Problem is that on On First time my Progress dialog shows well and hide after loading contents into app. But When i use Scroll-view to load more then progress dialog appears and hide after loading immediately at the same time progress dialog opens again and not hiding and Scroll-View loads data one more time in the background.I want only one time to load data after each using Scroll-View to load more. Progress Dialog is not hiding and It keeps running my app. I am struck at this point.
Basically i noticed that My Scroll-View indicator collide two times on the bottom due to this scroll-View trigger two times. How can i stop it and restrict this only one time after each scrolling.
And one more thing wanna share that everything is working awesome in Froyo 2.2 and not working in 2.3 to 4.2. Kindly help me on this. Thanks in advance.
Below is my code.
package com.example.lmf;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.lmf.ObservableScrollView.ScrollViewListener;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
public class searchClassified extends Activity implements ScrollViewListener
{
ObservableScrollView scrollView;
ProgressDialog _progressDialog;
int page_no = 1;
String k = "";
final static String URL = "http://www.lmf.com.pk/admin/json.php?YOUR URL OF JSON";
final getInternetData obj = new getInternetData();
public ImageLoader imageLoader = null;
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_classified);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
scrollView = (ObservableScrollView) findViewById(R.id.my_scroll);
scrollView.setScrollViewListener(this);
imageLoader = new ImageLoader(this);
String s = getIntent().getExtras().getString("query")!= "" ? getIntent().getExtras().getString("query") : "";
EditText et = (EditText) findViewById(R.id.query);
et.setText(s);
k = "all="+URLEncoder.encode(s);
//showProgress(context);
new getBackgroundData().execute();
}
public void onScrollEnded(ObservableScrollView scrollView, int x, int y,
int oldx, int oldy) {
// TODO Auto-generated method stub
page_no = page_no + 1;
k = k+"&page_no="+page_no;
//showProgress(context);
getBackgroundData d1 = new getBackgroundData();
d1.execute();
if(d1.getStatus()==AsyncTask.Status.FINISHED) {
d1 = null;
_progressDialog.dismiss();
}
}
public void searchAds(View v)
{
EditText query = (EditText) findViewById(R.id.query);
String q = query.getText().toString();
if(q == "" || q == "search")
{
Dialog d = new Dialog(this);
d.setTitle("Enter Valid Search Parameter");
d.show();
}
else
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Intent i = new Intent(searchClassified.this,com.example.lmf.searchClassified.class);
i.putExtra("query", ""+q+"");
startActivity(i);
}
}
public void showProgress(Context c)
{
_progressDialog = ProgressDialog.show(
c,
"Please wait",
"Performing task..."
);
}
public void hideProgress()
{
_progressDialog.dismiss();
}
//////////// Async Class
private class getBackgroundData extends AsyncTask<Void, Integer, JSONArray>
{
protected void onPreExecute()
{
_progressDialog = new ProgressDialog(context);
_progressDialog.setMessage("Loading...");
_progressDialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
try
{
JSONArray array = obj.getDATA(k,URL);
return array;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray array)
{
LinearLayout sv = (LinearLayout) findViewById(R.id.data);
try
{
for (int i = 0; i <array.length(); i++) {
JSONObject row = array.getJSONObject(i);
//// TextView Creation start here /////////
TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
tv.setText(row.getString("post_title"));
tv.setTextColor(Color.BLACK);
tv.setTextSize(14);
tv.setPadding(8, 6, 0, 12);
tv.setFocusable(true);
tv.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
//// TextView Creating Ends here /////////
//// Horizontal Line Creating here /////////
View v = new View(searchClassified.this);
LinearLayout.LayoutParams viewLp = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
viewLp.setMargins(0, 4, 0, 4);
v.setLayoutParams(viewLp);
v.setBackgroundColor(Color.LTGRAY);
//// Horizontal Line Creating Ends here /////////
//// Image Creating Starts from here /////////
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(3, 0, 15, 8);
lp.width = 70;
lp.height = 80;
ImageView imageView = new ImageView(searchClassified.this);
String[] parts = row.getString("post_img").split("/");
int last_index = parts.length - 1;
String image_name = "thumb_"+parts[last_index];
String str = "";
for(int j=0; j<last_index; j++)
{
str += parts[j]+"/";
}
String path = "http://www.lmf.com.pk/"+str+image_name;
imageLoader.DisplayImage(path, imageView);
//// Image Creating Ends here /////////
// Creating LinearLAyout /////////
LinearLayout l1 = new LinearLayout(searchClassified.this);
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setHapticFeedbackEnabled(true);
l1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
l1.setId(obj.convertStrtoInt(row.getString("post_id")));
l1.setHapticFeedbackEnabled(true);
l1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(searchClassified.this,com.example.lmf.adsDetail.class);
i.putExtra("id", v.getId());
startActivity(i);
}
});
l1.addView(imageView, lp);
l1.addView(tv);
sv.addView(l1);
sv.addView(v);
}
_progressDialog.hide();
_progressDialog.dismiss();
_progressDialog = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
/////////// Ends Here
public boolean onCreateOptionsMenu(Menu menu)
{
MenuItem item = menu.add ("Quit");
item.setOnMenuItemClickListener (new OnMenuItemClickListener()
{
public boolean onMenuItemClick (MenuItem item)
{
//clearArray();
finish();
return true;
}
});
return true;
}
}
I have Solved this issue and want to share with the future readers. I made a switch and add cases now the new Scroll-View trigger can not run until the previous data will not complete loads.
Here is the final code and hope will help you friends. Thanks
package com.example.lmf;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.lmf.ObservableScrollView.ScrollViewListener;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
public class searchClassified extends Activity implements ScrollViewListener
{
ObservableScrollView scrollView;
ProgressDialog _progressDialog;
int page_no = 1;
String k = "";
final static String URL = "Your URL HERE For Getting JSON";
final getInternetData obj = new getInternetData();
public ImageLoader imageLoader = null;
Context context = this;
int num = 1;
private static final int SPLASH_DURATION = 3000; // 3 seconds
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_classified);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
scrollView = (ObservableScrollView) findViewById(R.id.my_scroll);
scrollView.setScrollViewListener(this);
imageLoader = new ImageLoader(this);
String s = getIntent().getExtras().getString("query")!= "" ? getIntent().getExtras().getString("query") : "";
EditText et = (EditText) findViewById(R.id.query);
et.setText(s);
k = "all="+URLEncoder.encode(s);
showProgress();
new getBackgroundData().execute();
}
public void onScrollEnded(ObservableScrollView scrollView, int x, int y, int oldx, int oldy)
{
// TODO Auto-generated method stub
page_no = page_no + 1;
k = k+"&page_no="+page_no;
switch(num)
{
case 1:
showProgress();
new getBackgroundData().execute();
num = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
num = 1;
}
}, SPLASH_DURATION);
break;
case 0:
num = 0;
break;
}
}
public void searchAds(View v)
{
EditText query = (EditText) findViewById(R.id.query);
String q = query.getText().toString();
if(q == "" || q == "search")
{
Dialog d = new Dialog(this);
d.setTitle("Enter Valid Search Parameter");
d.show();
}
else
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Intent i = new Intent(searchClassified.this,com.example.lmf.searchClassified.class);
i.putExtra("query", ""+q+"");
startActivity(i);
}
}
public void showProgress()
{
_progressDialog = new ProgressDialog(context);
_progressDialog.setMessage("Loading...");
_progressDialog.show();
}
public void hideProgress()
{
_progressDialog.dismiss();
}
//////////// Async Class
private class getBackgroundData extends AsyncTask<Void, Integer, JSONArray>
{
#Override
protected JSONArray doInBackground(Void... params)
{
try
{
JSONArray array = obj.getDATA(k,URL);
return array;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray array)
{
LinearLayout sv = (LinearLayout) findViewById(R.id.data);
try
{
for (int i = 0; i <array.length(); i++) {
JSONObject row = array.getJSONObject(i);
//// TextView Creation start here /////////
TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
tv.setText(row.getString("post_title"));
tv.setTextColor(Color.BLACK);
tv.setTextSize(14);
tv.setPadding(8, 6, 0, 12);
tv.setWidth(350);
tv.setHeight(100);
tv.setFocusable(true);
LinearLayout.LayoutParams tvPar = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//tvPar.weight = 2;
tv.setLayoutParams(tvPar);
//// TextView Creating Ends here /////////
//// Horizontal Line Creating here /////////
View v = new View(searchClassified.this);
LinearLayout.LayoutParams viewLp = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
viewLp.setMargins(0, 4, 0, 4);
v.setLayoutParams(viewLp);
v.setBackgroundColor(Color.LTGRAY);
//// Horizontal Line Creating Ends here /////////
//// More Detail Icon Ends /////////////////////
ImageView more_info_icon = new ImageView(searchClassified.this);
//setting image resource
more_info_icon.setImageResource(R.drawable.arrow);
//setting image position
LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//par.weight = 1;
more_info_icon.setLayoutParams(par);
more_info_icon.getLayoutParams().height = 30;
more_info_icon.getLayoutParams().width = 30;
more_info_icon.setPadding(0, 14, 0, 0);
/// More Detail Icon Ends Here /////////////////////
//// Image Creating Starts from here /////////
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,4);
lp.weight = 1;
lp.setMargins(3, 0, 15, 8);
lp.width = 70;
lp.height = 80;
ImageView imageView = new ImageView(searchClassified.this);
String[] parts = row.getString("post_img").split("/");
int last_index = parts.length - 1;
String image_name = "thumb_"+parts[last_index];
String str = "";
for(int j=0; j<last_index; j++)
{
str += parts[j]+"/";
}
String path = "http://www.lmf.com.pk/"+str+image_name;
imageLoader.DisplayImage(path, imageView);
//// Image Creating Ends here /////////
// Creating LinearLAyout /////////
final LinearLayout l1 = new LinearLayout(searchClassified.this);
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setHapticFeedbackEnabled(true);
LinearLayout.LayoutParams LParam = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LParam.weight = 4;
l1.setLayoutParams(LParam);
l1.setId(obj.convertStrtoInt(row.getString("post_id")));
l1.setHapticFeedbackEnabled(true);
l1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
l1.setBackgroundColor(Color.GREEN);
//l1.setBackgroundColor(Color.WHITE);
Intent i = new Intent(searchClassified.this,com.example.lmf.adsDetail.class);
i.putExtra("id", v.getId());
startActivity(i);
}
});
l1.addView(imageView, lp);
l1.addView(tv);
l1.addView(more_info_icon);
sv.addView(l1);
sv.addView(v);
}
hideProgress();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
/////////// Ends Here
public boolean onCreateOptionsMenu(Menu menu)
{
MenuItem item = menu.add ("Quit");
item.setOnMenuItemClickListener (new OnMenuItemClickListener()
{
public boolean onMenuItemClick (MenuItem item)
{
//clearArray();
finish();
return true;
}
});
return true;
}
}

Getting zero as result (android)

I am getting zero as the output. I couldnt find any errors in it
any help would be great.
full code:
package com.equbez.resistor_decoder;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Second extends Activity {
int i,b1,b2,b3,result,four;
String one,two,three;
String arr[]={"black","brown","red","orange","yellow","green","blue","violet","grey","white"};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
EditText etone=(EditText) findViewById(R.id.editText1);
one=etone.getText().toString();
for(i=0;i<9;i++) {
if(one.equalsIgnoreCase(arr[i])) {
b1=i;
}
}
EditText ettwo=(EditText) findViewById(R.id.editText2);
two=ettwo.getText().toString();
for(i=0;i<9;i++) {
if(two.equalsIgnoreCase(arr[i])) {
b2=i;
}
}
EditText etthree=(EditText) findViewById(R.id.editText3);
three=etthree.getText().toString();
for(i=0;i<9;i++) {
if(three.equalsIgnoreCase(arr[i])) {
b3=i;
}
}
result=b2+b2+b3;
Button bfour=(Button) findViewById(R.id.button4);
bfour.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View V) {
TextView tv=(TextView) findViewById(R.id.textView4);
tv.setText(""+result);
}
});
}
}
any help would be great.
initially the EditTextView will be empty when the activity is called. so you always get an empty string which you are comparing to the Strings in arr[].
b1, b2, b3 are initialized to default values ie.,, '0' hence result is always '0'
write all the getText code in the bfour.setOnClickListener()
or else implement TextWatcher and use onTextChanged method
use
for(i = 0 ; i< arr.length ;i++)
do something
In your code if you are inputting white its not getting compared
Are you giving any spaces while inputing the string at the end? once check the length of the string that you give as input whether its exact or not
Here i have re-coded with the changes, try out this code,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Second extends Activity
{
private static int b1,b2,b3,result,four;
private String one,two,three;
private String arr[]={"black","brown","red","orange","yellow","green","blue","violet","grey","white"};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
EditText etone=(EditText) findViewById(R.id.editText1);
one=etone.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(one.trim().equalsIgnoreCase(arr[i].trim()))
{
b1=i;
break;
}
}
EditText ettwo=(EditText) findViewById(R.id.editText2);
two=ettwo.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(two.trim().equalsIgnoreCase(arr[i].trim()))
{
b2=i;
break;
}
}
EditText etthree=(EditText) findViewById(R.id.editText3);
three=etthree.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(three.trim().equalsIgnoreCase(arr[i].trim()))
{
b3=i;
break;
}
}
result=b2+b2+b3;
Button bfour=(Button) findViewById(R.id.button4);
bfour.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View V)
{
TextView tv=(TextView) findViewById(R.id.textView4);
tv.setText( String.valueOf(result));
}
});
}
}
I got the problem. You have to run your all 3 loops after clicking the button. you have done that on Oncreate(). So you always get 0.
see below:
int i, b1, b2, b3, result, four;
String one, two, three;
String arr[] = { "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" };
EditText etone, ettwo, etthree;
Button bfour;
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
etone = (EditText) findViewById(R.id.editText1);
ettwo = (EditText) findViewById(R.id.editText2);
etthree = (EditText) findViewById(R.id.editText3);
bfour = (Button) findViewById(R.id.button4);
bfour.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
one = etone.getText().toString();
for (i = 0; i < arr.length; i++) {
if (one.equals(arr[i])) {
b1 = i;
System.out.println("dhrupal one="+b1);
}
}
two = ettwo.getText().toString();
for (i = 0; i < arr.length; i++) {
if (two.equals(arr[i])) {
System.out.println("dhrupal one="+two);
b2 = i;
}
}
three = etthree.getText().toString();
for (i = 0; i < arr.length; i++) {
if (three.equals(arr[i])) {
System.out.println("dhrupal one="+three);
b3 = i;
}
}
result = b1 + b2 + b3;
tv = (TextView) findViewById(R.id.textView4);
tv.setText("result=" + result);
}
});
}

Change the value of EditText with onClick Button?

In main.xml I made a row containing a TextView, an EditText and a "+" and "-" button.
Underneath that I made an "Add" button that will help you create a new row When you click the add button, you get an EditText and a Submit and Cancel button.
On "Submit" it outputs the EditText value to the TextView and creates the same row as the first one.
The numeric value "NewValueBox" should +1 when the "+" button is pressed.
But because I call it in another function it is not recognized by createNewAddButton() function in which the button is set up.
So in short:
"How do I change the value of NewValueBox when I click NewAddButton?"
Here's the code:
package com.lars.MyApp;
import com.google.ads.*;
import com.lars.MyApp.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
public class DrinkRecOrderActivity extends Activity {
int currentValue1 = 0;
int currentValueNew = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText firstValue = (EditText) findViewById(R.id.firstValue);
Button valuePlus = (Button) findViewById(R.id.valuePlus);
Button valueMinus = (Button) findViewById(R.id.valueMinus);
final Button addValue = (Button) findViewById(R.id.add);
final TableLayout tableLayout1 = (TableLayout) findViewById(R.id.tableLayout1);
final LinearLayout addValueRow = (LinearLayout) findViewById(R.id.addValueRow);
final EditText addNewValue = (EditText) findViewById(R.id.addNewValue);
final Button submitNewValue = (Button) findViewById(R.id.submitNewValue);
final Button cancelNewValue = (Button) findViewById(R.id.cancelNewValue);
// BEGIN ONCLICKLISTENERS
valuePlus.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
plusValue();
firstValue.setText("" + currentValue1);
}
});
valueMinus.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
minValue();
firstValue.setText("" + currentValue1);
}
});
addValue.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
addValueRow.setVisibility(View.VISIBLE);
addValue.setVisibility(View.GONE);
}
});
cancelNewValue.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
addValueRow.setVisibility(View.GONE);
addValue.setVisibility(View.VISIBLE);
}
});
submitNewValue.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tableLayout1.addView(createnewRow());
addValueRow.setVisibility(View.GONE);
addValue.setVisibility(View.VISIBLE);
addNewValue.setText("");
}
});
// END ONCLICKLISTENERS
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
}
public TableRow createNewRow() {
final TableRow newRow = new TableRow(this);
final EditText addNewValue = (EditText) findViewById(R.id.addNewValue);
newRow.addView(createNewTextView(addNewValue.getText().toString()));
newRow.addView(createNewValueBox());
newRow.addView(createNewAddButton());
newRow.addView(createNewMinusButton());
return newRow;
}
public TextView createNewTextView(String text) {
final TextView textView = new TextView(this);
textView.setText(text);
return textView;
}
public EditText createNewValueBox() {
EditText NewValueBox = new EditText(this);
NewValueBox.setHint("0");
NewValueBox.setInputType(InputType.TYPE_CLASS_NUMBER);
return NewValueBox;
}
public Button createNewAddButton() {
final Button NewAddButton = new Button(this);
NewAddButton.setText("+");
NewAddButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
plusNew();
//NewValueBox.setText("" + currentValueNew);
}
});
return NewAddButton;
}
public Button createNewMinusButton() {
final Button NewMinusButton = new Button(this);
NewMinusButton.setText("-");
return NewMinusButton;
}
// BEGIN PLUS AND MIN FUNCTIONS
public void plusNew() {
if (currentValueNew <= 999) {
currentValueNew = currentValueNew + 1;
}
}
public void plusValue() {
if (currentValue1 <= 999) {
currentValue1 = currentValue1 + 1;
}
}
public void minValue() {
if (currentValue1 >= 1) {
currentValue1 = currentValue1 - 1;
}
}
// END PLUS AND MIN FUNCTIONS
}
Add IDs for your Views so you can later reference them. Make 3 private static int field in your activity(the ID for NewValueBox, NewAddButton and NewMinusButton):
private static int edt = 1;
private static int add = 1001;
private static int minus = 2001;
Then in your createNewValueBox() method set the ID:
NewValueBox.setId(edt);
edt++;
Do the same for the NewAddButton and the NewMinusButton:
NewAddButton.setId(add);
add++;
NewMinusButton.setId(minus);
minus++;
Then in your listener for the buttons find out exactly which add button has been clicked and set the text in the corresponding EditText:
NewAddButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
plusNew();
int tmp = v.getId();
EditText temp = (EditText) findViewById(1 + (tmp - 1001));
temp.setText("" + currentValueNew);
}
Kind of hackish method.

Android - How to add a"0" when "button" is clicked if TextBox is empty ""

i want to set a "0" in each "empyt" TextBoxes if the user clicks one button, to avoid an error in the app, any help? i dont know what to do
package com.doko.most;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class doko extends Activity {
private EditText bx1;
private EditText bx2;
private TextView txt3;
private Button btncalcular;
private Button btnreset;
private double variable1 = 0;
private double variable2 = 0;
private double variable3 = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
bx1 = (EditText)findViewById(R.id.bx1);
bx2 = (EditText)findViewById(R.id.bx2);
txt3 = (TextView)findViewById(R.id.txt3);
btncalcular = (Button)findViewById(R.id.btncalcular);
btnreset = (Button)findViewById(R.id.btnreset);
btncalcular.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calcular(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
}
private void calcular()
{
variable1 = Double.parseDouble(bx1.getText().toString());
variable2 = Double.parseDouble(bx2.getText().toString());
variable3 = Math.sqrt(1*2/3600);
txt3.setText(Double.toString(variable3));
}
private void reset(){
bx1.setText("");
bx2.setText("");
}
}
try something like this, quick and dirty:
private void calcular() {
try {
variable1 = Double.parseDouble(bx1.getText().toString());
}
catch(NumberFormatException e) {
bx1.setText("0");
}
try {
variable2 = Double.parseDouble(bx2.getText().toString());
}
catch(NumberFormatException e) {
bx2.setText("0");
}
variable3 = Math.sqrt(1*2/3600);
txt3.setText(Double.toString(3));
}
set up Hint property at your EditText
Ex.
and check it when you getText()
use str.isEmpty() and str.length to check user's inpupt
another way :
set up inputType for the EditText to number and setup Input filter
ex.
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(4);
input.setFilters(FilterArray);

Categories

Resources