One button for 2 different actions - java

I have "send" Button inside dialogFragment that onClick event push new data to firebase under key value.
I want this button to be also like an "update" button when the user click on particular button. the data will update in firebase under the same key value as before.
This is the send button onClick method:
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//some code .....//
DatabaseReference newPost = mDatabase.push();
str_key = newPost.getKey();
trempData = new TrempData(str_key, str_uid, str_name, str_phone, str_from, str_to, str_date, str_time, str_extra, str_timestamp);
newPost.setValue(trempData);
Toast.makeText(getActivity(), "Tremp Added", Toast.LENGTH_SHORT).show();
dismiss();
}
});
Any suggestions?

More important than the implementation is the way you think it can be done. So, the basic approach in these cases is to use a boolean variable.
Why? Because it can be used to indicate if the button is in a particular state or not.
So, you can do something like this.
boolean b=false;
//set your button in the initial state you want(submit in your case)
//In onClick() method
if(!b){ //button in submit state
b=true;
//do submit stuff
send_btn.setText("update");
}
else{ //button in update state
b=false;
//do update stuff
send_btn.setText("submit");
}
In this case, true value of b indicates that the button is in "update" state.

This is an Example :
private final int BUTTON_UPDATE = 1;
private final int BUTTON_SEND = 2;
private int buttonStatus = 0;
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(buttonStatus)
{
case BUTTON_UPDATE: { // your update code here}
case BUTTON_SEND : { // your send code here
}
the buttonStatus will control what operation the button will do.

Put a boolean in sharedPrefrences and keep to false initially when
user sends data to firebase update boolean to true.
in onClick check if the value is true or false using if else and
execute code accordingly

You can use the tag of the view for this and update the state as your need
Button button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (button.getTag().equals("send")) {
// push the value to firebase
// set the tag to update and the text
button.setTag("update");
button.setText("update");
}else if (button.getTag().equals("update")){
// update the value in firebase
}
}
});
xml
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="send"
android:text="send" />

Related

How can I persist the string/int value in EditText when i relaunch my application?

In my Android activity, I have one EditText, a '+' button, a '-' button, 'Save' button and 'Load' button. When I press '+', the value in EditText increases by 1, similarly on pressing '-' value decreases by 1. I used SharedPreferences to save the data when I click on 'Save'. When I click 'Load', I want to reload this data onto the EditText field.
Now the problem is, when I completely exit the application (even from recently used apps), and click 'Load' on relaunching it, the saved number doesn't appear. I included the onClick() action for the 'Load' method in onRestart() method. It still doesn't work. What am I missing here? I even tried out all other suggestions for the similar questions asked previously here.
Also, is it really onRestart() or onRestoreInstanceState() ?
public class MainActivity extends Activity {
Button btn1;
Button btn2;
Button btn3;
Button btn4;
EditText scoreText;
int counter = 0;
TextView textTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.add);
btn2 = (Button)findViewById(R.id.subtract);
btn3 = (Button)findViewById(R.id.save);
btn4 = (Button)findViewById(R.id.load);
scoreText = (EditText)findViewById(R.id.total);
textTitle = (TextView)findViewById(R.id.title);
btn1.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter=counter-1;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
//store data using sharedprefernces
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
//Edit method allow to write the data in sharedpreferences
editor.putString("count",scoreText.getText().toString());
//For commit changes commit() method is used
editor.commit();
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
}
});
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
// scoreText.setText(strcount);
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
#Override
protected void onRestart(Bundle savedInstanceState){
super.onRestart(savedInstanceState);
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
if (strcount.equals(""))
{
Toast.makeText(getApplicationContext(), "Data Was Not Found", Toast.LENGTH_SHORT).show();
}
else
{
scoreText.setText(strcount);
}
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
You using using count as key to save the value
editor.putString("count",scoreText.getText().toString());
but using name as key to retrieve the value so you need to use count key while getting the previously stored data so use
sharedPreferences.getString("count",scoreText.getText().toString());
instead of
sharedPreferences.getString("name",scoreText.getText().toString());
You are using different keys to save and retrieve the data from SharedPrefernces.
editor.putString("count",scoreText.getText().toString());
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
You should be using the same key in both the cases otherwise it would return default value which is the text in TextView and that would be empty at the start of the app, you just need to change the key and that would do the trick for you.
Just change the below line like it is mentioned
String strcount=sharedPreferences.getString("count",scoreText.getText().toString());

How to take inputs in multiple textviews?

i am new to development. i am creating an android calculator app with advanced functionality.The thing is i am using text view for taking and displaying inputs/outputs. My question is, how can i take Multiple inputs in multiple Textviews.
For example i have 3 text views,when user will enter 1st input in first textview(by default) and when user press the specific button it moves automatically to next textview . In some cases i want to take 2 inputs and in some cases i want to take 3 ,
How can i achieve this
Note: I dont want to use edit text , coz all buttons of already available in my app.Using Edit text will make softkeyboard to appear, and then for hiding the softkeyboard, i need to use hiding code lines in every class
You can do something like following:
private TextView[] textViews;
private TextView tvCurrentEditing;
private Button btnNext;
private Button btnPrev;
private Button btnSetText;
private int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
textViews = new TextView[3];
//Initialize all your textviews like textViews[0] = findViewById(<textview-id1>);
//textViews[1] = findViewById(<textview-id2>);
//textViews[2] = findViewById(<textview-id3>);
tvCurrentEditing = textViews[index];// I am assuming this is your first
//initialzie btnSettext
btnSettext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvCurrentEditing.setText("<what ever you want");
}
});
//initialize next buton
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index < textViews.length) {
index++;
}
tvCurrentEditing = textViews[index];
}
});
//Initialize previous button
btnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index > 0) {
index--;
}
tvCurrentEditing = textViews[index];
}
});
}
The names of the views could be different. The point is always use tvCurrentEditing whenever you want to change data of TextView. And update tvCurrentEditing whenever needed.

how to check whether Button is clicked or not

I have to check whether the button is clicked or not.if clicked application has to do one task and if not, application has to do another task. I tried to do this, but I am getting no connection error which I have put at the end of the code in catch block.
protected void onCreate(Bundle savedInstanceState) {
PracticeVO practiceObj;
try {
setTitle("Klarity");
setPrefBtn = (Button) findViewById(R.id.setPrefBtn);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klarity_home);
/*
* asynchronous calls
*/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
final ConnectionHelper con = new ConnectionHelper();
/*
* It will connect to DB and fetches the Practice Information
*/
if (Btnclicked == false) {
String allPracticesStr = null;
here I have set the boolean variable 'Btnclicked' true.
setPrefBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Btnclicked=true;
Intent setPrefIntent = new Intent(KlarityHome.this,
SetPreferences.class);
startActivity(setPrefIntent);
}
});
But After executing this The cursor is directly goin here and displaying 'no connection'.
catch (Exception ex) {
Context context = getApplicationContext();
CharSequence text = "There is some error in application";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
System.out.println("no connection");
}
}
Anyone has solution on this.
as you said
"the button is clicked or not.if clicked application has to do one task and if noapplication has to do another task"
so, if i were you, i'll put 2 radio buttons, every one with the text of the task you want to do, and add a listener for them, like this:
radiobutton1.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
radiobutton2.setChecked(false);
}
});
radiobutton2.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
radiobutton1.setChecked(false);
}
});
and last, in the button do the task you want to do:
Button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
if(radiobutton1.isChecked){
//do task 1
}else{
//do task2}
}
});
You are getting an NPE(NullPointerException) since you havent initialised Btnclicked in your code at the time of usage.ie you are checking whether Btnclicked is false like
if (Btnclicked == false) {
But at the time of this checking, the value of Btnclicked is null and hence an NPE.
So to get rid of this, you just add either
Btnclicked=true;
or
Btnclicked=false;
before the if loop according to your logic.
OR
or just replace the declaration from Boolean Btnclicked; to Boolean Btnclicked=false;
Hope this helps.
Remove Btnclicked you don't need that. OnClickListner is meant for what you're trying to do. The code which you want to run when button is not pressed put it before
//When button is not pressed
setPrefBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//When button is pressed
}
});
And the code which you want to run when the button is clicked place it inside the onClick(){}

How to return user input values (double) from EditText- Android

I'm new to OOP, but I've had experience with C previously. I'm learning Java and working on building an app slowly. I find I learn more when I apply what I've read and learned from other sources to projects.
The problem I've been facing for a while now is in regard to returning values users have inputted into EditText fields and using those values to run some calculations. Here is my code:
public class Linmotion extends Activity {
// Creating the variables
EditText time, acc, dis, ivel, fvel;
Button solve;
int count = 0;
double time1,acc1,dis1,ivel1,fvel1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linmotion1);
time = (EditText) findViewById(R.id.EditText01);
acc = (EditText) findViewById(R.id.EditText02);
dis = (EditText) findViewById(R.id.EditText03);
ivel = (EditText) findViewById(R.id.EditText04);
fvel = (EditText) findViewById(R.id.EditText05);
solve = (Button) findViewById(R.id.buttonSolve);
//Trying to return inputted values
/*
if (!(time.getText() == null)) {
time1=Double.parseDouble(time.getText().toString());
}
if(!(acc.getText()==null)){
acc1=Double.parseDouble(acc.getText().toString());
}
if(!(ivel.getText()==null)){
ivel1=Double.parseDouble(ivel.getText().toString());
}
if(!(fvel.getText()==null)){
fvel1=Double.parseDouble(fvel.getText().toString());
}s
if(!(dis.getText()==null)){
dis1=Double.parseDouble(dis.getText().toString());
}
/*
* Double.parseDouble(time.getText().toString());
* Double.parseDouble(acc.getText().toString());
* Double.parseDouble(ivel.getText().toString());
* Double.parseDouble(fvel.getText().toString());
* Double.parseDouble(dis.getText().toString());
*/
// add button listener
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (time1 < 0) {
count++;
if (acc1 < 0) {
count++;
}
if (ivel1 < 0) {
count++;
}
if (fvel1 < 0) {
count++;
}
if (dis1 < 0) {
count++;
}
if (count > 2) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Linmotion.this);
final AlertDialog alert = alertDialog.create();
alert.show();
alertDialog.setTitle("Error");
alertDialog
.setMessage("Please input values into at least 3 fields");
alertDialog.setPositiveButton("OK",new DialogInterface.OnClickListener() {
// function of dialog button
public void onClick(DialogInterface dialog,
int id) {
alert.cancel();
}
});
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.linmotion, menu);
getActionBar().setDisplayShowTitleEnabled(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The if statements and the other Double.parseDouble lines have been commented out because every time I try to debug the code the app crashes the instant Linmotion is created. I suspect its from the fact that onCreate runs the Double.parseDouble code and the values in the field are null. I tried to fix this with the if statements and it still crashes. I'm not sure where to go from here.
Again, if I wasn't clear I just want the values inputted into the EditText to return a double and then use that double in the Java code to run some equations and an alert dialog if not enough fields have been filled in.
EDIT/UPDATE:
I finally figured out what was wrong with my code. I took in advice from everyone and revised accordingly, so here it is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linmotion1);
time = (EditText) findViewById(R.id.eTexttime);
acc = (EditText) findViewById(R.id.eTextacc);
dis = (EditText) findViewById(R.id.eTextdis);
ivel = (EditText) findViewById(R.id.eTextivel);
fvel = (EditText) findViewById(R.id.eTextfvel);
solve = (Button) findViewById(R.id.buttonSolve);
solve.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
count=0;
if (time.getText().toString().equals("")){
count++;
}
if(dis.getText().toString().equals("")){
count++;
}
if(fvel.getText().toString().equals("")){
count++;
}
if(ivel.getText().toString().equals("")){
count++;
}
if(acc.getText().toString().equals("")){
count++;
}
if (count>2){
// TODO Auto-generated method stub
final AlertDialog alert= new AlertDialog.Builder(Linmotion.this).create();
alert.setTitle("Oops");
alert.setMessage("Please input values in at least 3 fields.");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.cancel();
}
});
alert.show();
count=0;
}
if(!(time.getText().toString().equals(""))){
time1=Double.parseDouble(time.getText().toString());
}
if(!(acc.getText().toString().equals(""))){
acc1=Double.parseDouble(acc.getText().toString());
}
if(!(dis.getText().toString().equals(""))){
dis1=Double.parseDouble(dis.getText().toString());
}
if(!(ivel.getText().toString().equals(""))){
ivel1=Double.parseDouble(ivel.getText().toString());
}
if(!(fvel.getText().toString().equals(""))){
fvel1=Double.parseDouble(fvel.getText().toString());
}
} });
}
In regard to the issues I had with the alertdialog I realized that my count integer would continue to increase every time the solve button was clicked. To fix this I simply equaled the integer to 0 at the beginning of the onclicklistener and at the end of the if statement regarding the dialog. Thanks everyone.
It looks to me like you're doing it right. I think the problem might be that it's in your OnCreate method.
Try making the Button Solve's OnClick method run your commented code before doing the logic!
You can get the value from an EditText using getText()..
See this link for more details
According to the docs getText() returns an Editable.
so,
time = (EditText) findViewById(R.id.EditText01);
String value = time.getText().toString();
Now, as i've said earlier, since getText() returns an Editable you need to convert it into String before you use it..
So, change
if (!(time.getText() == null)) {
to
if (!(time.getText().toString() == null)) {
Also, if you want to check if the EditText is empty or not, try like this..
if (!(time.getText().toString() .equals(""))) {
Try this answer..
Your code isn't working because you are trying to read these text fields on creation. This is not what you want to do.
You are trying to access the EditTexts before the page finishes loading. Instead, you need to do this in an event handler, like you have for the buttons. Read the values in an event handler, not in onCreate.
The simplest option would be to add an "update" button and do all those operations in the onClick handler for that button.
Most likely your EditText fields initially contain text, that cannot be parsed with Double.parseDouble (Something like the empty string). A NumberFormatException is thrown is this case. If you want to get the values at the time solve button is clicked, you have to get the text inside OnClickListener.onClick (otherwise you use the initial strings, i.e. the strings in the android:text attributes in the activity_linmotion1 layout). To handle invalid input, you can simply catch the NumberFormatException:
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
double time1 = Double.parseDouble(time.getText().toString());
double acc1 = Double.parseDouble(acc.getText().toString());
double ivel1 = Double.parseDouble(ivel.getText().toString());
double fvel1 = Double.parseDouble(fvel.getText().toString());
double dis1 = Double.parseDouble(dis.getText().toString());
// ... rest of your original listener code
} catch (NumberFormatException ex) {
// show error in dialog or something
}
}
});
Oncreate is the first method called when an activity is created, so by the time the onCreate is called, the editText is having an empty string which you are giving as an input to parseDouble which will give NumberFormatException.
You can avoid this crash by putting a button and handling the button onClick event. Inside this button click you collect the values from editfield. You can handle on click by defining listeners in the following way
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="yourHandlerName" />
Now define your onClick with getText to get text from editfield in the following way
public void yourHandlerName(View v) {
switch(v.getid()) {
case R.id.mybutton: Double.parseDouble(editField.getText().to string());
}
You have to register a Listener. Because onCreate() is called when the Actvity first start. This means that you can't get the text from your EditTexts because the Actvity is creating. But you can use your OnClickListener or other Listeners. You can easily write your commented lines to the OnClickListener. At the time you are clicking the button the method getText().toString() return the values. If you want to do it without clicking on a button use addTextOnChangedListener() on yout EditText.

Do you need to inflate a view in order to get its id for the onClick method?

Do you need to inflate a view in order to get its id for the onClick method? Because when I run my program in the emulator and click on the specific button it does nothing! I want it to go back to the main.xml layout! Do I need to procces the onClick some other way?
public void onClick(View v) {
switch( v.getId()){
case R.id.play:
setContentView(R.layout.play);
setQuestion();
break;
case R.id.level:
setContentView(R.layout.level);
if(lvl.equals("1")) {
lvl1.setChecked(true);
}
if(lvl.equals("2")) {
lvl2.setChecked(true);
}
if(lvl.equals("3")) {
lvl3.setChecked(true);
}
if(lvl.equals("4")) {
lvl4.setChecked(true);
}
if(lvl.equals("5")) {
lvl5.setChecked(true);
}
break;
case R.id.setLevel:
if(lvl1.isChecked()) {
setLevel("1");
}
if(lvl2.isChecked()) {
setLevel("2");
}
if(lvl3.isChecked()) {
setLevel("3");
}
if(lvl4.isChecked()) {
setLevel("4");
}
if(lvl5.isChecked()) {
setLevel("5");
}
setContentView(R.layout.main);
break;
}
}
Here is how I get the views:
setContentView(R.layout.main);
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(this);
Button level = (Button)findViewById(R.id.level);
level.setOnClickListener(this);
Button setLevel = (Button)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
lvl1 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl1);
lvl2 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl2);
lvl3 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl3);
lvl4 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl4);
lvl5 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl5);
What should I do so that when I click the setLevel button it changes the view back to the main.xml view
Andrew,
You may want to make individual onClick() methods for each item. That's how I handle my click-able objects.
Example:
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//perform play button actions here
}
});
This way you already have the button object created based on its ID value, and the onClickListener is specifically tailored to that item.
good luck!

Categories