Sometimes Socket data not received properly in android studio - android

I am new to the java as well as Android.
Data write is working ok as i seen it on the modsim terminal(modbus protocol terminal), query is also valid as the response is generated through terminal but most of the time data is not received in the socket.
Here is the expected work flow of the code.
after pressing read button writing thread is being called after some delay like 500ms read thread is called and after some delay for ensuring reading is complete process the data if valid query is received or not. what i observe is in the received buffer data is 0 but rec_count showing the value.
and chk_data is being called.
I have tried the handler postdelayed but some error generated as i call thread there.
Also m'i using the CounDowntimer correctly?
Please suggest the good approach to delay the function call
I have skip the some code routine as it gets the unnecessary attention.
here is the code,
write_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder.setMessage("Wait...");
builder.setCancelable(false);
//Creating dialog box
final AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Data Writing!");
alert.show();
((Myapplication) getApplication()).setData_array( 10,1);
data_length = write_multiple_reg(output_array);
new Thread(new Write_Thread()).start();
start_timer3();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 500ms
alert.cancel();
}
}, 5000);
}
});
read_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder.setMessage("Wait...");
builder.setCancelable(false);
//Creating dialog box
final AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Data Read!");
alert.show();
data_length = holding_register(output_array);
new Thread(new Write_Thread()).start();
start_timer1();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 500ms
alert.cancel();
cancel_timer1();
start_timer2();
}
}, 5000);
}
});
}
void start_timer1(){
timer1 = new CountDownTimer(300,10) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
new Thread(new Read_Thread()).start();
//cancel_timer1();
}
};
timer1.start();
}
void cancel_timer1(){
if(timer1 != null)
{
timer1.cancel();
}
}
void start_timer2(){
timer2 = new CountDownTimer(1000,10) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
chk_data();
}
},500);
//cancel_timer2();
}
};
timer2.start();
}
void cancel_timer2(){
if(timer2 != null)
{
timer2.cancel();
}
}
void start_timer3(){
timer3 = new CountDownTimer(500,10) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
new Thread(new Read_Thread()).start();
start_timer2();
//cancel_timer3();
}
};
timer3.start();
}
void cancel_timer3(){
if(timer3 != null)
{
timer3.cancel();
}
}
class Thread1 implements Runnable {
#Override
public void run() {
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
output = socket.getOutputStream();
input = socket.getInputStream();
runOnUiThread(new Runnable() {
#Override
public void run() {
//tvMessage.setText("Connected\n");
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_LONG).show();
}
});
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Write_Thread implements Runnable {
#Override
public void run() {
try {
output.write(output_array,0,data_length);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Read_Thread implements Runnable {
#Override
public void run() {
while (true) {
try {
rec_count = input.read(input_array);
} catch (UnknownHostException e1) {
e1.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
void chk_data()
{
if(rec_count!=0) {
rec_crc = crc_generate(input_array, (byte) (rec_count - 2));
rec_crc &= 0x0000FFFF;
rec_high_crc = (byte) (rec_crc >> 8);
rec_low_crc = (byte) rec_crc;
if ((rec_high_crc == input_array[rec_count - 1]) && (rec_low_crc == input_array[rec_count - 2])) {
if (input_array[1] == 0x03) //holding register response
{
copy_input_data(rec_count);
if(cnv_data[10]==2)
{
//write successful message
cnv_data[10]=0;
builder1.setMessage("Successful");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder1.show();
}
else if(cnv_data[10]==1)
{
//write failed message
cnv_data[10]=0;
builder1.setMessage("Failed");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder1.show();
}
}
if(input_array[1] == 0x10)
{
data_length = holding_register(output_array);
new Thread(new Write_Thread()).start();
start_timer3();
}
} else {
builder1.setMessage("Failed");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder1.show();
}
}
else
{
builder1.setMessage("Failed");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder1.show();
}
rec_count=0;
cancel_timer2();
}

Related

android print "connection timeout" when timeout in loopj

android I finding more but none of get solution..
when occur time out in loopj , I want print Time-out message..
Follow code for time-out which I used.
private static final int DEFAULT_TIMEOUT = 15 * 1000;
private static AsyncHttpClient client = new AsyncHttpClient();
public static void setTimeOutTime() {
client.setTimeout(DEFAULT_TIMEOUT);
System.out.println("timeout");
}
try {
response = client.newCall(request).execute();
jsonObj = new JSONObject(response.body().string());
} catch (IOException e) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (getStatus() == Status.RUNNING) {
cancel(true);
if(!hiddenDialog) {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle("Timeout error")
.setMessage("Sorry server doesn't response!\nCheck your internet connection and try again.")
.setCancelable(true)
.setPositiveButton("Try again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Log.d(TAG, "load again");
}
}).setIcon(R.drawable.ic_dialog_alert_dark);
AlertDialog alert = builder.create();
alert.show();
}
});
} catch (JSONException e) {}
EDIT
for your case it should be the same way
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// make toast
}
});

Call Thread.wait()

I need to make currentThread wait when do some operations in UiThread and then in UiThread call currentThread().notify() . I was trying this code
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
try {
currentThread().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
AlertDialog.Builder facultyChooser = new AlertDialog.Builder(ctx);
facultyChooser.setTitle("choose")
.setCancelable(false)
.setItems(arr, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
currentThread().notify();
}
})
.create()
.show();
}
});
}
but got java.lang.IllegalMonitorStateException: object not locked by thread before wait() exception. Please help me.
Try this code:
final Thread CURRENT_THREAD = currentThread();
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog.Builder facultyChooser = new AlertDialog.Builder(ctx);
facultyChooser.setTitle("choose")
.setCancelable(false)
.setItems(arr, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
synchronized(CURRENT_THREAD) {
CURRENT_THREAD.notify();
}
}
})
.create()
.show();
}
});
}
synchronized(CURRENT_THREAD) {
try {
CURRENT_THREAD.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

delay an alertdialog

is it posible ??
I have an activity and an alertdialog on it.
but i need the activity run first and then 2 seconds later appears the alertdialog.
i have no idea how. regards
pd: iam not an english speaker
public class Pantalladeinicio extends Activity {
private final int SPLASH_DISPLAY_LENGTH = 2000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.index);
if(checkInternetConnection()==true) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent mainIntent = new Intent(Pantalladeinicio.this,
NetworkingActivity.class);
mainIntent.putExtra("MAIN", true);
startActivity(mainIntent);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
else
{
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
}
public void aceptar() {
// Toast t=Toast.makeText(this,"Bienvenido a probar el programa.", Toast.LENGTH_SHORT);
super.onDestroy();
finish();
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
//Log.v("TAG", "Internet Connection Not Present");
return false;
}
}
}
I don't understand your question, but looking at the accepted answer I suggest changing the order of your existing code:
new Handler().postDelayed(new Runnable() {
public void run() {
if(checkInternetConnection()) {
Intent mainIntent = new Intent(Pantalladeinicio.this, NetworkingActivity.class);
mainIntent.putExtra("MAIN", true);
startActivity(mainIntent);
finish();
}
else
{
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
}
}, SPLASH_DISPLAY_LENGTH);
Change your code as using Thread and runOnUiThread
//Your Code here...
else
{
myThread();
}
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
Pantalladeinicio.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(Pantalladeinicio.this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
I assume you want to wait for 2 seconds after you get into the else block.
You could do this by calling Thread.sleep(2000); before you call dialogo1.show();. However, this will make your program appear to "freeze". In order to avoid this you can create a seperate thread that sleeps and then displays the dialog.

How can I put Toast in a Runnable of a Service?

I have a service which contains a Timer and TimerTask for receiving data from Webservice in periods of time. everything works fine except Toast. I want to show a Toast to user in procSendMapMovements but i get exception. How can I use Toast in it?
class taskSendMapMovements extends TimerTask {
#Override
public void run() {
hhSendMapMovements.sendEmptyMessage(0);
}
};
// /////////////////////
final Runnable rSendMapMovements = new Runnable()
{
public void run()
{
procSendMapMovements();
}
};
final Handler hhSendMapMovements = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
performOnBackgroundThread(rSendMapMovements);
return false;
}
});
// /////////////////////
public void procSendMapMovements() {
try {
Toast.makeText(SrvDataExchange.this,
"some texts"
Toast.LENGTH_SHORT).show();
// exception here
// my process
} catch (Exception e) {
}
}
#Override
public void onStart(Intent intent, int startId) {
try {
timerSendMapMovements = new Timer();
timerSendMapMovements
.schedule(new taskSendMapMovements(),
10*60*1000,
10*60*1000);
//
} catch (NumberFormatException e) {
Toast.makeText(this, "error running service: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "error running service: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
#Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
Create a handler to display toast.
Use following:
where you want to display toast call:
//printToast.sendEmptyMessage();//If you dont want to send no paramter
//if you want to send some object to handler
/*
Message msg=printToast.obtainMessage();
msg.obj=objToSent;
printToast.sendMessage(msg);
*/
final Handler printToast= new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
Toast.makeText....;
}
});
**
Handler printToast= new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
Toast.makeText....;
}
});
your Runnable
{
run()
{
do what ever you want
printToast.sendMessage(printToast.obtainMessage());
}
}
**

How can I prevent UI hang, when my service runs a TimerTask?

I have a service which contains a Timer and TimerTask for receiving data from Webservice in periods of time. When my TimerTask runs, the UI hangs until the Webservice process complete. How can I put my task in a thread to prevent the UI hanging?
My code:
Timer timerSyncFull = new Timer();
class taskSyncFull extends TimerTask {
#Override
public void run() {
hSyncFull.sendEmptyMessage(0);
}
};
final Handler hSyncFull = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
procSyncFull();
return false;
}
});
public void procSyncFull() {
try {
// My webservice process
} catch (Exception e) {
}
}
#Override
public void onStart(Intent intent, int startId) {
timerSyncFull = new Timer();
timerSyncFull.schedule(new taskSyncFull(), 5*60*1000,
5*60*1000);
}
Use AsyncTasks or attach your Handler to another Looper thread.
I used the following code and my problem solved:
class taskSendMapMovements extends TimerTask {
#Override
public void run() {
hhSendMapMovements.sendEmptyMessage(0);
}
};
// /////////////////////
final Runnable rSendMapMovements = new Runnable()
{
public void run()
{
procSendMapMovements();
}
};
final Handler hhSendMapMovements = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
performOnBackgroundThread(rSendMapMovements);
return false;
}
});
// /////////////////////
public void procSendMapMovements() {
try {
showToast("some text");
//My Main Process
} catch (Exception e) {
}
}
#Override
public void onStart(Intent intent, int startId) {
try {
timerSendMapMovements = new Timer();
timerSendMapMovements
.schedule(new taskSendMapMovements(),
10*60*1000,
10*60*1000);
//
} catch (NumberFormatException e) {
Toast.makeText(this, "error running service: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "error running service: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
final Handler hToast = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
Toast.makeText(SrvDataExchange.this,
msg.getData().getString("msg"),
Toast.LENGTH_LONG).show();
return false;
}
});
private void showToast(String strMessage) {
Message msg = new Message();
Bundle b = new Bundle();
b.putString("msg", strMessage);
msg.setData(b);
hToast.sendMessage(msg);
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
#Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
Simply invoke your procSyncFull() method in thread or asyncTask.
final Handler hSyncFull = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
Thread thread=new Thread()
{
public void run(){
procSyncFull();
}
}
return false;
}
});
private Handler webserviceCompletionHandler=new Handler()
{
#Override
public boolean handleMessage(Message msg) {
return false;
}
};
use AsyncTask carry out your execution in doInBackground() and populate it in onPostExecute()
AsyncTask Example

Categories

Resources