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());
}
}
}
}
});
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.
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;
}
}
I know this is easy but i m just not able to debug it.
I am dynamically creating 3 LinearLayouts and adding them to a scroll View . I am adding a Button "ins" to the top of 3 linearlayout.
The problem is that on clicking the ins Button , its on clicklistener is being called 3 times .
code:
package com.integrated.mpr;
import android.app.Activity;
import android.app.Dialog;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class Page1 extends Activity implements OnClickListener{
static int pos = new Choose().n;
static String partname;
int i;
int[][] id = new int[pos][5];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int p =0;
for(int i =0;i<3;i++){
for(int j =0;j<5;j++){
p++;
}
}
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
int resid = getResources().getIdentifier("background", "drawable", getPackageName());
ll.setBackgroundResource(resid);
Button ins = new Button(this);
ins.setText("Instructions");
ins.setOnClickListener(this);
ins.setId(5000);
ll.addView(ins);
for(i =0;i<3;i++){
LinearLayout llay = new LinearLayout(this);
llay.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setText("enter the " +(i+1)+" position name");
EditText et = new EditText(this);
et.setId(id[i][0]);
Button starta = new Button(this);
starta.setText("Record 1");
starta.setId(id[i][1]);
starta.setOnClickListener(this);
Button startb = new Button(this);
startb.setText("Record 2");
startb.setId(id[i][2]);
startb.setOnClickListener(this);
Button startc = new Button(this);
startc.setText("Record 3");
startc.setId(id[i][3]);
startc.setOnClickListener(this);
Button stop = new Button(this);
stop.setText("Submit");
stop.setId(id[i][4]);
stop.setOnClickListener(this);
TextView tv1 = new TextView(this);
tv1.setVisibility(llay.INVISIBLE);
llay.addView(tv);
llay.addView(et);
llay.addView(starta);
llay.addView(startb);
llay.addView(startc);
llay.addView(stop);
llay.addView(tv1);
ll.addView(llay);
}
Button bcon = new Button(this);
bcon.setText("Continue");
bcon.setId(10000);
bcon.setOnClickListener(this);
ll.addView(bcon);
sv.addView(ll);
this.setContentView(sv);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==5000){
Log.d("ins", "called");
Context mContext = Page1.this;
Dialog dialog = new Dialog(mContext);
dialog.setTitle("Instructions");
dialog.setContentView(R.layout.instructiondialog);
dialog.show();
}
}
}
}
I know definitely , there is some problem in the code of OnCreate but what it is ? Help please
Can anyone further explain how to set the button aligned o the right of screen , that is how to set its layout gravity?
I am not sure about what exactly you want to achieve.but you can set the flag.if flag value is 1 then only process onClick else not.
Below snippet will help you.
Yes but you will have to somehow reset that flag to 1.
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(v.getId()==5000)
{
if(flag)
{
Log.d("ins", "called");
Context mContext = Page1.this;
Dialog dialog = new Dialog(mContext);
dialog.setTitle("Instructions");
dialog.setContentView(R.layout.instructiondialog);
dialog.show();
}
flag=0;
}
}
You can also call button click event like this
Button ins = new Button(this);
ins.setText("Instructions");
ins.setOnClickListener(this);
ins.setId(5000);
ins.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Context mContext = Page1.this;
Dialog dialog = new Dialog(mContext);
dialog.setTitle("Instructions");
dialog.setContentView(R.layout.instructiondialog);
dialog.show();
}
});
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.