android print "connection timeout" when timeout in loopj - android

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
}
});

Related

Sometimes Socket data not received properly in android studio

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();
}

Set timeout function with AsyncTask [Android]

In my case, I would like to get the button pressed and get process with the timeout. When button clicked then it will verify the accNo with web services, if the verification (ProgressDialog) is over 5 seconds then it will stop and display the alertDialog to notice user "Timeout".
But now I have not idea when I in testing with 1 milliseconds, in logically it will pause in alertDialog until get pressed, but now it will display the dialog in milliseconds then auto dismiss and intent to next activity. Here is my code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information3);
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title.getText().toString().equals("INFO")) {
InfoAsyncTask infoAsyncTask = new InfoAsyncTask();
try {
infoAsyncTask.execute().get(1, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Verify Timeout. Please try again.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
});
}
private class InfoAsyncTask extends AsyncTask<Void, Void, String> {
private String results;
private ProgressDialog pDialog;
private Object resultRequestSOAP;
String accNo = et_accNo.getText().toString().trim();
int timeout = 15000;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Information3.this);
pDialog.setMessage("Verifying...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Code", InfoCode);
request.addProperty("AccNo", accNo);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, timeout);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
String requestDumpString = androidHttpTransport.requestDump;
Log.d("request Dump: ", requestDumpString);
} catch (Exception e) {
e.printStackTrace();
}
try {
resultRequestSOAP = envelope.getResponse();
results = resultRequestSOAP.toString();
Log.d("Output: ", results);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
if (resultRequestSOAP == null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Connection error, please check your internet connection.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
pDialog.dismiss();
}
} else {
if (results.equals("false")) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in correct account number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_billNo.getText().toString().trim().isEmpty()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in bill number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_amountNo.getText().toString().trim().isEmpty() || Integer.parseInt(et_amountNo.getText().toString().trim()) <= 0) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in amount");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (results.equals("true")) {
Title = title.getText().toString();
String value1 = et_accNo.getText().toString().trim();
String value2 = et_billNo.getText().toString().trim();
int value3 = Integer.parseInt(et_amountNo.getText().toString().trim());
addSearchInput(value1);
addSearchInput(value2);
addSearchInput(String.valueOf(value3));
Intent intent = new Intent(Information3.this, confirmation3.class);
intent.putExtra("name", Title);
intent.putExtra("value1", value1);
intent.putExtra("value2", value2);
intent.putExtra("value3", value3);
startActivity(intent);
} else {
super.onPreExecute();
}
pDialog.dismiss();
}
}
}
get() method will block the UI thread and I guess you don't want this.
You should implement cancel mechanics in doInBackground and call AsyncTask.cancel() by timeout [like that](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long))
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
AsyncTask.cancel();
}
}, 1);
Be aware there are many gotchas with AsyncTask, check my article.

Android updating ui in thread getting null pointer exception

When user login i will get user id and i will get device id and i will check in database(server end) and if the response is SUCCESS the ui need to update. But i am getting null pointer exception. I am updating ui in thread. Whats is the issues in this.
public class MainActivity extends AppCompatActivity {
final String LOG_TAG="TESTOPENAPP";
OpenAppLock mSelectedLock;
String email,devid;
ArrayList<OpenAppLock> scanList;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
AlertDialogManager alert = new AlertDialogManager();
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
Button mScan,mConnect,mUnlock,mDisconnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = getIntent();
// Receiving the Data
// String name = i.getStringExtra("name");
email = i.getStringExtra("email");
System.out.println("user mail id" + email);
mScan=(Button)findViewById(R.id.scan);
mConnect=(Button)findViewById(R.id.connect);
mUnlock=(Button)findViewById(R.id.unlock);
mDisconnect=(Button)findViewById(R.id.disconnect);
OpenApp.initialize(this);
mScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mScan.setText("Scanning ...");
OpenApp.scanForLocks(new ScanFinishedCallback() {
#Override
public void onScanFinished(ArrayList<OpenAppLock> scanList) {
Log.d(LOG_TAG, "OnScanFinishedCallback");
for (int i = 0; i < scanList.size(); i++) {
Log.d(LOG_TAG, "Available Lock " + i + " - " + scanList.get(i).getLockName());
devid = scanList.get(i).getLockName();
}
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
});
mConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mConnect.setText("Connecting ...");
mSelectedLock.connect(new ConnectionCallback() {
#Override
public void onFinishedTrying(boolean success) {
if(success){
mConnect.setVisibility(View.GONE);
mUnlock.setVisibility(View.VISIBLE);
//mDisconnect.setVisibility(View.VISIBLE);
}else{
mConnect.setText("Connect");
Toast.makeText(MainActivity.this, "Unable to connect to lock.", Toast.LENGTH_LONG).show();
}
}
});
}
});
mUnlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//It should be already ensured that this mSelectedLock is something user is authorized to access
if(mSelectedLock.unlock("RANDOM")){
mUnlock.setVisibility(View.INVISIBLE);
mUnlock.postDelayed(new Runnable() {
public void run() {
mUnlock.setVisibility(View.VISIBLE);
mUnlock.performClick();
Toast.makeText(getApplicationContext(),"Button Clicked",Toast.LENGTH_SHORT).show();
}
}, 6000);
}else{
Toast.makeText(MainActivity.this, "Unable to unlock.", Toast.LENGTH_LONG).show();
}
}
});
}
void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.25.107:8080/ActCFWeb/login"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("email", email)); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("pass", devid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
System.out.println("Response : " + response);
}
});
if (response.contains("success")) {
runOnUiThread(new Runnable() {
public void run() {
if (scanList.size() > 0) {
Toast.makeText(MainActivity.this, "Scanning finished. Lock Found.", Toast.LENGTH_LONG).show();
mScan.setVisibility(View.GONE);
mConnect.setVisibility(View.VISIBLE);
mSelectedLock = scanList.get(0);
dialog.dismiss();
} else {
mScan.setText("Scan");
Toast.makeText(MainActivity.this, "No Lock Found while scanning. Please scan again.", Toast.LENGTH_LONG).show();
}
}
});
}
else {
showAlert();
}
} catch (Exception e) {
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert() {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
protected void onStop() {
OpenApp.destroy();
if(mSelectedLock!=null)
mSelectedLock.destroy();
super.onStop();
}
Hey I found your solution.
I check your code and found that when your response is null and you check about response.contains("success"), you will get NullPointerException.
Just add one If condition more.
Check code below.
if(response != null){
if (response.contains("success")) {
runOnUiThread(new Runnable() {
public void run() {
if (scanList.size() > 0)
{
try
{
Toast.makeText(MainActivity.this, "Scanning finished. Lock Found.", Toast.LENGTH_LONG).show();
mScan.setVisibility(View.GONE);
mConnect.setVisibility(View.VISIBLE);
mSelectedLock = scanList.get(0);
}
catch (NullPointerException e) {
e.printStackTrace();
}
} else {
mScan.setText("Scan");
Toast.makeText(MainActivity.this, "No Lock Found while scanning. Please scan again.", Toast.LENGTH_LONG).show();
}
}
});
}
else {
showAlert();
}
}
I just add if(response != null) for check response is null or not.
if (response.contains("success")) {
runOnUiThread(new Runnable() {
public void run() {
if (scanList.size() > 0)
{
try
{
Toast.makeText(MainActivity.this, "Scanning finished. Lock Found.", Toast.LENGTH_LONG).show();
mScan.setVisibility(View.GONE);
mConnect.setVisibility(View.VISIBLE);
mSelectedLock = scanList.get(0);
}
catch (NullPointerException e) {
e.printStackTrace();
}
} else {
mScan.setText("Scan");
Toast.makeText(MainActivity.this, "No Lock Found while scanning. Please scan again.", Toast.LENGTH_LONG).show();
}
}
});
}
else {
showAlert();
}

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();
}
}

progressDialog didn't show with several views in one activity

I created 3 views in one activity depending on the process of the workflow.
i.e. viewA->viewB->viewC, then on viewC, when I do HTTP-POST(using AsyncTask), show progress dialog.
I tried 2 ways to show progress dialog:
using runOnUiThread() to show progressDialog, it didn't show.
write show progressDialog code in AsyncTask. Make progress dialog show in onPreExecute() and dismiss in onPostExecute(), it shows after doinbackground task, and onPostExecute() didn't execute as well.
Anyone can help?
Thanks
sam
Here is the main activity code:
public void setA(){
setContentView(R.layout.a_fm);
Button aNextBtn=(Button)findViewById(R.id.aNextBtn);
aNextBtn.setOnClickListener(this);
}
public void setB(){
setContentView(R.layout.b_fm);
Button bNextBtn=(Button)findViewById(R.id.bNextBtn);
bNextBtn.setOnClickListener(this);
}
public void setC(){
setContentView(R.layout.c_fm);
Button cNextBtn=(Button)findViewById(R.id.cNextBtn);
cNextBtn.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.aNextBtn:
setB();
break;
case R.id.bNextBtn:
setB();
break;
case R.id.cNextBtn:
postmsg();
break;
}
}
public void postmsg(final Info info)
{
postDialog=new ProgressDialog(AssistFm.this);
postDialog.setMessage(getString(R.string.alert_sendmsg_sending));
postDialog.show();
this.runOnUiThread(new Runnable() {#Override
public void run() {
// TODO Auto-generated method stub
send_online=sendlogtowebservice(info);
SEND_COUNT++;
if (send_online)
{
postDialog.dismiss();
AlertDialog.Builder builder = new Builder(A_activity.this);
builder.setMessage(getString(R.string.alert_sendmsg_success));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setA();
SEND_COUNT=0;
}
});
builder.create().show();
}
else
{
postDialog.dismiss();
if (SEND_COUNT<SEND_COUNT_MAX)
{
AlertDialog.Builder builder = new Builder(A_activity.this);
builder.setMessage(getString(R.string.alert_sendmsg_retry));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
postmsg(info);
SEND_COUNT++;
}
});
builder.create().show();
}
else
{
AlertDialog.Builder builder = new Builder(AssistFm.this);
builder.setMessage(getString(R.string.alert_sendmsg_error));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setA();
}
});
builder.create().show();
}
}
}
});
}
private boolean sendlogtowebservice(Info info) {
boolean isTrue = false;
int result_code = 0;
Object []param = new Object[3];
HttpResponse response = null;
String result_str;
try {
String sURL=url;
HttpClient client = new DefaultHttpClient();
ArrayList<BasicNameValuePair> paierList = new ArrayList<BasicNameValuePair>();
paierList.add(new BasicNameValuePair("person_firstname", info.person_firstname));
paierList.add(new BasicNameValuePair("person_lastname", info.person_lastname));
paierList.add(new BasicNameValuePair("person_mobile", info.person_mobile));
param[0] = sURL;
param[1] = paierList;
param[2] = client;
AsyncTask<Object, Object, HttpResponse> res = new HttpReqTask().execute(param);
response = (HttpResponse) res.get();
result_code=response.getStatusLine().getStatusCode();
result_str = EntityUtils.toString(response.getEntity());
if ( result_str.equals("00"))
{
isTrue = true;
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e)
{
Log.e("HttpAPI.callHttpPost()", "Error", e);
}
return isTrue;
};
Here is the HTTP-POST AsyncTask code:
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.HTTP;
import android.os.AsyncTask;
public class HttpReqTask extends AsyncTask<Object, Object, HttpResponse>{
#Override
protected HttpResponse doInBackground(Object... params){
String url = (String)params[0];
ArrayList<NameValuePair> paierList = (ArrayList<NameValuePair>)params[1];
HttpClient httpclient = (HttpClient)params[2];
HttpPost request = new HttpPost(url);
HttpResponse response = null;
try {
request.setEntity(new UrlEncodedFormEntity(paierList, HTTP.UTF_8));
response = httpclient.execute(request);
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
}
No one know how this happened?
I changed the AsyncTask to below, the progress dialog just show a flush away when it is trying to dismiss the progress dialog.
public class HttpReqTask extends AsyncTask<Object, Object, HttpResponse>{
private Context mCtx;
private ProgressDialog progressDialog;
public HttpReqTask(Context context){
myLog.i("HttpReqTask constructor, before show dialog!");
progressDialog = new ProgressDialog(mCtx);
progressDialog.setMessage("Your progress dialog message...");
progressDialog.show();
myLog.i("HttpReqTask constructor finish, start show dialog!");
}
#Override
protected HttpResponse doInBackground(Object... params){
myLog.i("do in background execute");
String url = (String)params[0];
ArrayList<NameValuePair> paierList = (ArrayList<NameValuePair>)params[1];
HttpClient httpclient = (HttpClient)params[2];
String s=null;
HttpPost request = new HttpPost(url);
HttpResponse response = null;
try {
request.setEntity(new UrlEncodedFormEntity(paierList, HTTP.UTF_8));
response = httpclient.execute(request);
//add for longer process time.
for (int i=0;i<10000000;i++)
{
s="a";
}
} catch (Exception e) {
throw new RuntimeException(e);
}
myLog.i("finish in background execute");
return response;
}
#Override
protected void onPostExecute(HttpResponse result) {
myLog.i("HttpReqTask onPostExecute(), before dismiss dialog!");
if (progressDialog!=null) progressDialog.dismiss();
myLog.i("HttpReqTask onPostExecute(), after dismiss dialog!");
}
}
It seems no one knows the answer...
Under my research, I can make the progessDialog shown by creating a new thread, however the AlertDialog in the new thread, can not be shown now...
public void postmsg(final OnlineHistoryInfo info)
{
dialog=new ProgressDialog(mActivity.this);
dialog.setMessage(getString(R.string.alert_sendmsg_sending));
dialog.setCancelable(false);
dialog.show();
myLog.i("dialog show!");
new Thread(){
#Override
public void run()
{
try
{
myLog.i("new thread: run!");
// TODO Auto-generated method stub
send=sendlogtowebservice(info);
//send_online=true;
SEND_COUNT++;
}
finally
{
dialog.dismiss();
if (send)
{
myLog.i("send:true!");
new DataRule(AssistFm.this).saveOnlineHistory(info);
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_success));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setA();
SEND_COUNT=0;
}
});
builder.create().show();
}
else
{
myLog.i("send:false!");
if (SEND_COUNT<SEND_COUNT_MAX)
{
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_retry));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
postmsg(info);
SEND_COUNT++;
}
});
builder.create().show();
}
else
{
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_error));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setA();
}
});
builder.create().show();
}
}
}
}
}.start();
}//postmsg() finish

Categories

Resources