I'm creating an IoT project through which I will be able to control home devices and utilities over internet. In the below code, it'll open a curtain when the switch is enabled. What I want to do here is to disable the button until the curtain is fully open which takes 5 seconds of time, so the user won't be able to press the button to close the curtain until it is fully open (because of limitations in servo motor). I've wrote the below code to accomplish this. It uses the Timer class. But it is not disabling the switch at all. Any help would be appreciated. Thanks!
curtain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("open")) {
Toast.makeText(getApplicationContext(), "Curtain is opening..", Toast.LENGTH_LONG).show();
final long period = 5000;
new Timer().schedule(new TimerTask() {
#Override
public void run() {
curtain.setEnabled(false);
}
}, System.currentTimeMillis(), period);
curtain.setEnabled(true);
} else {
Toast.makeText(getApplicationContext(), "Failed to open", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Connection failed. Please check your internet connection.", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> getData = new HashMap<>();
getData.put("device", "curtain");
getData.put("action", "open");
return getData;
}
};
IotSingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
}
Simply use Handler as below:
...
#Override
public void onResponse(String response) {
if (response.equals("open")) {
buttonView.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
buttonView.setEnabled(true);
}
}, 5000);
} else {
Toast.makeText(getApplicationContext(), "Failed to open", Toast.LENGTH_SHORT).show();
}
}
...
See if it works for you...!!
Related
I have this issue with Volley library requests. I make calls to API and since they have to be updated very often I implemented timers. After some time it throws me error:"Throwing OutOfMemoryError “pthread_create (1040KB stack) failed: Try again. I used the method which was suggested in this post: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again" when doing asynchronous posts using Volley , but for me it did not work, the data coming from API stopped updating. I thought it might be something with timers or it is just something I am doing wrong using Volley.
If you have any idea, feel welcome to share.
My printer class
public void setMenuInformation(String url, Context context, final VolleyCallback callback) {
Log.d("API", "Currently calling URL " + url);
if (eRequestQueue == null) {
eRequestQueue = Volley.newRequestQueue(context);
eRequestQueue.add(new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String temp = response.substring(2, response.length() - 2);
Log.d("API", "Current menu" + response);
byte msgArray[];
try {
msgArray = temp.getBytes("ISO-8859-1");
currentMenu = msgArray[0];
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
menuInformation = response;
callback.onSuccess(menuInformation);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("API", "Current menu Nope ");
callback.onFailure(error);
}
}));
}
}
Main Activity:
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu",
MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("NSD", "Current menu response succeded and added to array " + nsdServiceInfo);
//services.add(myPrinterDetails);
mAdapter.notifyDataSetChanged();
}
});
Log.d("NSD", "CurrentMenu " + myPrinterDetails.getMenuInformation());
myTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu", MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
Log.d("NSD", "Current menu response added to timer " + nsdServiceInfo);
mAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu timer failed");
}
});
}
});
}
}, 0, 2000);
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu response failed");
}
});
}
};
}
I'm using IP Webcam app in my android phone to use it as an IP camera and I'm using another android phone to run my app that recognizes faces using Kairos API. I'm using the IP Webcam app and the image is streamed at a url which is something like:
"http://xxx.xxx.x.xxx:8080/photo.jpg" and I am able to view the image through this url on all the devices, however the API that I'm using has a recognize function that takes image url as one of it's parameters but when I'm using the streamed image URL, it doesn't work. I tried figuring out what's happening through logs but all I could see was that it threw a SocketTimeoutException(read time out) and tried solutions for it from SO but nothing worked, any suggestions here?
code:
public void getUrlText(){
try{
url = new URL("http://xxx.xxx.x.xxx:8080/photo.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Handler handler = new Handler();
Runnable timedTask = new Runnable(){
#Override
public void run() {
getUrlText();
handler.postDelayed(timedTask, 1000);
}};
and this is inside onCreate method:
getUrlText();
handler.post(timedTask);
recognizePhotoKairos(Uri.parse(url.toString()), userPhoneNumber);
When you are using ip webcam make sure your all the devices connected to same server.
Second thing is that you have to refresh the url again and again in order to get the latest image. I think this is your main problem in refreshing the url. I suggest you to use handler for this, which wait for a particular time and then refresh the url again or api in your case.
Read more about handler
I am adding the my source code of a project where i start the handler again and again
public class CounterActivity extends AppCompatActivity {
TextView textView;
private boolean started = false;
private PowerManager.WakeLock wl;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
textView=findViewById(R.id.points);
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My:Tag");
// screen stays on in this section
start();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final String URL="http://172.16.16.108:8080/wallgame/api/game_points";
StringRequest request=
new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object=new JSONObject(response);
JSONObject data=object.getJSONObject("data");
int points=Integer.parseInt(data.getString("game_points"));
textView.setText(points+"");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CounterActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
);
RequestQueue queue= Volley.newRequestQueue(CounterActivity.this);
queue.add(request);
}
},1000);
}
Runnable runnable = new Runnable() {
#Override
public void run() {
final String URL="http://172.16.16.108:8080/wallgame/api/game_points";
StringRequest request=
new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object=new JSONObject(response);
JSONObject data=object.getJSONObject("data");
int points=Integer.parseInt(data.getString("game_points"));
textView.setText(points+"");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CounterActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
);
RequestQueue queue= Volley.newRequestQueue(CounterActivity.this);
queue.add(request);
start();
}
};
public void onDestroy() {
super.onDestroy();
started = false;
handler.removeCallbacks(runnable);
if (wl.isHeld())
wl.release();
}
public void start(){
started = true;
handler.postDelayed(runnable, 1500);
}
}
how can i create notification
when the date current equals date in the base data(mysql)
then the notification created with information.
i dont know how can i create the notification with this setting
please help me it's for project
btn.setOnClickListener(new View.OnClickListener() {
#override
public void onClick(final View view) {
StringRequest request = new StringRequest(Request.Method.POST, insert, new Response.Listener<String>() {
#override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(partietache.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> para = new HashMap<String , String>();
para.put("taskname", ed1.getText().toString().trim());
para.put("totalwork",ed4.getText().toString().trim());
para.put("datetask",ed2.getText().toString().trim());
para.put("starttime",ed3.getText().toString().trim());
para.put("description",ed5.getText().toString().trim());
return para;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(partietache.this);
requestQueue.add(request);
Snackbar snackbar = Snackbar.make(view,"Add with Succesful" , Snackbar.LENGTH_LONG);
snackbar.show();
new Timer().schedule(new TimerTask(){
public void run() {
partietache.this.runOnUiThread(new Runnable() {
#override
public void run() {
finish();
}
});
}
} , 4000);
}
});
#override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (not.isChecked()) {
Toast.makeText(getApplicationContext() , "Notification " + not.getTextOn().toString() , Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext() , "Notification " + not.getTextOff().toString() , Toast.LENGTH_SHORT).show();
}
}
In order to use push notifications you will need to do both server-side and client-side coding. Describing the whole process in detail would be too much for an SO answer, you should take a look at one of the many tutorials available online. Here's one to get you started.
I don't even know I am right are wrong. My situation of thinking is currently null. can some please tell me how to update deliverystatus
This is code in AdapterClass
delivered.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String serverURL= PathUrls.pathUrl+"evs_updatedeliverystatus.php?db="+companyName.getString("companyName","")+"&invoiceid="+dlb.getInvoiceNo()+"&deliverystatus=1";
JsonObjectRequest jsonArrayRequest=new JsonObjectRequest(serverURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("update delivery list",response.toString());
deliveryListBeans.clear();
notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error DeliveryList:%n %s ", error);
Toast.makeText(ct,"NetworkError Not Responding", Toast.LENGTH_SHORT).show();
}
});
//Toast.makeText(ct, "companyName"+companyName.getString("companyName","").toString(), Toast.LENGTH_LONG).show();
VolleySingleton.getsInstance().getRequestQueue().add(jsonArrayRequest);
}
});
My app performs uploading operation to backend php server.My problem is i cannot dismiss the progressdialog inside volley Onresponse() method.Onresponse() method gets executed and toast is displayed in background of the Progressdialog so that means Onresponse() gets called currectly.
I declared ProgressDialog variable in public
onCreate() method look like this
ProgressDialog dialog;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog=new ProgressDialog(context,ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(true);
dialog.show(context,"Signing up","Please wait...");
login_call();
}
Login_call() performs volley request and inside the onResponse() i need to dismiss the dialog but its not working.
public void login_call()
{
RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.56.1/sign.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
dialog.dismiss();
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
else
{
dialog.dismiss()
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = new HashMap<>();
param.put("user",user.getText().toString());
param.put("pass",pass.getText().toString());
param.put("name",name.getText().toString());
param.put("mob",mob.getText().toString());
param.put("email",email.getText().toString());
param.put("photo",photo);
return param;
}
};
queue.add(request);
}
Toast message is displaying correctly but progressdialog is not gettting dismissed.
Any ideas to solve the problem??
Just change this :
RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.56.1/sign.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss(); // write it there
if (response.equals("success")) {
// dialog.dismiss(); remove this from here..!!
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}
Edit : set this
dialog.setIndeterminate(false);
first in first you didn't check all conditions
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
dialog.dismiss();
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
**} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}**
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
The else block doesn't hide the dialog so you should change it in this way
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
if (response.equals("success")) {
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
I think that the mistake is this, of course assuming that your dialog is accessible from the callback
Change your Dialog.show method to use this version: show(Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable) like this:
final ProgressDialog dialog = ProgressDialog.show(context, "Signing up","Please wait...", false, true);
So your onClick code should change to something like this:
public void onClick(View view) {
final ProgressDialog dialog = ProgressDialog.show(context, "Signing up","Please wait...", false, true);
login_call();
}
Please give this a try and let me know if it helps.