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();
}
}
Related
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();
}
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
}
});
Heres my code for checking the network connection of my app.I want my app run only when it is connected to a network and closes it if not. The code was running with no errors but the problem is the alertdialog show many times.
private void checkConnectivity(){
final Thread checkConnection = new Thread(new Runnable(){
#Override
public void run()
{
while (checkCon == true){
if(!isNetworkAvailable(MainActivity.this)) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setMessage("No network connection.")
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int which) {
checkCon = false;
finish();
}
}).show();
}
});
} else {
checkCon = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
});
checkConnection.start();
}
Answer by harism, thanks
private void checkConnectivity(){
final Thread checkConnection = new Thread(new Runnable(){
#Override
public void run()
{
while (checkCon == true){
if(!isNetworkAvailable(MainActivity.this)) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setMessage("No network connection.")
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int which) {
finish();
}
}).show();
checkCon = false;
}
});
} else {
checkCon = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
});
checkConnection.start();
}
Add a new method inside your current Activity or Fragment:
private boolean isNetworkAvailable(){
boolean available = false;
/** Getting the system's connectivity service */
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
/** Getting active network interface to get the network's status */
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo !=null && networkInfo.isAvailable())
available = true;
/** Returning the status of the network */
return available;
}
And here is how to use it. You can use it inside onCreate() method:
if (isNetworkAvailable() == true){ // if network is available
// do your thing here
...
}else{ // "else" means that the network is not available
// do your thing here
...
}
I want to open alert dialog box after successfully submitted data.
I am using following code but not work.
dialog = ProgressDialog.show(TanantDetails.this, "", "Please Wait...", true);
new Thread(new Runnable() {
public void run() {
String response;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences sp=getSharedPreferences("login",MODE_WORLD_READABLE);
try {
Utility utility=new Utility();
//
new_url=url+mobile_no.getText().toString();
response = utility.getResponse(utility.urlEncode(new_url));
dialog.dismiss();
if (response.equals("Success"))
{
AlertDialog alertbox = new AlertDialog.Builder(getBaseContext())
//.setIcon(R.drawable.no)
.setTitle("Submit successfully")
.setMessage("“Police will verify documents between preferred timing")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
TanantDetails.this.finish();
Intent i=new Intent(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);
}
})
.show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}).start();
}
toast show the message response success.
I am new to android
Simple Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Alert")
.setTitle("Warning");
AlertDialog alert =builder.create();
alert.show();
If you want to add ok, cancel buttons then add
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked cancel button
}
});
Try this code:
new AlertDialog.Builder(this)
.setTitle("Your title")
.setMessage("Your message")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
Your alert dialog needs to be displayed on the UI thread. The code you are running is on a separate thread. In most cases when you want to update a UI element while in a separate thread it is done by using runOnUiThread()
Please see the code below
if (response.equals("Success"))
{
runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog alertbox = new AlertDialog.Builder(getBaseContext())
//.setIcon(R.drawable.no)
.setTitle("Submit successfully")
.setMessage("“Police will verify documents between preferred timing")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
TanantDetails.this.finish();
Intent i=new Intent(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);
}
}).show();
}
});
}
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.