how to check whether Button is clicked or not - java

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(){}

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());

Not Allowing Multiple Button Presses

I'm building a camera app with Camera2 API, relatively new to Android development. Everything is working just working out the bugs. But I have a switch camera button, going from the front camera to the back or vise-versa. If the user continuosly presses the button, the app will crash. Trying to set it up in a way that it finishes everything it needs to do before the button can be used again.
I have the button set to enabled, but after press, it disables the button until everyting finishes, then renables, but that doesn't seem to work:
//The button to switch the camera to front and back camera.
mChangeCamera = (ImageButton) findViewById(R.id.change_camera);
mChangeCamera.setEnabled(true);
mChangeCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mChangeCamera.setEnabled(false);
closeCamera();
// stopBackgroundthread();
if (mTextureView.isAvailable()) {
setUpCamera(mTextureView.getWidth(), mTextureView.getHeight());
transformImage(mTextureView.getWidth(), mTextureView.getHeight());
connectCamera();
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
mChangeCamera.setEnabled(true);
}
});
there has to be a simple way to do this, but not finding anyting from searchs. Anyone know how I can set it up not to crash when the user smashes the button?
Alight, so I ended up figuring out how to do this. You can use a handler with a post delay like so:
mChangeCamera = (ImageButton) findViewById(R.id.change_camera);
mChangeCamera.setEnabled(true);
mChangeCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mChangeCamera.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mChangeCamera.setEnabled(true);
}
},1000);
closeCamera();
// stopBackgroundthread();
if (mTextureView.isAvailable()) {
setUpCamera(mTextureView.getWidth(), mTextureView.getHeight());
transformImage(mTextureView.getWidth(), mTextureView.getHeight());
connectCamera();
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
}
});
i did this by calculate time between multiple button presses...
create global variable in your class first
private long mLastClickTime = 0;
and a final int for duration between clicks
public static final int CLICK_TIME = 400;
then paste this code in on click of button
if (SystemClock.elapsedRealtime() - mLastClickTime < CLICK_TIME) {
return; //button pressed repeatedly so do nothing
}
mLastClickTime = SystemClock.elapsedRealtime();
// button is not pressed repeatedly so add your desired action
and of course you can increase the CLICK_TIME value if error still occurs

Continuous Message as long as EditText is being used

We're trying to implement a "The User is typing" message as long as a user keeps typing within a specific EditText. For example, once the user starts typing within the EditText, and as long as 2 seconds didn't pass since the last typing event, keep showing the "User is typing" message.
Any idea how to achieve that easily without blocking any threads?
Thanks!
Yohay
you can handle it by using focusChangeListener
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
//user typing
} else {
//user stop typing
}
}
});
Once user start typing , start a background thread(BT) and pass text of your edit text via Message to your BT. After every 2 seconds ping (post a message) to your Main Thread from BT. On receiving the message in MainThread pass a message containing text in your edit text to your BT. On receiving message in BT simply compare text just received to previous text passed in BT. If both the texts are same, user is not typing.
But user can start typing again any moment, so keep on playing this game in background until message is alive(neither sent nor discarded). Once message life is over kill your BT.
Edit example code
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private boolean killThread = false;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
Log.d(TAG, "onFocusChange: gained focus");
startThread(new WeakReference<MainActivity>(MainActivity.this));
}
}
});
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// for simplicity killing thread here
killThread = true;
}
});
}
private void startThread(final WeakReference<MainActivity> activityWeakReference) {
new Thread(new Runnable() {
String savedText = "";
#Override
public void run() {
do {
MainActivity activity = activityWeakReference.get();
if (null == activity) {
// Activity destroyed, killME!!!
killThread = true;
Log.e(TAG, "run: activity reference null, killing MYSELF😔😔");
} else {
if (savedText.equals(activity.editText.getText().toString())) {
Log.e(TAG, "run: user is not typing");
} else {
savedText = activity.editText.getText().toString();
Log.e(TAG, "run: user typing ");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} while (!killThread);
}
}).start();
}
}
When EditText gains focus , I am starting a Thread (passing WeakReference to Activity also) and then using WeakReference getting hold of EditText and checking its Text. For Simplicity, I am simply killing Thread on Button Click.

One button for 2 different actions

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" />

What happens after onClick is finished. Android

In my app after they press an on screen button. In the listener I do some check to see if they win. When they win i set a boolean like so:
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
aWin = true;
}
}
I am wondering. Where does the code go after the onClick. Am i suppose to call the function in the onClick?
I have looked everywhere for an answer, I am very new to android programming.
If by "the function" you mean a funcion that you have developed, then Yes, you should call whatever function you want to execute in the onClick method.
For example:
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
aWin = true;
//Example
this.informUser(aWin) //Call your function here
}
}
If by "the funcion" you mean the onClick, then no, you shouldn't call it, Android OS should do it for you.
Where does the code go after the onClick. Am i suppose to call the
function in the onClick?
It depends on what you do in the onClick.
For example :
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
aWin = true;
}
}
In your code above, the code will stop at aWin = true;.
Now lets say you want to go to another Activity after a click happened :
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
Intent i = new Intent(this, AnotherActivity.class);
startActivity(i);
}
}
The onClick will end when your apps go to another activity.
UPDATE
Lets say you want to "refresh" your TextView after a click happened :
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
aWin = true;
if(aWin)
myText.setText("WIN");
else
myText.setText("LOSE");
}
}
Feel free to comment if you still have some questions (although no guarantee i can answer it) :)

Categories