When the user clik on Register Button, a Custom Dialog box appear and the user move to the menu. But in my case, the Costum Dialog appear just for one second and then the user pass to the next layout.
How to set a time for the Custom Dialog please ?
Here my code :
buttonRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new Thread(new Runnable() {
#Override
public void run() {
final String name = inputName.getText().toString();
final String mail = inputEmail.getText().toString();
final String password = inputPassword.getText()
.toString();
PatientFunctions patientFunction = new PatientFunctions();
json = patientFunction.registerPatient(name, mail,
password);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
Intent main = new Intent(
getApplicationContext(), Main.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
finish();
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
CustomizeDialog customizeDialog = new CustomizeDialog(RegisterPatient.this);
customizeDialog.show();
Handler handler = null;
handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
customizeDialog.cancel();
customizeDialog.dismiss();
}
}, 3000);
}
});
There are many good options including AlarmManager, Timer & TimerTask
You can use a handler too like so:
Handler handler = null;
handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
customdialog.cancel();
customdialog.dismiss();
}
}, 500);
the best way to do these kind of process is to use AsyncTask class
and override onPreExecute and doInBackground and onPostExecute
see the official guide
implement the doInBackground() callback method, which runs in a pool of background threads. To update your UI, you should implement onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread, so you can safely update your UI. You can then run the task by calling execute() from the UI thread
private class Registration extends AsyncTask<String, Void, String>{
CustomizeDialog customizeDialog;
#Override
protected void onPreExecute() {
// show ur dialog
customizeDialog = new CustomizeDialog(RegisterPatient.this);
customizeDialog.show();
}
#Override
protected String doInBackground(String... params) {
final String name = params[0];
final String email = params[1];
final String password = params[2];
PatientFunctions patientFunction = new PatientFunctions();
json = patientFunction.registerPatient(name, mail,
password);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
return res;
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
if (Integer.parseInt(res) == 1) {
if(customizeDialog != null)
customizeDialog.dismiss();
Intent main = new Intent(
getApplicationContext(), Main.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//move to the next activity
startActivity(main);
finish();
}
}
}
Edit
and then execute it what ever you want
buttonRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String name = inputName.getText().toString();
final String mail = inputEmail.getText().toString();
final String password = inputPassword.getText()
.toString();
new Registration().execute(name,mail,password);
}
});
Related
I'm work on crate server and android client
but thread doesn't interrupted by android client
My android Client has request for the RoomList from server
and Server receive, Client Accept
and fill in my ListView used the Adapter
here's problem if Click backButton,
than RoomListAcitivity was close and thread was stop
but thread dosen't stop just alive in my app
first Enter has work on sucessfully
but Press BackButton on and re-Enter this Activity
MyApp just White, No Action
how can i stop this thread?
(and sorry for my English skill...)
i tried .interrupt() method , and handler.removeMessages(0)
but failed thread keep alive
upload this full java code just in case...
ListView roomList;
RoomAdapter roomAdapter;
Socketservice ss;
String msg,rtitle;
String msgs[];
String list[];
Thread listthread,EnterRoomThread,removeV;
boolean staterun = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_room);
roomList = findViewById(R.id.roomList);
roomAdapter = new RoomAdapter();
listthread = new Thread() {
public void run(){
ss.out.println("163|");
ss.out.println("100|");
try {
while (staterun == true) {
msg = ss.in.readLine();
handler.post(new Runnable() {
public void run() {
msgs = msg.split("\\|");
String protocol = msgs[0];
switch (protocol) {
case "163":
list = msgs[1].split(",");
for (int i = 0; i < list.length; i++) {
String list1[] = list[i].split("-");
String listT = list1[0];
int listC = Integer.parseInt(list1[1]);
int listI = Integer.parseInt(list1[2]);
roomAdapter.CreateRoom(listI, listT, listC);
}
roomList.setAdapter(roomAdapter);
msg = "";
msgs = null;
break;
case "200":
Intent i = new Intent(getApplicationContext(), GameWaitingActivity.class);
i.putExtra("tname", rtitle);
staterun = !staterun;
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
startActivity(i);
finish();
break;
case "201":
Toast.makeText(getApplicationContext(), "방이 꽉 찼습니다.", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
} catch (IOException e) {
}
}
};
listthread.start();
roomList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Room item = (Room) roomList.getItemAtPosition(position);
rtitle=item.getTitle();
EnterRoomThread = new Thread() {
public void run() {
ss.out.println("200|" + rtitle);
EnterRoomThread.interrupt();
}
};
EnterRoomThread.start();
}
});
}
Handler handler = new Handler();
#Override
public void onBackPressed() {
removeV = new Thread() {
public void run(){
ss.out.println("101|");
removeV.interrupt();
}
};
removeV.start();
handler.removeMessages(0);
staterun = false;
listthread.interrupt();
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
finish();
}
}
Go ahead with this, write this inside run() method
//use this boolean value to keep track.
boolean shouldRunFlag = true;
while (shouldRunFlag) {
try {
Thread.sleep(10);
//Do your work............
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Interrupted Exception caught");
// change the flag, so that while loop can be broken.
shouldRunFlag = false;
Log.v(TAG, "run: breaking the loop");
break;
}
}
and this is how you interrupt and clean the thread
private void interrupt(Thread currentThread) {
Log.i(TAG, "interrupt");
if (currentThread != null) {
Thread dummyThread = currentThread;
dummyThread.interrupt();
currentThread = null;
}
}
I'm developing DES decryption in Android platform.
this is my main
package com.example.crack;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class Main extends Activity {
public final static String EXTRA_MESSAGE = "com.example.crack.MESSAGE";
public final static String EXTRA_PLAINTEXT = "com.example.crack.PLAINTEXT";
public final static int ENCRYPTION_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#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;
}
public void sendMessage(View view) {
Intent intent = new Intent(this, encryption.class);
EditText editText = (EditText) findViewById(R.id.input_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(intent, ENCRYPTION_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == ENCRYPTION_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
String result = data.getStringExtra(encryption.EXTRA_ENCRYPTION_RETURN);
Intent intent = new Intent(this, DisplayMessage.class);
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);
}
}
}
}
and this is the partial of my encrpytion
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.encryption);
Intent intent = getIntent();
message = intent.getStringExtra(Main.EXTRA_MESSAGE);
//Dictionary
is = getResources().openRawResource(R.raw.english);
in = new BufferedReader(new InputStreamReader(is));
readDic();
String result = "";
try {
result = decryptBruteForce();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent returnIntent = new Intent();
returnIntent.putExtra(EXTRA_ENCRYPTION_RETURN,result);
setResult(RESULT_OK,returnIntent);
finish();
}
when i click on the button, it calls the sendMessage function, while it is running the decryption the screen just black out until it finish running.
I had try using progress bar follow this guide, but not working, I need a button that can stop the process while running.
And is it possible to set a log on view, which show what the function is doing right now? like what is shown in the IDE log? Example, showing what key is the decryption trying right now.
Or maybe just a progress bar or please wait will do too.
I tried to change the sendMessage to this, yet it still black out and crash
public void sendMessage(View view) {
final Intent intent = new Intent(this, encryption.class);
view.setEnabled(false);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
EditText editText = (EditText) findViewById(R.id.input_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(intent, ENCRYPTION_REQUEST);
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
b.setEnabled(true);
}
}
};
task.execute((Void[])null);
}
if I put sleep to 50000, it did not crash, but still it black out.
You can do it with a Thread and a Handler. While you try each combination, you update the progress bar.
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle savedInstanceState)
{
.... // Other initializations
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
mProgress.setMax(dictionaryLength);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
for (int i=0 ; i<dictionaryLength ; i++)
{
mProgressStatus = decryptBruteForce(i);
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
}
However i recommend you to use AsyncTask to do background operations while you need to update the UI to show the progress or info about whats going on.
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html
Its a good habit to add a cancel control in your loop, so you can finish it from outside of the AsyncTask (for example another button in you UI).
private class DecryptTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... words)
{
long wordsDecrypted = 0;
for (int i = 0; i < words.length ; i++) {
wordsDecrypted += decryptBruteForce(i);
publishProgress(i);
// Escape early if cancel() is called
if (isCancelled())
break;
}
return wordsDecrypted;
}
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Decrypted " + result + " words");
}
}
And you can cancel the AsyncTask from outside with the cancel method:
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html#cancel(boolean)
PD: Codes are not tested, just examples to show how it works
I am unable to understand why my background thread is not able to change the content of textView(txtName) after screen orientation is changed.
If I make txtname as static it works, but without static it does not work. It just has its initial value not getting updated by the background thread.
private TextView txtName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
txtName = (TextView) findViewById(R.id.txtName);
TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
Button btnClose = (Button) findViewById(R.id.btnClose);
Button btnBack = (Button) findViewById(R.id.btnBack);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String email = i.getStringExtra("email");
// String data = i.getStringExtra("data");
// Displaying Received data
txtName.setText("HI");
txtEmail.setText(email);
// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
Thread background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 30; i++) {
try {
Thread.sleep(1000);
Message msg = new Message();
Bundle b = new Bundle();
b.putString("My Key", "My Value: " + String.valueOf(i));
msg.setData(b);
// send message to the handler with the current message handler
handler.sendMessage(msg);
Log.e("Error", "IN THREAD");
} catch (Exception e) {
Log.d("Error", e.toString());
}
}
}
});
background.start();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = getIntent();
returnIntent.putExtra("returnResult","i want to back page.");
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
// get the bundle and extract data by key
Bundle b = msg.getData();
String key = b.getString("My Key");
txtName.setText( "Item " + key);
txtName.setVisibility(View.VISIBLE);
Log.e("TEST MESSAGE", txtName.getText().toString());
}
};
Try runOnUiThread:
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
Handler handler = new Handler() {
public void handleMessage(Message msg) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// get the bundle and extract data by key
Bundle b = msg.getData();
String key = b.getString("My Key");
txtName.setText( "Item " + key);
txtName.setVisibility(View.VISIBLE);
Log.e("TEST MESSAGE", txtName.getText().toString());
}
});
}
};
}
Create your OnClickListener as a fixed Class and then apply it as:
MyListener myListener = new MyListener();
btnClose.setOnClickListener(myListener);
In this way the txtName variable musn't be set as final
Your UI can only be updated by the UI thread. Try something like this to ask your UI thread to update the interface as soon as possible. This way i think you can avoid using a handler.
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
Thread background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 30; i++) {
try {
Thread.sleep(1000);
final String val = "My Value: " + String.valueOf(i);
// ask UI thread to make the changes as soon as possible
txtName.post(new Runnable(){
public void run(){
txtName.setText( "Item " + val);
txtName.setVisibility(View.VISIBLE);
});
} catch (Exception e) {
Log.d("Error", e.toString());
}
}
}
});
background.start();
}
});
This is my scenario. A class A implements Runnable. When user click a button, there will show a progress dialog and call the method searchMap() to search an address. The dialog dismisses after 10 seconds. I really misunderstand how to execute the run() method. this is my creepy code.
public class AddLocationMapActivity extends MapActivity implements Runnable {
private ProgressDialog progressDialog;
private MyHandler myHandler;
private Message msg;
#Override
public void run() {
mapCurrentAddress();
}
public void mapLocation(View v) // click event here{
progress();
Thread thread = new Thread(this);
thread.start();
}
private class MyHandler extends Handler{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
case NOT_OK_MESSAGE: // Fail
alert(AddLocationMapActivity.this, message());
progressDialog.dismiss();
break;
case OK_MESSAGE: // Success
found(); // Point to the appropiate address
progressDialog.dismiss();
break;
case EXPTION_MESSAGE: // Exception
alert(AddLocationMapActivity.this, "Unexpected error");
progressDialog.dismiss();
break;
}
}
}
protected void mapCurrentAddress() {
String addressString = addressText.getText().toString();
Geocoder g = new Geocoder(this);
List<Address> addresses;
myHandler = new MyHandler();
msg = myHandler.obtainMessage();
try {
addresses = g.getFromLocationName(addressString, 1);
if (addresses.size() > 0) {
//address = addresses.get(0);
msg.what = OK_MESSAGE;
myHandler.sendEmptyMessage(OK_MESSAGE);
} else {
// show the user a note that we failed to get an address
myHandler.sendEmptyMessage(NOT_OK_MESSAGE);
}
} catch (IOException e) {
// show the user a note that we failed to get an address
//e.printStackTrace();
myHandler.sendEmptyMessage(EXPTION_MESSAGE);
}
}
private void progress() {
progressDialog = ProgressDialog.show(this,
"Checking", "Contacting Map Server");
Thread progressThread = new Thread();
progressThread.start();
}
}
When click event occurs, the program fails with exception Uncaught Handler
here's a little bit of my threading code that doesn't give away too much...
progress = ProgressDialog.show(this, "", "Loading...", true);
new Thread(new Runnable() {
#Override
public void run()
{
// get some network content
Chooser.this.runOnUiThread(new Runnable() {
#Override
public void run()
{
progress.dismiss();
// update the UI
}
});
}
}).start();
Here is my code & probelm.
static Throwable t= null;
static String responseFromServer = "";
static Activity a ;
static Handler mHandler = new Handler();
public static String sendToServer(final Activity act, final String data)
{
progDailog = ProgressDialog.show(act, "", " Please wait...", true);
progDailog.setCancelable(true); //BUT this not displaying
Thread th = new Thread()
{
public void run(){
try{
// .........code ... SENDING data to server
responseFromServer = httpclient.execute(httppost, new BasicResponseHandler()).trim();
mHandler.post(showResponse);
}
catch (Exception e)
{
t = e;
e.printStackTrace();
progDailog.dismiss();
mHandler.post(exception);
}
}
};
th.start();
th.join();
return responseFromServer;
}
private static Runnable showResponse = new Runnable()
{
public void run(){
Toast.makeText( a, responseFromServer, Toast.LENGTH_SHORT).show();
progDailog.dismiss();
}
};
private static Runnable exception = new Runnable()
{
public void run(){
Toast.makeText( a, t + " ", Toast.LENGTH_SHORT).show();
progDailog.dismiss();
}
};
Why progressdialog is not getting displayed ?
And Where is the correct place to display it ?
progressDialog.show() can be executed only from the UI thread.
just do the following:
instead of:
progDailog = ProgressDialog.show(act, "", " Please wait...", true);
use this code:
a.runOnUiThread(new Runnable() {
#Override
public void run() {
progDailog = ProgressDialog.show(act, "", " Please wait...", true);
}
});
same thing with the dismiss() method
You should make use of AsyncTask other than using Threads. The UI can be handled only from the UI thread. You can not handle the UI thread from the other threads.
For more information on this please read my blog at below link
http://pavandroid.blogspot.in/2010/09/how-to-create-calendar-in-android.html