我正在从我的应用程序向服务器发送一些信息并等待响应。在我发送之前,我将我的textview设置为消息以显示“处理请求”,并在收到响应后显示不同的消息。
未显示此处理消息。是否因为其他操作导致UI被阻止。 怎么处理这个。由于需要显示响应,线程无法给出正确的结果。 因此涉及线程中的UI。
package com.PandG.app.android.activities;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.PandG.app.android.R;
import com.PandG.app.android.dataAccess.SettingsDBAccess;
import com.PandG.app.android.entity.Job;
import com.PandG.app.android.entity.Settings;
import com.PandG.app.android.services.JobsManager;
import com.lib.android.Utils.Utils;
import com.lib.android.activity.BaseActivity;
import com.lib.android.dataAccess.DatabaseManager;
public class JobCheckoutActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setViewContent();
}
private void setViewContent() {
Settings setting = getSettings();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.job_checkout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
//new DataProcess().execute(null);
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
private void sendDataToServer(JSONObject jobObject) {
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(Utils.getPostUrl());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("orderparameters",
jobObject.toString()));
Log.i("Job ORDER", jobObject.toString());
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
checkResponseFromServer(response);
ClearCart();
} catch (Exception e) {
Log.w("error", "connection failed");
Toast.makeText(this, "Order not placed due to connection error",
Toast.LENGTH_LONG);
e.printStackTrace();
}
}
private void ClearCart() {
JobsManager.JobsCartList.clear();
}
private void checkResponseFromServer(HttpResponse response) {
try {
if (response != null) {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
in.close();
JSONObject jsonResponse = new JSONObject(buffer.toString());
Log.i("Status", jsonResponse.getString("status"));
Log.i("Status", jsonResponse.getString("message"));
Log.i("Status", jsonResponse.getString("debug"));
TextView text1 = (TextView)findViewById(R.id.checkoutheading);
text1.setVisibility(View.VISIBLE);
TextView text = (TextView) findViewById(R.id.checkoutmessage);
if (jsonResponse.getString("status").equals("SUCC")) {
text.setText( Html.fromHtml(getString(R.string.checkout_body1)));
} else
text.setText(jsonResponse.getString("message")
+ jsonResponse.getString("debug"));
}
} catch (Exception ex) {
}
}
private JSONObject encodeData(Settings setting) {
JSONObject jobObject = new JSONObject();
try {
JSONObject jobject = new JSONObject();
jobject.put("name", setting.getName());
jobject.put("email", setting.getEmail());
jobject.put("phone", setting.getPhone());
jobject.put("school", setting.getSchool());
jobject.put("major", setting.getMajor());
jobObject.put("customer", jobject);
JSONArray jobsarray = new JSONArray();
for (Job job : JobsManager.JobsCartList) {
JSONObject jobEntry = new JSONObject();
jobEntry.put("jobtitle",job.getTitle());
jobEntry.put("qty","1");
jobsarray.put(jobEntry);
}
jobObject.put("orders", jobsarray);
} catch (JSONException ex) {
}
return jobObject;
}
private Settings getSettings() {
SettingsDBAccess settingsDBAccess = new SettingsDBAccess(
DatabaseManager.getInstance());
Settings setting = settingsDBAccess.getSetting();
if (setting==null){
startActivityForResult((new Intent(this,SettingsActivity.class)),Utils
.getDefaultRequestCode());
}
return setting;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Settings setting = new SettingsDBAccess(
DatabaseManager.getInstance()).getSetting();
if(setting!=null){
JSONObject jobObject = encodeData(setting);
sendDataToServer(jobObject);
}
}
/* private class DataProcess extends AsyncTask {
@Override
protected void onPostExecute(Object result) {
}
@Override
protected Object doInBackground(Object... arg0) {
processDataandsend();
return null;
}
private void processDataandsend() {
Settings setting = getSettings();
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
} */
}
答案 0 :(得分:1)
您不应该在UI线程上执行HTTP工作。而是使用AsyncTask
在AsyncTask中,您只能在两个位置更新UI:
@Override
protected void onPreExecute()
TextView.setText("Beginning HTTP-work..Please wait");
{
和
@Override
protected void onPostExecute(Void v) {
TextView.setText("Done..SUCCESS!");
}
使用这两个来在HTTP工作完成之前和之后更新UI。
答案 1 :(得分:0)
长时间操作必须在后台进行。在Android上实现此功能的最佳方式是使用AsyncTask,以获取更多信息:http://developer.android.com/reference/android/os/AsyncTask.html