toggle button state depend on feedback from server - java

Arduino server and android client i want to make toggle button state depend on string feedback from server
i have tried this but does not work
this code below was woeking week ago i didnt change anything but now i got the problem
Arduino:
if (packetBuffer[0]=='3')
{
if (buttonstate == HIGH)
{
Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
Udp.write("on");
Udp.endPacket();
}
else
{
Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
Udp.write("off");
Udp.endPacket();
}
}
Android:
coming = new String(recd.getData());
Toast.makeText(getApplicationContext(),coming,Toast.LENGTH_LONG).show();
textView = (TextView)findViewById(R.id.textView);
textView.setText(coming);
if (coming=="on")
{
apf.setChecked(true);
}
else if (coming=="off")
{
apf.setChecked(false);
}
d1.close();

Related

Java: Stuck inside if statement block

i am starting with creating android apps, i already have some basic experience with C# and Java. Now i'm stuck at a strange problem, see below:
public void pictureSwitch (View view){
ImageView imageView = (ImageView) findViewById(R.id.imgVCat);
boolean switched = false;
if (switched){
imageView.setImageResource(R.drawable.catstart);
Log.i("Status-Start", "Wert: " + switched);
switched = false;
} else {
imageView.setImageResource(R.drawable.catswitch);
Log.i("Status-switched", "Wert: " + switched);
switched = true;
}
}
}
The Problem is, on the first click on the Button it changes to the catswitch drawable. But it never switches back and i dont know why.
Thanks for your help in advance.
Lets have a boolean as instance variable.
private boolean switched = false;
public void pictureSwitch() {
ImageView imageView = (ImageView) findViewById(R.id.imgVCat);
if (switched) {
imageView.setImageResource(R.drawable.catstart);
} else {
imageView.setImageResource(R.drawable.catswitch);
}
switched = !switched;
}
And you do not need a parameter View view if you are not using it .

Android Studio TextToSpeech run issue

I am basically making a firstaid training app (to help get people prepared for NL (National lifeguard) and Standard first aid).
This is done in a multiple choice form factor, and I have an activity which pulls all the questions, answers, and explanations and stores them in an array. As the user answers each question, it moves onto the next by replacing the text on the buttons and textview of the question, and I have made it so android says the question using TextToSpeech.
My error, is that for some reason on the first question, the string (question) gets given to the TextToSpeech talker, but it does not say it? What is weird is that for the other questions (2,3,4,etc.) it works, just not for the first.
I thought that maybe it was that it didnt have enough time to construct (which some other thread said was the problem when the TextToSpeech lags), so I added a delay to the button that starts the multiple choice activity and it still did not work for the first question, but works for the rest.
Here is my code for the TextToSpeech:
In the onCreate of the class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_menu);
prefs = getSharedPreferences("com.comsci.michelaustin.comscisummative", MODE_PRIVATE);
moduleNumber = getIntent().getIntExtra("MODULE_ID", 0);
talker = new TextToSpeech(QuizMenuActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
result = talker.setLanguage(Locale.UK);
}
else
{
Toast.makeText(getApplicationContext(), "Talking feature not supported on this device", Toast.LENGTH_SHORT).show();
}
}
});
In the method that sets the textview and buttons to the correct question and answers:
private void displayQuestions(){
String ques = mQuestionLibraryTest.getQuestion(questionNumber);
questionLabel.setText(ques);
talker.speak(ques,TextToSpeech.QUEUE_FLUSH,null);
option1.setText(getChoice(questionNumber,0));
option2.setText(getChoice(questionNumber,1));
option1.setEnabled(true);
option2.setEnabled(true);
option3.setEnabled(true);
option4.setEnabled(true);
option1.setBackgroundColor(getResources().getColor(R.color.colorLightblue));
option2.setBackgroundColor(getResources().getColor(R.color.colorLightblue));
option3.setBackgroundColor(getResources().getColor(R.color.colorLightblue));
option4.setBackgroundColor(getResources().getColor(R.color.colorLightblue));
//to test specifically for true and false questions and to remove visibility of the last two buttons
if (testWhetherBlank(2)) {
option3.setVisibility(View.GONE);
}
else{
option3.setVisibility(View.VISIBLE);
option3.setText(getChoice(questionNumber,2));
}
if (testWhetherBlank(3)) {
option4.setVisibility(View.GONE);
}
else{
option4.setVisibility(View.VISIBLE);
option4.setText(getChoice(questionNumber,3));
}
//
//answerArray=(ArrayList<Object>)mQuestionLibrary.getCorrectAnswer(questionNumber).clone();
answerArray = (ArrayList<String>) mQuestionLibraryTest.getCorrectAnswer(questionNumber).clone();
//Collections.copy(mQuestionLibraryTest.getCorrectAnswer(questionNumber), answerArray);
//explanation=mQuestionLibrary.getExplanation(questionNumber);
explanation = mQuestionLibraryTest.getExplanation(questionNumber);
amountCorrect=mQuestionLibraryTest.getAnswerAmount(questionNumber);
nextArrowButton.setVisibility(View.GONE);
writeResume();
}
//allows the UI to test and remove buttons if the options are blank
public boolean testWhetherBlank(int q){
/*if(mQuestionLibrary.getChoice(questionNumber,q).equals("")){
return true;
}*/
if(mQuestionLibraryTest.getChoice(questionNumber,q).equals("")){
return true;
}
else{
return false;
}
}
Any help is greatly appreciated!

How to save the state of a togglebutton when scrolled out in recyclerview?

I have togglebuttons in each views from my recyclerview and I set a Data in my Sqlite database which give me the state of the ToggleButton when I quit the app to restore it at the start. It's work fine: when i check a ToggleButton, leave the app and restart it, the ToggleButton has the same state that when i left the app. But the problem is: When i check a ToggleButton, scroll out the view and after scroll up, the ToggleButton is no longer checked but if I quit the app and come back, it's checked. How can I save the state of my ToggleButton when I scroll out ?
My code in my onBindViewHolder:
holder.state.setText(item.getState());
holder.toggle.setChecked(false);
if(holder.state.getText().toString().equals("yes")) {
holder.toggle.setChecked(true);
holder.toggle.setBackgroundResource(R.drawable.trianglegreenup);
marks_string = holder.marks.getText().toString();
marksint = Integer.valueOf(marks_string);
marksint--;
marks_string = String.valueOf(marksint);
myDb.updateData(holder.id.getText().toString(), marks_string);
holder.marks.setText(marks_string);
} else {
holder.toggle.setChecked(false);
}
Where State is just a string in sqlite Database with default value:"no"
My code in MyViewHolder:
toggle =((ToggleButton) itemView.findViewById(R.id.toggleButton));
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked ){
if (isChecked){
if(toggledown.isChecked()) {
toggledown.setChecked(false);
toggle.setChecked(false);
toggledown.setBackgroundResource(R.drawable.triangleblackdown);
myDb.updateData2(id.getText().toString(), "no");
} else {
toggle.setBackgroundResource(R.drawable.trianglegreenup);
marks_string = marks.getText().toString();
marksint = Integer.valueOf(marks_string);
marksint++;
marks_string = String.valueOf(marksint);
myDb.updateData(id.getText().toString(), marks_string);
marks.setText(marks_string);
myDb.updateData2(id.getText().toString(), "yes");
state.setText("yes");
}
} else {
toggle.setBackgroundResource(R.drawable.triangleblackup);
marks_string = marks.getText().toString();
marksint = Integer.valueOf(marks_string);
marksint--;
marks_string = String.valueOf(marksint);
myDb.updateData(id.getText().toString(), marks_string);
marks.setText(marks_string);
myDb.updateData2(id.getText().toString(), "no");
state_.setText("no");
}
}
});
Where "ToggleDown" is the ToggleButton opposite of Toggle.
Thanks !
Assume you have scrolled up and forth, and pretty reasonably, your ViewHolder is being reused.
Now let's analyze your onBindViewHolder():
holder.toggle.setChecked(false); // This will result in `onCheckedChanged()` to be called
if(holder.state.getText().toString().equals("yes")) {
holder.toggle.setChecked(true); // This will result in `onCheckedChanged()` to be called
// some code here
} else {
holder.toggle.setChecked(false); // This will result in `onCheckedChanged()` to be called
}
So, at least two times you are unintentionally calling onCheckedChanged() method of your ViewHolder. That ViewHolder is being reused and when you first created it you attached a CheckedChangeListener and haven't detached it.
In order to remove that listener you have to know when a ViewHolder is actually being recycled, which onViewRecycler(ViewHolder) exactly tells you:
#Override
public void onViewRecycled(final RecyclerView.ViewHolder holder) {
holder.toggle.setOnCheckedChangeListener(null);
super.onViewRecycled(holder);
}
I think you aren't updating your model when you are checking the switch. You're just updating the database. Update your model too and your code will work as expected.

Login button not setting the textview text correctly Android

I have been working at this for a hot minute now and I can't figure out why the text won't be set correctly when the button is pressed. It is set correctly everywhere else just not this spot. I tried moving it around in different places but still no effect.
the first loginSuccess.setText("Checking Credintails"); is not working. The others work fine in the code which has me baffled. Any help with this would be appreciated.The loginSuccess.setText("Checking Credintails"); should be called when the button is pushed.
So here is my code for the button OnClick
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginSuccess.setText("Checking Credintails");
//test to see if there is a connection
ConnectionTester ct = new ConnectionTester();
boolean online = ct.isOnline(v.getContext());
boolean issue = false;
Tracker longinTracker = ((AnalyticsApplication) getApplication()).getDefaultTracker();
userName = user.getText().toString();
passWord = pass.getText().toString();
LoginJsonParser ljp = new LoginJsonParser();
if(online)
{
try {
ljp.checkUsername(loginUrl, userName, passWord);
canLogin = ljp.returnedResult;
} catch (IOException e) {
e.printStackTrace();
}catch (NullPointerException ne)
{
issue = true;
loginSuccess.setText("接続の問題");
Log.d("Null point ", "Jsonl login");
}
//if(userName.equals("admin") && passWord.equals("admin")0
if(canLogin == true)
{
//Write to the ShardedPreference to store for later use
Log.d("My user name " , userName);
Log.d("My Password " , passWord);
MySharedPerference.writeString(getApplicationContext(),MySharedPerference.USERNAME, userName);
MySharedPerference.writeString(getApplicationContext(),MySharedPerference.PASSWORD, passWord);
//build login event
//call this first otherwise it may not be called and wont post to the servers
longinTracker.send(new HitBuilders.EventBuilder()
.setCategory(getString(R.string.eventCategory))
.setAction(getString(R.string.loginevent))
.build()
);
//Start downloaing and processing customer data
//Also open up the Loading screeen animation
loadingImage.setVisibility(View.VISIBLE);
loginSuccess.setText("Loging you in now");
donwloadCustomerData();
}else
{
if(issue != true)
{
loginSuccess.setText("パスワードが違います");
}else{
loginSuccess.setText("接続に関する問題");
}
}
}else
{
Intent noCon = new Intent(v.getContext(), NoConnection.class);
startActivity(noCon);
}
}
});
Thank you everyone for helping with this. I figured what was happing with the setText() problem.
I was changing right to a degree so it would change but the UI would not update before it started to download the data from the server. So the downloading was taking over the thread and not letting the UI update and change. so that is why the later setText worked but not the first setText. After I put all the downloading into its own thread the set text works fine. I appreciate everyones help with this all your ideas lead me to think about this in a new light and solve this issue. Thank you again.

How can I show a button when all views are viewed in viewpager?

Right now I have a save button that I want to show only if all the views inside a viewpager are shown. That means that when the user swipes between views and have seen all views inside a viewpager, then show a save button.
I want to show the save button on every view when they have seen all views hereby after.
The trouble I am having is how to set up the logic. I started out with setting the save button invisible until the last view of the viewpager. On the last view of the viewpager, show the save button. But the problem is when the user goes to the last view (there's a save button) and then goes back to a previous view, the save button is gone.
So, I was wondering how can I show the save button permanently on all views after the user has seen all views?
Here's what I have so far:
I have this snippet inside my InstantiateItem() :
if(isViewed)
{
save_button.setVisibility(Button.VISIBLE);
System.out.println("Is this called? isViewed = true");
}else if (position == numberOfPages.size()-1) {
isViewed = true;
save_button.setVisibility(Button.VISIBLE);
}
where
#Override
public void onPageSelected(int position) {
isViewed = true;
}
EDIT:
I tried the following solutions but with no luck.
Button save_button = (Button) findViewById(R.id.save);
if(isViewed[position])
{
save_button.setVisibility(Button.VISIBLE);
}
if (position == numberOfPages.length-1 && !isViewed[position]) {
isViewed[position] = true;
save_button.setVisibility(Button.VISIBLE);
}
isViewed[position] =true;
And
isViewed[position] = true;
if (isViewed[position] == isViewed[numberOfPages.length-1]) {
save_button.setVisibility(Button.VISIBLE);
}
if (isViewed[position]) {
save_button.setVisibility(Button.VISIBLE);
} else {
save_button.setVisibility(Button.INVISIBLE);
}
In your onPageSelected, do the following
if(isViewed)
{
save_button.setVisibility(Button.VISIBLE);
}
if (position == numberOfPages.size()-1) {
isViewed = true;
save_button.setVisibility(Button.VISIBLE);
}
Note the above are two seperate if statements.
Make your isViewed global and default to false.
boolean []isViewed = new boolean[noOfPages.size()];
#Override
public void onPageSelected(int position) {
if(isViewed[position])
{
save_button.setVisibility(Button.VISIBLE);
}
else {
save_button.setVisibility(Button.GONE);
}
isViewed[position] = true;
}

Categories

Resources