I want to recieve data from thingspeak and change automatically state of switch from checked to unchecked or vice versa.
This is my code, but it doesn't work, just can set text but can't change state.
Please help me!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
myswitch1 = (Switch) findViewById(R.id.switch1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
postdata2();
}
});
t.start();
now_da1.setText(get_da1);
if(get_dk1 == "1") {
myswitch1.setChecked(False);
}
else if (get_dk1 =="0") {
myswitch1.setChecked(True);
}
}
});
myswitch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
t1 = "1";
} else {
t1 = "0";
}
}
});
public void postdata2() {
HttpRequest mReq = new HttpRequest();
get_t1 = mReq.sendGet("https://thingspeak.com/channels/106453/field/1/last");
get_da1 = get_t1.substring(0, 2);
get_dk1 = get_t1.substring(3, 3);
Log.d(myGet, get_dk1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
use this myswitch1.setChecked(false); to uncheck and myswitch1.setChecked(true); to make it checked.
Happy Coding :)
When comparing the value of two Strings always use the equals() method which compares the values instead of using == which compares the object references.
For example:
String first = "1";
String second = "1";
first == second will return false because they are not referencing to the same object. However, first.equals(second) will return true because the value of the two Strings are identical.
You can try replacing the conditions with this:
if (get_dk1.equals("1")) {
myswitch1.setChecked(false);
} else if (get_dk1.equals("0")) {
myswitch1.setChecked(true);
}
Related
I have a program which creates a list of to-dos that allows the user to set a date/time for the app to notify them about it. There's a checkbox that says 'Notify me' which is supposed to schedule the notification. But, in the main RecyclerView of the list, there is also a toggle switch that allows the user to turn off/on the notification after they've saved it. Problem is, the toggle switch doesn't seem to be changing the notification state.
holder.notifSwitch.setChecked(journalModel.isNotify());
if(journalModel.getJournalDateNotify().getTime() > System.currentTimeMillis())
{
holder.notifSwitch.setVisibility(View.VISIBLE);
} else {
holder.notifSwitch.setVisibility(View.INVISIBLE);
}
holder.notifSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!journalModel.isNotify())
{
createJournalFunction.updateJournal(realm, journalModel.getRealmJournalNo(),true);
} else
{
createJournalFunction.updateJournal(realm, journalModel.getRealmJournalNo(), false);
}
}
});
And here is the code for updating the Realm object:
public boolean updateJournal (Realm realm, final int realmJournalNo, final boolean isNotify){
success = false;
try{
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
final TblJournal tblJournal = realm.where(TblJournal.class).equalTo("realmJournalNo", realmJournalNo).findFirst();
tblJournal.setNotify(isNotify);
success = true;
}
});
}catch (RealmException e){
Log.i("INFO","update Retail Exception: "+e.toString());
success = false;
}finally {
return success;
}
}
As per your code your are not updating journalModel.isNotify= true or false in on click. journalModel.setIsNotify(true):/journalModel.setIsNotify(false):
holder.notifSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// status="true"; //edit here
switch_btn.setChecked(true);
} else {
// status="false"; //edit here
switch_btn.setChecked(false);
}
}
});
Everything looks fine, you just need to modify your onClick method.
holder.notifSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox checkbox = (CheckBox)v;
createJournalFunction.updateJournal(realm, journalModel.getRealmJournalNo(),checkbox.isChecked());
}
});
I am fairly new in android programming.
I am having two cases where I am unable to get the list updated.
FIRST
Here is my Activity (QuestionList Activity).
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ques_list);
....
quesList=quesDB.getQues(); //getting arraylist from database
qAdapter = new QuesList_Adaptor(quesList, this, this);
rv_qlist.setAdapter(qAdapter);
qAdapter.notifyDataSetChanged();
}
On other activity, taking user input which updates the database (thus also updates quesList above).
public void save (View view)
{
String ques = et_ques.getText().toString();
String optionA = et_optA.getText().toString();
String optionB = et_optB.getText().toString();
String optionC = et_optC.getText().toString();
String optionD = et_optD.getText().toString();
String ans = et_ans.getText().toString();
QuesDB qd = new QuesDB(this);
boolean b = qd.addQues(ques, optionA, optionB, optionC, optionD, ans);
if (b)
{
Toast.makeText(this, "Question Saved", Toast.LENGTH_SHORT).show();
}
*//so... I have to notify adapter here right? than, what's the way here to reference adaptor and use notifyDataSetChanged*
finish();
SECOND CASE
Setting up Multi-delete on recyclerview. Data is getting deleted but trouble in refreshing the list.
Please take a look into the code, I mentioned there using comments.
On Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
..
StoreNotesDB sdb = new StoreNotesDB(this);
noteslist= sdb.getStoreNotes(); //storing from database to array
mAdapter = new AdaptorNotes(this,noteslist, this);
rv.setAdapter(mAdapter);
}
#Override
public void OnLongClick() {
fab.setVisibility(View.GONE);
inActionMode = true;
actionMode = this.startActionMode(new ContextualCallback());
mAdapter.notifyDataSetChanged();
}
#Override
public void OnClick(AdaptorNotes.MyViewHolder holder, int pos) {
if (holder.chk_notes.isChecked())
{
selected_list.add(noteslist.get(pos));
//counter = counter + 1;
}
else
{
selected_list.remove(noteslist.get(pos));
//counter = counter - 1;
}
}
class ContextualCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.notescontextual_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
//Toast.makeText(MainActivity.this,"delete",Toast.LENGTH_SHORT).show();
if (selected_list.isEmpty()) {
Toast.makeText(NotesListViewActivity.this, "No item is selected", Toast.LENGTH_SHORT).show();
}
else{
//loop for deleting item from database of the selected list
for (MyStoreNotes myStoreNotes: selected_list)
{
String x = String.valueOf(myStoreNotes.getSl());
int y = storeNotesDB.deleteRow(x);
}
mAdapter.notifyDataSetChanged(); // it doesn't work
inActionMode = false;
selected_list.clear();
Toast.makeText(NotesListViewActivity.this, "Selected List Deleted", Toast.LENGTH_SHORT).show();
actionMode.finish();
}
}
return false;
}......
.....
I'm not sure if you're trying to refresh the data on each load of the activity, or if you are using a different method to refresh your data.
If you want to reload the data each time the recyclerview activity is shown, then you need to call...
quesList.clear();
after declaring the list, and before getting the data. That ensures that you are populating your recyclerview with the latest data from your database.
If this is not what you're asking, please explain what your app is currently doing vs what you want it to do.
I am working on android. I have a checkbox in my app and I want to save a custom text against my checkbox when it is checked or not.
CheckBox atbSealedCheckBox;
String selectedAtbSealedValue ="";
atbSealedCheckBox = (CheckBox) view.findViewById(R.id.atbCheckBox);
Now, If I checked the checkbox then I want to store Yes otherwise No. Also, I want to store it in my DB. For this I have already created get and set methods in my Model
private String atbSealed;
public String getAtbSealed(){return atbSealed;}
public void setAtbSealed(String atbSealed){this.atbSealed=atbSealed;}
Update 1
As per suggestion, I have tried below
atbSealedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(isatbSealedChecked)
{
selectedAtbSealedValue = "Yes";
ctQuantitySpinner.setEnabled(false);
ctQuantitySpinner.setSelection(0);
isatbSealedChecked = true;
}
else
{
selectedAtbSealedValue = "No";
ctQuantitySpinner.setEnabled(true);
ctQuantitySpinner.setSelection(0);
isatbSealedChecked = false;
}
}
});
But It doesn't help me out. Also, the ctQuantitySpinner is not disabled on atbSealedCheckbox checked. Also if checked the boolean value of the checkbox is not changed to true. Although in log I do see the selectedAtbSealedValue but it's not set in the app. In my SaveDataLocal() function I have set the value like below
survey.setAtbSealed(this.selectedAtbSealedValue);
SurveyManager dbHelper = new SurveyManager(getActivity());
dbHelper.addSurvey(survey);
I have also tried the below code
atbSealedCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(((CheckBox)v).isChecked())
{
ctQuantitySpinner.setEnabled(false);
ctQuantitySpinner.setSelection(0);
selectedAtbSealedValue = "Yes";
isatbSealedChecked = true;
//atbCheckBoxEdittext.setText(selectedAtbCheckBox);
}
else {
ctQuantitySpinner.setEnabled(true);
ctQuantitySpinner.setSelection(0);
selectedAtbSealedValue = "No";
isatbSealedChecked = false;
//atbCheckBoxEdittext.setText(selectedAtbCheckBox);
}
}
});
This code shows me the selected checkbox value, disabled the spinner and set the spinner value to null. but again the checkbox value is not saved.
How can I save custom text in a string?
Try this, it work for me:
atbSealedCheckBox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged( CompoundButton buttonView, boolean isChecked ) {
if (isChecked) {
selectedAtbSealedValue = "yes";
} else {
selectedAtbSealedValue = "no";
}
}
} );
After that, you can store selectedAtbSealedValue into DB;
Update: Your fixed code:
atbSealedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b)
{
selectedAtbSealedValue = "Yes";
ctQuantitySpinner.setEnabled(false);
ctQuantitySpinner.setSelection(0);
isatbSealedChecked = true;
}
else
{
selectedAtbSealedValue = "No";
ctQuantitySpinner.setEnabled(true);
ctQuantitySpinner.setSelection(0);
isatbSealedChecked = false;
}
}
});
As long as I understand your question, you want to change this variable String selectedAtbSealedValue =""; when user checked your checkbox.
To achieve this statement, you can use onCheckedListener that is triggered as soon as users checked or removed the check from your checkbox.
atbSealedCheckBox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged( CompoundButton buttonView, boolean isChecked ) {
// Todo something.
}
} );
This will help you.
At submit button get the current value of checkbox.
submit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
control_of_vectors_value = control_of_vectors_checkbox.isChecked() == true ? "yes" : "no"; }}
I am making an app that toggles off and on a switch. I have 4 switches in total and at the bottom I would like to have a button that will toggle them all off at the same time - like an override switch. I'm trying to follow the same format as when creating the 4 switches, but I can't wrap my head around how it would be. I already tried looking through stackOverFlow and I can't find anything on it, maybe I just don't know the key words.
Switch toggleapp1 = (Switch) findViewById(R.id.app1);
toggleapp1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
toggleapp1(true);
Toast.makeText(getApplicationContext(), "[Application1] Enabled!", Toast.LENGTH_LONG).show();
} else {
toggleapp1(false);
Toast.makeText(getApplicationContext(), "[Application1] Disabled!", Toast.LENGTH_LONG).show();
}
}
});
Is how one of the switches look. toggleapp1 is switched with 2,3,4.
public boolean toggleapp1(boolean status) {
if (status == true) {
return true;
}
else if (status == false) {
return false;
}
return status;
}
I have 4 switches in total and at the bottom I would like to have a button that will toggle them all off at the same time - like an override switch.
If i understood the problem you have something like:
toggleapp1 = (Switch) findViewById(R.id.app1);
toggleapp2 = (Switch) findViewById(R.id.app2);
toggleapp3 = (Switch) findViewById(R.id.app3);
toggleapp4 = (Switch) findViewById(R.id.app4);
And you want to disable all of them togheter.
You can create a method that do this:
private toggleOffSwitches(boolean state) {
toggleapp1.setChecked(state);
toggleapp2.setChecked(state);
toggleapp3.setChecked(state);
toggleapp4.setChecked(state);
}
And call it in the OnClickListener of the button:
Button yourButton = (Button) findViewById(R.id.yourButton);
yourButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
toggleOffSwitches(false);
}
});
Remember to declare your Switches as field class variables in order to use them in the toggleOffSwitches method!
UPDATE
For example:
public class MainActivity extends Activity {
private Switch toggleapp1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
toggleapp1 = (Switch) findViewById(R.id.app1);
....
}
I'm working on rendering a text on textview. I'm trying to add two buttons to zoom in and out the text inside text view and the code goes like this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chapter_view);
String chapter;
chapter=getIntent().getExtras().getString("ChapterName");
final StringBuffer buffer = new StringBuffer();
int id= getResources().getIdentifier(chapter,"raw",getPackageName());
try{
DataInputStream dataIO= new DataInputStream(getResources().openRawResource(id));
String strLine= null;
while((strLine = dataIO.readLine())!=null){
buffer.append(strLine);
buffer.append("\n");
}
dataIO.close();
}catch(Exception e){
}
final TextView tv=(TextView) findViewById(R.id.chapter);
tv.setText(buffer.toString());
Button zoomIn = (Button) findViewById(R.id.zoomin);
zoomIn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
textSize = tv.getTextSize();
tv.setTextSize((float) (textSize+0.25));
}
});
Button zoomOut = (Button) findViewById(R.id.zoomout);
zoomOut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
textSize = tv.getTextSize();
tv.setTextSize((float) (textSize-0.25));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.chapter_view, menu);
return true;
}
}
But the problem I'm getting is the even upon clicking zoom out button, it still increasing the font size of the text. Please help me out in this. Also once I close one chapter and opens another, the text size will reset to its default value. Are there any solutions regarding this. I'm thinking of using the namevalue pair for this solution.
The problem is that the unit passed to setTextSize(float size) is in scaled pixels, whereas getTextSize() reports in pixels. Try using setTextSize(int unit, float size) instead, setting unit to TypedValue.COMPLEX_UNIT_PX.
I've tried a sample at my machine. Check the code below. You have to place the variable at the right place with the scope.
public class MainActivity extends Activity {
float textSize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView1);
textSize = tv.getTextSize();
Button btnPlus = (Button)findViewById(R.id.button1);
btnPlus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.textView1);
Log.v("TextSizeP", String.valueOf(textSize));
textSize = (float) (textSize+0.25);
tv.setTextSize(textSize);
Log.v("TextSizeP", String.valueOf(textSize));
}
});
Button btnMinus = (Button)findViewById(R.id.button2);
btnMinus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.textView1);
Log.v("TextSize", String.valueOf(textSize));
textSize = (float) (textSize-0.25);
tv.setTextSize(textSize);
Log.v("TextSize", String.valueOf((float) (textSize-0.25)));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
For example I have my textSize variable declared at the class level. And the textSize variable is increased and decreased when the relevant button is clicked.
This works fine for me.
As for the size that returns to its default , you will have to use shared preferences to save the value of the last text size .
As for the text size , why don't you increment the value one by one , for instance tv.setTextSize(textsize++) when zoomOut is clicked
or tv.setTextSize(textsize--) when zoomIN is clicked
public class MainActivity extends Activity {
TextView tv;
Button in,out;
static float textSize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,30);
textSize = tv.getTextSize();
in = (Button) findViewById(R.id.zoomin);
out = (Button) findViewById(R.id.zoomout);
in.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textSize = (float)(textSize + 2);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,textSize);
}
});
out.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textSize = (float)(textSize - 2);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,textSize);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}