How to declare boolean inside button click? - java

I want to set something like this on button click:
boolean isLightOn = false;
if(!isLightOn)
{
FlashTask.flash.on();
isLightOn=true;
return;
} else {
FlashTask.flash.off();
isLightOn=false;
return;
}
But it's not working...
Thanks advance.

Hard to know without seeing all your code. But you could declare a variable as field member, then change it on every button click.
That's the simpliest way:
public class MyActivity extends Activity {
//boolean field member initialized as false by default
private boolean isLightOn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
final Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isLightOn){
FlashTask.flash.off();
} else{
FlashTask.flash.on();
}
isLightOn = !isLightOn;
}
});
}
}

Every time the button is clicked, boolean isLightOn = false; is called and isLightOn will always be false when the button is clicked. You are not preserving the previous state.
To preserve the state, make isLightOn as a class variable and remove boolean isLightOn = false; from your listener method.

You need somthing like this.
private boolean isLightOn = false; //defined as class variable;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isLightOn){
FlashTask.flash.on();
isLightOn=true;
}else {
FlashTask.flash.off();
isLightOn=false;
}
}
});
But make sure isLightOn is defined outside the listener scope.

Related

How to change the background color of a view from a different activity in android?

I am working on a Quiz app. First when a user opens the app they go to the MainActivity, from there when they press start they go to the Categories Activity , from there after selecting a category they go to the Sets Activity, from there after selecting a set the go to the Questions Activity and finally after completing all the questions they reach the Score Activity. Here in the score activity when the click on Done button they are redirected to the MainActivity. In the Score Activity i want to change the color of the Set that they completed to green instead of the default color. How can i do this? I created a sets item layout xml file and used an adapter to fill the gridview in the Sets Activity with views from the adapter. Currently i am getting a null object reference after clicking the Done button in the ScoreActivity.
Here is the code :
SetsAdapter.java
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return numOfSets;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view;
if(convertView == null){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
}
else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent questionIntent = new Intent(parent.getContext(), QuestionActivity.class);
questionIntent.putExtra("SETNUM", position +1);
parent.getContext().startActivity(questionIntent);
}
});
((TextView) view.findViewById(R.id.setNumber)).setText(String.valueOf(position+1));
return view;
}
}
SetsActivity.java
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
private FirebaseFirestore firestore;
public static int categoryID;
private Dialog loadingDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
Toolbar toolbar = (Toolbar)findViewById(R.id.set_toolbar);
setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
categoryID = getIntent().getIntExtra("CATEGORY_ID",1);
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridView);
loadingDialog = new Dialog(SetsActivity.this);
loadingDialog.setContentView(R.layout.loading_progressbar);
loadingDialog.setCancelable(false);
loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.progress_background);
loadingDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
loadingDialog.show();
firestore = FirebaseFirestore.getInstance();
loadSets();
}
private void loadSets() {
firestore.collection("Quiz").document("CAT" + String.valueOf(categoryID))
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
long sets = (long) doc.get("SETS");
SetsAdapter adapter = new SetsAdapter(Integer.valueOf((int)sets));
sets_grid.setAdapter(adapter);
} else {
Toast.makeText(SetsActivity.this, "No Sets Exists!", Toast.LENGTH_SHORT).show();
finish();
}
} else {
Toast.makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
ScoreActivity.java
public class ScoreActivity extends AppCompatActivity {
private TextView score;
private Button done;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
score = findViewById(R.id.score_tv);
done = findViewById(R.id.score_activity_done);
String score_str = getIntent().getStringExtra("SCORE");
final int setNum = getIntent().getIntExtra("SetNum", 1);
score.setText(score_str);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
View view = findViewById(R.id.setNumber);
view.setBackgroundColor(Color.GREEN);
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
}
}
As your activity Sequence is MainActivity -> Categories -> Sets -> Scores.
You've two options to change the color with two different life cycle of the change.
To change the color on a temporary basis, this will reset itself after closing the app or resrtating the 'Sets' activity. It can be done in two ways: Using Public Static Variable and using a public function.
To change the color on a permanent basis until the app is uninstalled/reinstalled. You should use SharedPreferences. SharedPreferences acts like a private data stored in device's memory for further use and it stays there unchanged until and unless the app is removed/data is cleared. Although, apps with root permission can access any app's SharedPreferences data and can modify it as well.You can use SharedPreferences as explained here. Or, you can use some library to access it an easy way. The way I use it in all my apps is TinyDB(it's just a java/kotlin file). This works as:
//store the value from ScoreActivity after completion as
TinyDB tinyDB = TinyDB(this);
tinyDB.putBoolean("isSet1Completed",true);
//access the boolean variable in SetsActivity to change the color of any set that
//is completed and if it's true, just change the color.
TinyDB tinyDB = TinyDB(this);
Boolean bool1 = tinyDB.getBoolean("isSet1Completed");
But, it's your choice what way you want to prefer.
Now, this was about the lifecycle of the change you'll do: Temp or Permanent. Now, we'll talk about how you change the color.
Using public static variable in Sets activity. What you can do is you can set the imageView/textview whose background you want to change as public static variable. Remember, this idea is not preferred as it causes memory leak but it's just easy.
Declare it as public static ImageView imageview;(or TextView) intialize it in the
onCreated() as imageView = finViewById(R.id.viewId); in Sets activity. Call
it as new SetsActivity().imageView.setBackgroundColor(yourColor); in ScoreActivity.
Second way is to create a public function in SetsAcitvity, putting the color change code in it, and then calling it from the ScoreActivity. Just declare it as public void changeColor(){ //your work} and call it from ScoreActivity as new SetsActivity().changeCOlor(). You can also pass some arguments to the function like setId.
I've provided you every thing you need. Rest you should figure out yourself to actually learn it and not copy it.
I think simply you add flag in MainActivity.
for example, add flag in MainActivity.
boolean isFromDone = false;
and when done clicked,
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
mainIntent.putExtra("FromDone", true);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
and in MainActivity, add this.
#Override
protected void onResume() {
super.onResume();
isFromDone = getIntent().getBooleanExtra("FromDone", false);
if(isFromDone) {
(TextView) view.findViewById(R.id.setNumber)).setBackgroundColor(Color.GREEN);
}
}
Suppose you have a Linear Layout in Activity A and you want to change it's background color from a button click which is present in Activity B.
Step 1 Create a class and declare a static variable.
class Util { private static LinearLayout mylayout ; }
Step 2
In the activity which is holding this layout, initialize it.
Util.mylayout = findviewbyid(R.id.linear);
Step 3Change the background color on button click from Activity B
onClick{
Util.mylayout.setBackgroundColor(Color.RED);
}

Andorid : setOnClickListener does not work when calling Twice

I'm using setOnClickListener for listening on the click event on imageButton in two methods, but it's does not fire in my another method,my first listener firing but my second listener does not fire please see my codes :
Class FirstActivity extends BaseActivity
{
#Override
public void onCreate()
{
super.onCreate();
this.methodA();
this.methodB();
}
public void methodA()
{
ImageButton imageButton = (ImageButton) RContextHelper.getActivity().findViewById(R.id.my_location_button);
imageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//event firing when image button touched
}
});
}
public void methodB()
{
Test test = new Test(this);
test.methodA();
}
}
class Test
{
Context con;
public Test(Context con)
{
this.con = con;
}
public void methodA()
{
ImageButton imageButton = (ImageButton) getActivity().findViewById(R.id.my_location_button);
imageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//event does not fire when image button touched
}
});
}
protected ActionBarActivity getActivity()
{
return (ActionBarActivity) con;
}
}
As you can guess from the name setOnClickListener sets the new listener and replaces the old one. That is the case with all the set* listeners in Java. If it was addOnClickListener then you could expect that both listeners should be called.
If you want both of them to be called, you can write a composite on click listener and add both of the listeners to it and set the composite listener to the target.
class CompositeListener implements OnEventListener {
private List<OnEventListener> registeredListeners = new ArrayList<OnEventListener>();
public void registerListener (OnEventListener listener) {
registeredListeners.add(listener);
}
public void onEvent(Event e) {
for(OnEventListener listener:registeredListeners) {
listener.onEvent(e);
}
}
}
And then:
CompositeListener composite = new CompositeListener();
composite.registerListener(listener1);
composite.registerListener(listener2);
imageButton.setOnEventListener(composite);
Source
Very confusing to code with two methodA functions. You never call the second one. At least you are not showing code for that. Moreover - as has been said already - there can only be one listener.

Event get String from 2 buttons

I am using an Adapter to generate buttons in a GridView.
Using an OnClickListener, whenever I click a button from the GridView, it is possible to get the String of the button in a variable. However, I want to click a button, store its text in a variable, then click a different button, store its text in another variable so later I can compare the two texts. How could I do that?
gI'm using OnClickListener, therefore my previous implementation for one button was the following:
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText.toString();
With this approach, I can only get and store text from first button clicked, unless I store all the values in an array.
Ok so from what I can understand, you want to compare the strings of the two items in a grid view. If this is what you want, heres how I would do it(just a psuedocode):
String mValue1, mValue2;
boolean isOneClicked = false;
onItemClickedListener(item, position){
if(!isOneClicked){
mValue1 = item.stringValue;
isOneClicked = true;
}
else{
mValue2 = item.stringValue;
//do whatever you want here
//Reset when done
mValue1 = "";
mValue2 = "";
isOneClicked = false;
}
}
Please you can share your code to turn the things more comprehensible? Edit your question please... Anyways:
MainActivity.java
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private String butString, butString2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString = (String) button1.getText();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString2 = (String) button1.getText();
}
});
}
}
After that you can compare the two strings.

Getting the State of a Toggle Button

I may be going about this all wrong, but I have a view that contains a few ToggleButtons and a Save button. When the Save button is pressed, I want to collect the states of the various toggles as boolean values. I have tried the following in the onClickHandler for the Save button:
ToggleButton tb = (ToggleButton) findViewById(R.id.button1);
boolean pol = tb.isChecked();
and I would expect pol to be set to the state of button1, but it keeps being set to true. Of course I have tried this with the button in both states.
Thanks
you can try this
ToggleButton tb = (ToggleButton) findViewById(R.id.button1);
boolean pol = false;
tb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(tb.isChecked()) {
pol = true;
} else {
pol = false;
}
}
});
}

Pass method as parameter in Java to assign Listeners to multiple Buttons

I'm new to Java (coming from Python) and I'm trying to pass a method as a parameter in order to convert this code:
Button button1;
Button button2;
...
Button buttonN;
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button1(v);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button2(v);
}
});
(...)
buttonN = (...)
To something like:
public AssignListener( integer tButton, Method tMethod )
{
button_view = (Button) findViewById(tButton);
button_view.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
tMethod(view);
}
}
}
(...)
AssignListener( R.id.button1, onClick_button1 );
AssignListener( R.id.button2, onClick_button2 );
(...)
AssignListener( R.id.buttonN, onClick_buttonN );
I've read that you can't pass methods to functions, and some advice to wrap my function using Runnable to achieve this.
I have not clear idea about how to do it. Any idea on how do it easily? :?
Thanks.
EDIT: Should I wrap "AssignListener" in its own class and pass the class itself? :?
You can call findViewById() and seOnClickListener into onCreate method, and OnClickListenet outside the onCreate.
Button button1 = (Button)findViewById(R.id.button1);
or
findViewById(R.id.button1).seOnClickListener(mClickListener);
findViewById(R.id.button2).seOnClickListener(mClickListener);
findViewById(R.id.button3).seOnClickListener(mClickListener);
findViewById(R.id.button4).seOnClickListener(mClickListener);
private OnClickListener mClickListener = new View.OnClickListener(
public void onClick(View view){
switch(view.getId()){
case R.id.button1:
//button1 click handle here...
break;
case R.id.button2:
//button2 click handle here...
break;
case R.id.button3:
//button3 click handle here...
break;
case R.id.button4:
//button4 click handle here...
break;
}
});
Try it, hope it will helpful to you.
You could define and pass an onClickListener like this:
public AssignListener( integer tButton, OnClickListener listener ){
tButton.setOnClickListener(listener);
}
The simplest way is to create listener implementation for each button, as is written in your first snippet.
I don't see any reasonable benefit of having universal method like AssignListener(). Don't reinvent bicycle, use existing setOnClickListener() method and pass listener specific for button.
An easy solution would be to create a function called tMethod that takes a button id, and has a switch statement that allows for a certain action to be performed for the given button id. This would then be called inside the onClick function like tMethod(view.getId()).
Btw, Python has methods. Java has functions. Pedant mode turned off!
public class MyClass implements OnClickListener, OnLongClickListener {
Button button1;
Button button2;
...
Button buttonN;
. . .
setButtonsListener(findViewById(<your top view id>));
. . .
void setButtonsListener(ViewGroup vg) {
int count = vg.getChildCount();
Button btn;
View v;
for(int i=0; i < count ; i++) {
v = vg.getChildAt(i);
if( v instanceof Button ) {
btn = (Button)v;
btn.setOnClickListener(this);
btn.setOnLongClickListener(this);
} else if( v instanceof ViewGroup ) {
setButtonsListener((ViewGroup) v);
}
}
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}

Categories