Android onclick Buttons Sequence - android

I have 5 buttons every one has letter (Button "H",Button "E"Button "L"Button "L"Button "O") which make the word "HELLO". what I need is to make on click sequence to these buttons so if I click "H" first and "E" second until complete the word the app will do something, But if I click "L" first will give me some error message.
Any Idea to do this sequence?
Thanks

Just have an Array like this:
int[] tracker = new int[5];
and when you click a button, say "H", set tracker[0] = 1;
but when you click a button, say "L", check whether all the previous button values are 1. If yes, then set the corresponding tracker to 1 else, show an error message, and do not make any change to the tracker Array.
Something Like this:
onHClick{
tracker[0] = 1;
}
onEClick{
for(int i=0; i<1; i++){
if(tracker[i] == 0){
//show error message and return;
}else{
tracker[1] = 1;
return;
}
}
}

You can do something like
When activity started you just make other button Enabled = false of something like that. But make the first button Enabled. Don't make the Visible=false.
Now on click of Button "H" make enable Button "E" and so on.
So user will only have to click the button in sequence. Button can not be presses in any random manner.
Try this and let me know that it works or not.

Very Interesting and exactly same to your requirement..check once..
If you give any string other than HELLO also works better.
public class ButtonTest extends Activity
{
private String result="";
String sampleText = "HELLO";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
int noOfBtns = sampleText.length();
LinearLayout ll = (LinearLayout)findViewById(R.id.btnlay);
final TextView tvtext = (TextView)findViewById(R.id.result);
final Button[] btns = new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setText(sampleText.substring(i,i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
System.out.println(j+" "+result.length());
if(j == result.length())
{
result = result+btns[j].getText().toString();
if(sampleText.startsWith(result))
{
tvtext.setText(result);
}
}
else
{
Toast.makeText(getApplicationContext(), "Wrong Button Pressed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/result"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textColor="#fff"/>
<LinearLayout
android:id="#+id/btnlay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>

Try the following
package com.example.buttonsequence;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ArrayList<Button> buttonList=null;
TextView resultTextView=null;
Button buttons[]=null;
String helloStr="HELLO";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
buttons=new Button[5];
this.resultTextView=(TextView) this.findViewById(R.id.result_text);
this.resultTextView.setText("");
buttons[0]=(Button)this.findViewById(R.id.h_button);
buttons[1]=(Button)this.findViewById(R.id.e_button);
buttons[2]=(Button)this.findViewById(R.id.l_button);
buttons[3]=(Button)this.findViewById(R.id.l2_button);
buttons[4]=(Button)this.findViewById(R.id.o_button);
for(int k=0;k<5;k++)
buttons[k].setOnClickListener(onClickListener);
Button button=(Button)this.findViewById(R.id.exit_button);
button.setOnClickListener
(
new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
);
}
OnClickListener onClickListener=new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Button b=(Button)v;
buttonList.add(b);
int size=buttonList.size();
if(size>0)
{
StringBuilder resultBuilder=new StringBuilder();
for(int i=0;i<size;i++)
{
Button tempButton=buttonList.get(i);
if(tempButton==buttons[i])
{
resultBuilder.append(helloStr.charAt(i));
if(i==4)
{
resultTextView.setText(resultBuilder.toString()+" clicked");
buttonList.clear();
}
else
{
resultTextView.setText(resultBuilder.toString()+" clicked");
}
}
else
{
buttonList.remove(i);
Toast.makeText(getApplicationContext(), "No correctly clicked", Toast.LENGTH_SHORT).show();
break;
}
}
}
else
{
resultTextView.setText("Invalid pressed");
}
}
};
}
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/h_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="H" />
<Button
android:id="#+id/e_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E" />
<Button
android:id="#+id/l_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/l2_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/o_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" />
<TextView
android:id="#+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/exit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>

I don't know exactly your flow but you can try this.
set Tag to each button as its Text, like this.
b.setTag("H");
and than after like this.
Button b;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = (String) v.getTag();
name +=s;
if( "HELLO".startsWith(name)){
<VALID>
}else{
<ERROR>
}
}
});
}
check the variable name on each button click with your original word i.e. HELLO like above.

Related

show EditText on condition

Right now I have an idea for a project and I would like to know if anyone can help me on the same logic.
As such I need to create or generate a number of EditText according to amount you enter, ie, to select or enter a number such as 5, show me 5 EditText layout for type 5 values​​. They know that the form could accomplish this? Any ideas please?
I guess it must be a way to do it with a loop, but not like carrying this calculation Java to XML. Thank you.
Here is an example of generating EditText items based on the number you enter. You can ignore the scrollview in the layout file I just put it in case someone added a lot of EditText items that would go off the screen.
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
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 TextView output = (TextView) findViewById(R.id.output);
final Button generate = (Button) findViewById(R.id.generate);
final Button values = (Button) findViewById(R.id.values);
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);
}
}
}
});
values.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] editTextValues = new String[container.getChildCount()];
StringBuilder editTextValuesBuilder = new StringBuilder();
for (int counter = 0; counter < container.getChildCount(); counter++) {
EditText child = (EditText) container.getChildAt(counter);
editTextValues[counter] = child.getText().toString().trim();
editTextValuesBuilder.append(editTextValues[counter]).append("\n");
}
output.setText(editTextValuesBuilder.toString());
}
});
}
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);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp"
tools:context="${packageName}.${activityClass}" >
<EditText
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="#+id/generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
<Button
android:id="#+id/values"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Values" />
<TextView
android:id="#+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>

How to keep state of RadioButton in Android?

Hi I'm trying to develop an application which runs for every interval time, lets say for every 1 minute it will display some Toast message.
But problem is I'm using RadioButton functionality is perfect but when I tap on one radio button it will be green, but when I close and re-open the activity I'll get as none of the radio buttons selected.
Here is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
//some code
}
break;
}
}
}
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/radio">
<RadioButton android:id="#+id/radio_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_one_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ten_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10 minute"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Please help me to solve this riddle.
Thanks in advance...
This code is useful for store the ratingbar state, when we start new activity, you will see the previous rating state..
package com.example.ratingbar;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class RatingbarMainActivity extends Activity {
RatingBar ratingbarClick;
Button sub_btn;
TextView textRatingView , textRatingViewSave;
Boolean val = true;
float ans = (float) 0.0;
//--------------------------------------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ratingbar_main);
ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
ratingbarClick.setOnRatingBarChangeListener(rateObj);
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
ans = sharePref.getFloat("Get_Rating", 0.0f);
System.out.println("--------------------------------------ans = " + ans);
if(val) {
ratingbarClick.setRating(ans);
}
else {
ratingbarClick.setRating(ans);
}
textRatingView = (TextView) findViewById(R.id.ratingView);
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
//textRatingView.setText(String.valueOf(rating));
ans = ratingbarClick.getRating();
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
SharedPreferences.Editor edit = sharePref.edit();
edit.putFloat("Get_Rating", ans);
edit.commit();
val = false;
}
};
//--------------------------------------------------------------------------------------------
}
---------------------------------------------------------------------------------------------------
activity_ratingbar_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ratingBar1"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="23dp"
android:text="Select Your Rating Bar Here"
tools:context=".RatingbarMainActivity" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="63dp" />
<TextView
android:id="#+id/ratingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ratingBar1"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Click To Save Rating In TextBox" />
</RelativeLayout>
it is the simplest way to do so,no need of sharedpreference at all.you will get confused while using it.keep the things simple like this
public class MainActivity extends Activity {
Public static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(flag==1)
radio_one_min.setChecked(true);
else if(flag==2)
radio_ten_min.setCheckek(true);
else if(flag==3)
radio_disable.setCheckek(true);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
flag =1;
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
flag=2 ;
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
flag=3;
//some code
}
break;
}
}
}
[EDITED]
I found developer.android.com/training/basics/activity-lifecycle/recreating.html document first, so my first guess was using Bundles and on Save/Resume Instace State methods. However this does not seem to work well. Here's my final attempt at a working solution (using SharedPreferences class, as suggested by some users):
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class MainActivity extends Activity {
final String PREFERENCES = "prefs";
final String RADIO_BUTTON = "prefsval";
SharedPreferences sp;
Editor e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
e = sp.edit();
}
#Override
protected void onResume() {
super.onResume();
if (sp != null) {
if (sp.getInt(RADIO_BUTTON, 0) != 0) {
RadioButton rb;
rb = (RadioButton) findViewById(sp.getInt(RADIO_BUTTON, 0));
rb.setChecked(true);
}
}
}
public void onRadioButtonClicked(View view) {
e.putInt(RADIO_BUTTON, view.getId());
e.apply();
}
}

Android Quote app, next and back buttons

Im trying to make a simple quote app, but every time I hit my back button after my next button it will go to the next array and not backwards. Im using an int num to keep track of with quote the user is on.
here is my back button
package me.me.quote;
public class Startme extends Activity {
Random gen= new Random();
int num;
String[] quotes = new String[15];
public void next(View N){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
if(num == 5){
num =0;}
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num++]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
public void back(View B){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num--]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);}
public void rand(View G) {
num = gen.nextInt(5);
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.startquotes);
TextView Dark=(TextView)findViewById(R.id.Quote);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/font1.ttf");
Dark.setTypeface(face);
}
}
//LAYOUT FILE text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:text="VISIBLE EVERY TIME"
android:visibility="visible" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="NEXT" >
</Button>
<Button
android:id="#+id/next"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="BACK" >
</Button>
</RelativeLayout>
///ACTIVITY CLASS
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
Button next;
Button back ;
TextView quoteText;
int currentSelectedQuote=0;
String[] quote={"QUOTE1","QUOTE2","QUOTE3","QUOTE4","QUOTE5",};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
quoteText=(TextView)findViewById(R.id.textView);
quoteText.setText(quote[currentSelectedQuote]);
next=(Button)findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentSelectedQuote++;
if(currentSelectedQuote == 5){
currentSelectedQuote =0;}
quoteText.setText(quote[currentSelectedQuote]);
}
});
back=(Button)findViewById(R.id.back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(currentSelectedQuote==0)
{
currentSelectedQuote=4;
}
else
{
currentSelectedQuote--;
}
quoteText.setText(quote[currentSelectedQuote]);
// TODO Auto-generated method stub
}
});
}
}

Delete button in TableRow

I have an Edit button in my header. And I populating my TableLayout in a loop. In The loop I am inflating a Delete button.
Following is the code I have used :
MainActivity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cookbooklist);
btnHeaderEdit = (Button)findViewById(R.id.btnEdit);
btnHeaderEdit.setVisibility(View.VISIBLE);
delete_button = (View)findViewById(R.id.btnDelete);
listTable = (TableLayout)findViewById(R.id.cookbookListTable);
btnHeaderEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
delete_button.getTag();
delete_button.setVisibility(View.VISIBLE);
}
});
for(int i=0;i<=10;i++)
{
// Row to display news title
final TableRow newsRow = new TableRow(this);
newsRow.setMinimumHeight(200);
newsRow.setClickable(true);
newsRow.setTag(i);
newsRow.setBackgroundColor(Color.WHITE);
// Some other views
//create inflater
LayoutInflater inflater = getLayoutInflater();
delete_button = inflater.inflate(R.layout.deletebutton,
(ViewGroup) newsRow, false);
delete_button.setTag(i);
delete_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
listTable.removeView(newsRow);
}
});
//Add views in table
newsRow.addView(delete_button);
listTable.addView(newsRow);
}
}
delebutton.xml :
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btnDelete"
android:layout_width="100dip"
android:visibility="invisible"
android:layout_height="40dip"
android:padding="10sp"
android:text="Delete">
</Button>
Question :
The problem I am facing is that when I click the Edit button in header, Delete button appears only in the last row. When I setVisibility of Delete button to Visible in layout, it appears in all rows. But I want it to be invisible in the start. And on clicking the Edit button it should appear in all rows. I Am wondering how to achieve that.
Can someone assist me? Let me know if more code is needed.
Thanks
The problem I am facing is that when
Hi Stone i think you have to use a boolean flag. which wil determine whether the delete button should be visible or not. Try with the following example. Its working fine. On click of edit button if delete buttons are invisible i make all as visible and viceversa. Try the following code.
See My Working Example
Sample2.java
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Sample2 extends Activity {
boolean showDeleteButtonFlag = false;
Button delteBtn2 = null;
Button delteBtn1 = null;
Button editBtn = null;
ArrayList<Button> deleteButtonList = new ArrayList<Button>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tablerow);
delteBtn1 = (Button) findViewById(R.id.delete1);
delteBtn2 = (Button) findViewById(R.id.delete2);
// add all delete buttons buttons to the array list
deleteButtonList.add(delteBtn1);
deleteButtonList.add(delteBtn2);
editBtn = (Button) findViewById(R.id.edit);
setVisibilityOfDeleteButtons();
editBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// if delete button is visible make it as invisible and viceversa
showDeleteButtonFlag = !showDeleteButtonFlag;
setVisibilityOfDeleteButtons();
}
});
}
void setVisibilityOfDeleteButtons(){
if(showDeleteButtonFlag){
Iterator<Button> itr =deleteButtonList.iterator();
while(itr.hasNext()){
itr.next().setVisibility(View.VISIBLE);
}
}else{
Iterator<Button> itr =deleteButtonList.iterator();
while(itr.hasNext()){
itr.next().setVisibility(View.INVISIBLE);
}
}
}
}
tablerow.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow>
<Button
android:id="#+id/edit"
android:layout_width="100dip"
android:layout_height="60dip"
android:text="Edit" />
<Button
android:id="#+id/delete1"
android:layout_width="100dip"
android:layout_height="60dip"
android:text="Delete" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:textColor="#ffffff"
android:textStyle="bold" />
<Button
android:id="#+id/delete2"
android:layout_width="100dip"
android:layout_height="60dip"
android:text="Delete" />
</TableRow>
</TableLayout>

Android : EditText.getText() returns "" (Empty) String on Android 1.6

I am trying to fetch the EditText value on click of a button.
String ETValue = ((EditText)findViewById(R.id.ETID)).getText().toString().trim();
Every things works fine on other android versions, but on 1.6 I am getting ""(Empty) String.
Whats going wrong on Android 1.6, how this is happening?
Thanks
Screen Shots:
Code Reference :
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_marginTop="10dip"
android:layout_marginLeft="5dip"
android:text="Type you text here"
android:id="#+id/TextView02"
android:layout_height="wrap_content"
android:textColor="#333333"
android:layout_width="fill_parent"
android:textSize="16dip">
</TextView>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/ID1">
<EditText android:layout_marginLeft="5dip"
android:id="#+id/keyword"
android:hint="e.g. Text here"
android:textSize="17dip"
android:singleLine="true"
android:layout_height="wrap_content"
android:layout_width="250dip"/>
<Button android:id="#+id/btnID"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:background="#drawable/icon"
android:gravity="bottom"
android:paddingBottom="9dip"
android:layout_marginLeft="3dip"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/ID2"
android:visibility="gone">
<EditText android:layout_marginLeft="5dip"
android:id="#+id/keyword"
android:hint="e.g. Text here"
android:textSize="17dip"
android:singleLine="true"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginRight="5dip" />
</LinearLayout>
<Button android:text="Click" android:id="#+id/Button01" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
Etext.Java
public class EText extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((LinearLayout)findViewById(R.id.ID1)).setVisibility(View.GONE);
((LinearLayout)findViewById(R.id.ID2)).setVisibility(View.VISIBLE);
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String ETValue = ((EditText) findViewById(R.id.keyword)).getText().toString().trim();
Toast.makeText(EText.this, ETValue, Toast.LENGTH_SHORT).show();
}
});
} }
Even this way doesn't works
public class EText extends Activity {
/** Called when the activity is first created. */
EditText ETextt1 = null;
EditText ETextt2 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(Integer.parseInt(Build.VERSION.SDK) < 7){
((LinearLayout)findViewById(R.id.ID1)).setVisibility(View.GONE);
((LinearLayout)findViewById(R.id.ID2)).setVisibility(View.VISIBLE);
ETextt1 = ((EditText) findViewById(R.id.keyword1));
}else{
ETextt2 = ((EditText) findViewById(R.id.keyword2));
}
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String ETValue = null;
if(null == ETextt1){
ETValue = ETextt2.getText().toString().trim();
}else if(null == ETextt2){
ETValue = ETextt1.getText().toString().trim();
}
Toast.makeText(EText.this, ETValue, Toast.LENGTH_SHORT).show();
}
});
} }
This Works Perfectly Fine :-)
package com.test.et;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class EText extends Activity {
/** Called when the activity is first created. */
EditText ETextt1 = null;
EditText ETextt2 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(Integer.parseInt(Build.VERSION.SDK) < 7){
((LinearLayout)findViewById(R.id.ID1)).setVisibility(View.GONE);
((LinearLayout)findViewById(R.id.ID2)).setVisibility(View.VISIBLE);
}
//ETextt = ((EditText) findViewById(R.id.keyword1));
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String ETValue = null;
if(Integer.parseInt(Build.VERSION.SDK) < 7){
ETValue = ((EditText) findViewById(R.id.keyword2)).getText().toString().trim();
}else{
ETValue = ((EditText) findViewById(R.id.keyword1)).getText().toString().trim();
}
Toast.makeText(EText.this, ETValue, Toast.LENGTH_SHORT).show();
}
});
} }
I have found the problems source. You declareted two EditTexts with the same id. To resolve problem just rename your EditText as keyword1 and keyword2. Then, get text from second EditText.
public class EdText extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((LinearLayout)findViewById(R.id.ID1)).setVisibility(View.GONE);
((LinearLayout)findViewById(R.id.ID2)).setVisibility(View.VISIBLE);
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String ETValue = ((EditText) findViewById(R.id.keyword2)).getText().toString().trim();
Toast.makeText(EdText.this, ETValue, Toast.LENGTH_SHORT).show();
}
});
} }
layout:
`
<TextView
android:layout_marginTop="10dip"
android:layout_marginLeft="5dip"
android:text="Type you text here"
android:id="#+id/TextView02"
android:layout_height="wrap_content"
android:textColor="#333333"
android:layout_width="fill_parent"
android:textSize="16dip">
</TextView>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/ID1">
<EditText android:layout_marginLeft="5dip"
android:id="#+id/keyword1"
android:hint="e.g. Text here"
android:textSize="17dip"
android:singleLine="true"
android:layout_height="wrap_content"
android:layout_width="250dip"/>
<Button android:id="#+id/btnID"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:background="#drawable/icon"
android:gravity="bottom"
android:paddingBottom="9dip"
android:layout_marginLeft="3dip"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/ID2"
android:visibility="gone">
<EditText android:layout_marginLeft="5dip"
android:id="#+id/keyword2"
android:hint="e.g. Text here"
android:textSize="17dip"
android:singleLine="true"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginRight="5dip" />
</LinearLayout>
`
I have just finished struggling with EditText returning an empty string ("").
The reason was that setContentView(R.layout.main); was invoked twice:
private EditText editText1;
private EditText editText2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); /// !!!
editText1=(EditText)findViewById(R.id.editText1);
editText2=(EditText)findViewById(R.id.editText2);
// some really long and untrivial initialization stuff
setContentView(R.layout.main); /// !!!
}
It looks like editText1 and editText2 pointed into the parts of the previous incarnation of R.layout.main...
Here is my test example for your case:
public class EdText extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// string initialised here will always have initial value and never changes
final String ETValue = ((EditText) findViewById(R.id.EditText01)).getText().toString().trim();
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(EdText.this, ((EditText) findViewById(R.id.EditText01)).getText().toString().trim(), Toast.LENGTH_SHORT).show();
}
});
} }
Everything works fine for API 4. Maybe your probles connected with the moment when you read the string value. see my comment.
public class EditTextDemo extends Activity {
/** Called when the activity is first created. */
Button btnClick;
String ETValue;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ETValue = ((EditText)findViewById(R.id.editText1)).getText().toString().trim();
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
//assign a default value
ETValue.equals("Welcome!!");
Toast.makeText(getBaseContext(), "Value is:"+ETValue, Toast.LENGTH_SHORT).show();
Log.i("EditTextDemo","-----Value of EditText is:----------"+ETValue);
}
});
}}
You can also give value at runtime.. Also that value can be used for further coding.
Hope this will help!!

Categories

Resources