我正在使用连接到服务器的应用程序..我想在应用程序中连接服务器时出现进度条。我也使用了asyncTask.BUt然后在我的应用程序进度条中没有出现,屏幕变黑当连接到server.Plz帮助我...我创建了三个AsyncTask ..
public class LocationActivity extends ListActivity {
TextView txtName;
TextView txtState;
TextView distance;
TextView txtparamname;
TextView txtparamvalue;
TextView output;
TextView txtdate;
TextView txtproc_date;
TextView looking;
String LAT;
String LONGITUDE;
ImageButton forecast;
ImageView image;
JSONArray weatherinfo = null;
ActionBar actionBar;
MenuItem refreshMenuItem;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> weatherlist;
// URL for getting weather forecast details
private static final String url_Weather_details = "";
private static final String url_Weather_details1 = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isNetworkAvailable()) {
new GetWeatherDetails0().execute();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
// Setting Dialog Title
alertDialog.setTitle("Network Connection Error");
// Setting Dialog Message
alertDialog.setMessage("Your 2G/3G/Wifi is not working");
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),
AndroidGPSTrackingActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
alertDialog.show();
// Toast.makeText(this, "Network unavailable",
// Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
class GetWeatherDetails0 extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LocationActivity.this);
pDialog.setMessage("Loading Your weather details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting weather details in background thread
* */
@SuppressLint("SimpleDateFormat")
protected String doInBackground(String... params1) {
int success = 0;
int success2 = 0;
// getting LAT/LONG details from intent
Intent i = getIntent();
// getting LAT/LONG from intent
LAT = i.getStringExtra(TAG_LAT);
LONGITUDE = i.getStringExtra(TAG_LONG);
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("get LATITUDE ====", LAT);
Log.d("get LONGITUDE ====", LONGITUDE);
params.add(new BasicNameValuePair("LAT", LAT));
params.add(new BasicNameValuePair("LONGITUDE", LONGITUDE));
JSONObject json = jsonParser.makeHttpRequest(url_Weather_details,
"GET", params);
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (success == 3) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
LocationActivity.this);
// Setting Dialog Title
// alertDialog.setTitle("Network Connection Error");
// Setting Dialog Message
alertDialog
.setMessage("Server encountered some error.Sorry for inconvenience.Please try again later");
// On pressing Settings button
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent i = new Intent(getApplicationContext(),
AndroidGPSTrackingActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
alertDialog.show();
} else if (success == 2) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
LocationActivity.this);
// Setting Dialog Title
// alertDialog.setTitle("Network Connection Error");
// Setting Dialog Message
alertDialog.setMessage("Sorry,Forecast is not available");
// On pressing Settings button
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent i = new Intent(getApplicationContext(),
AndroidGPSTrackingActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
alertDialog.show();
}
else {
// success=0;
JSONObject json2 = jsonParser.makeHttpRequest(
url_Weather_details1, "GET", params);
try {
// Log.d("1","yty");
success2 = json2.getInt(TAG_SUCCESS);
// Log.d("q",Integer.toString (success2));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (success2 == 3) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
LocationActivity.this);
// Setting Dialog Title
// alertDialog.setTitle("Network Connection Error");
// Setting Dialog Message
alertDialog
.setMessage("Server encountered some error.Sorry for inconvenience.Please try again later");
// On pressing Settings button
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent i = new Intent(
getApplicationContext(),
AndroidGPSTrackingActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
alertDialog.show();
} else if (success2 == 2) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
LocationActivity.this);
// Setting Dialog Title
// alertDialog.setTitle("Network Connection Error");
// Setting Dialog Message
alertDialog.setMessage("Sorry,Forecast is not available");
// On pressing Settings button
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent i = new Intent(
getApplicationContext(),
AndroidGPSTrackingActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
alertDialog.show();
} else
{
setContentView(R.layout.activity_location);
weatherlist = new ArrayList<HashMap<String, String>>();
// Getting complete weather details in background thread
new GetWeatherDetails().execute();
new GetWeatherDetails1().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// getting values from selected ListItem
String FC_DATE = ((TextView) view
.findViewById(R.id.fc_date)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ForecastActivity.class);
// sending pid to next activity
in.putExtra(TAG_FC_DATE, FC_DATE);
in.putExtra(TAG_LAT, LAT);
in.putExtra(TAG_LONG, LONGITUDE);
// starting new activity and expecting some response
// back
startActivityForResult(in, 100);
}
});
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Get complete weather details
* */
class GetWeatherDetails extends AsyncTask<String, String, String> {
@SuppressLint("SimpleDateFormat")
protected String doInBackground(String... params1) {
// Check for success tag
int success;
String OutputData = "";
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("get LATITUDE ====", LAT);
Log.d("get LONGITUDE ====", LONGITUDE);
params.add(new BasicNameValuePair("LAT", LAT));
params.add(new BasicNameValuePair("LONGITUDE", LONGITUDE));
Log.d("params", params.toString());
// getting weather details by making HTTP request
// Note that weather details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_Weather_details, "GET", params);
// check your log for json response
Log.d("Weather Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received weather details
JSONArray stationObj = json.getJSONArray(TAG_WEATHER); // JSON
// Array
int lengthJsonArr = stationObj.length();
// get weather info object from JSON Array
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject station = stationObj.getJSONObject(i);
// Log.d("FC_DATE",station.getString("FC_DATE"));
// JSONObject station1 = stationObj.getJSONObject(1);
// JSONObject station2 = stationObj.getJSONObject(2);
// Edit Text
txtName = (TextView) findViewById(R.id.textView2);
txtState = (TextView) findViewById(R.id.textView4);
txtdate = (TextView) findViewById(R.id.textView5);
// txtproc_date=(TextView)findViewById(R.id.textView1);
distance = (TextView) findViewById(R.id.textView3);
looking = (TextView) findViewById(R.id.textView6);
OutputData += " \n" + station.getString(TAG_PARAM_NAME)
+ " : " + station.getString(TAG_PARAM_VALUE)
+ " " + station.getString(TAG_PARAM_UNIT)
+ "\n";
// txtdate= (TextView)findViewById(R.id.textView1);
// txtparamname=(TextView)findViewById(R.id.textView2);
// txtparamvalue=(TextView)findViewById(R.id.textView7);
// table1=(TableRow)findViewById(R.id.tableRow1);
txtName.setText("Forecast location: "
+ station.getString(TAG_STATION));
txtName.setTextSize(size);
txtName.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
txtState.setText("State: "
+ station.getString(TAG_STATE));
txtState.setTextSize(size);
txtState.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
String distance1 = station.getString(TAG_DISTANCE);
looking.setText("Looking Ahead");
looking.setTextSize(size);
looking.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
// DecimalFormat df2 = new DecimalFormat("0.##");
// String distance2=df2.format(distance1);
double distance2 = Double.parseDouble(distance1);
}
tl = (TableLayout) findViewById(R.id.maintable);
t2 = (TableLayout) findViewById(R.id.maintable1);
addHeaders();
addData();
addHeaders1();
addData1();
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
class GetWeatherDetails1 extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
/**
* getting All products from url
* */
@SuppressLint("SimpleDateFormat")
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("get LATITUDE ====", LAT);
Log.d("get LONGITUDE ====", LONGITUDE);
params.add(new BasicNameValuePair("LAT", LAT));
params.add(new BasicNameValuePair("LONGITUDE", LONGITUDE));
Log.d("params", params.toString());
JSONObject json = jsonParser.makeHttpRequest(url_Weather_details1,
"GET", params);
// Check your log cat for JSON response
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
weatherinfo = json.getJSONArray(TAG_WEATHER);
// looping through All Products
for (int i = 0; i < weatherinfo.length(); i++) {
JSONObject c = weatherinfo.getJSONObject(i);
// String id = c.getString(TAG_PID);
String FC_DATE = c.getString(TAG_FC_DATE);
SimpleDateFormat sf = new SimpleDateFormat(
"dd-MMM-yyyy");
SimpleDateFormat sf1 = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
String date = sf.format(sf1.parse(FC_DATE));
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_PID, id);
map.put(TAG_FC_DATE, date);
// adding HashList to ArrayList
weatherlist.add(map);
}
} /*
* else if(success==2){
*
* // weather details not found Intent i = new
* Intent(getApplicationContext(), NotFound.class); // Closing
* all previous activities
* i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i);
* } // no products found // Launch Add New product Activity
* else { { // weather details not found Intent i = new
* Intent(getApplicationContext(), Exception_report.class); //
* Closing all previous activities
* i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i);
* } }
*/
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(LocationActivity.this,
weatherlist, R.layout.list_item,
new String[] { TAG_FC_DATE }, new int[] { R.id.fc_date });
// updating list view
setListAdapter(adapter);
}
}
}
logcat的:
11-16 16:35:50.289: D/Network(24204): Network
11-16 16:35:50.289: D/Lat(24204): 23.0350297
11-16 16:35:50.289: D/LONGITUDE(24204): 72.5252883
11-16 16:35:50.459: D/ProgressBar(24204): setProgress = 0
11-16 16:35:50.459: D/ProgressBar(24204): setProgress = 0, fromUser = false
11-16 16:35:50.459: D/ProgressBar(24204): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
11-16 16:35:50.549: D/get LATITUDE ====(24204): 23.0350297
11-16 16:35:50.549: D/get LONGITUDE ====(24204): 72.5252883
11-16 16:35:50.649: D/ProgressBar(24204): updateDrawableBounds: left = 0
11-16 16:35:50.649: D/ProgressBar(24204): updateDrawableBounds: top = 0
11-16 16:35:50.649: D/ProgressBar(24204): updateDrawableBounds: right = 96
11-16 16:35:50.649: D/ProgressBar(24204): updateDrawableBounds: bottom = 96
11-16 16:36:01.609: W/dalvikvm(24204): threadid=12: thread exiting with uncaught exception (group=0x41808898)
11-16 16:36:01.659: E/AndroidRuntime(24204): FATAL EXCEPTION: AsyncTask #1
11-16 16:36:01.659: E/AndroidRuntime(24204): java.lang.RuntimeException: An error occured while executing doInBackground()
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-16 16:36:01.659: E/AndroidRuntime(24204): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-16 16:36:01.659: E/AndroidRuntime(24204): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-16 16:36:01.659: E/AndroidRuntime(24204): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-16 16:36:01.659: E/AndroidRuntime(24204): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-16 16:36:01.659: E/AndroidRuntime(24204): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-16 16:36:01.659: E/AndroidRuntime(24204): at java.lang.Thread.run(Thread.java:841)
11-16 16:36:01.659: E/AndroidRuntime(24204): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6857)
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1084)
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.view.View.requestLayout(View.java:16784)
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.view.View.requestLayout(View.java:16784)
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.view.View.requestLayout(View.java:16784)
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.view.ViewGroup.removeAllViews(ViewGroup.java:4136)
11-16 16:36:01.659: E/AndroidRuntime(24204): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:359)
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.app.Activity.setContentView(Activity.java:1956)
11-16 16:36:01.659: E/AndroidRuntime(24204): at com.example.gpstracking.LocationActivity$GetWeatherDetails0.doInBackground(LocationActivity.java:309)
11-16 16:36:01.659: E/AndroidRuntime(24204): at com.example.gpstracking.LocationActivity$GetWeatherDetails0.doInBackground(LocationActivity.java:1)
11-16 16:36:01.659: E/AndroidRuntime(24204): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-16 16:36:01.659: E/AndroidRuntime(24204): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-16 16:36:01.659: E/AndroidRuntime(24204): ... 3 more
11-16 16:36:01.949: E/WindowManager(24204): Activity com.example.gpstracking.LocationActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42414e78 V.E..... R.....ID 0,0-684,192} that was originally added here
11-16 16:36:01.949: E/WindowManager(24204): android.view.WindowLeaked: Activity com.example.gpstracking.LocationActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42414e78 V.E..... R.....ID 0,0-684,192} that was originally added here
11-16 16:36:01.949: E/WindowManager(24204): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:456)
11-16 16:36:01.949: E/WindowManager(24204): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:258)
11-16 16:36:01.949: E/WindowManager(24204): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
11-16 16:36:01.949: E/WindowManager(24204): at android.app.Dialog.show(Dialog.java:287)
11-16 16:36:01.949: E/WindowManager(24204): at com.example.gpstracking.LocationActivity$GetWeatherDetails0.onPreExecute(LocationActivity.java:177)
11-16 16:36:01.949: E/WindowManager(24204): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
11-16 16:36:01.949: E/WindowManager(24204): at android.os.AsyncTask.execute(AsyncTask.java:534)
11-16 16:36:01.949: E/WindowManager(24204): at com.example.gpstracking.LocationActivity.onCreate(LocationActivity.java:133)
11-16 16:36:01.949: E/WindowManager(24204): at android.app.Activity.performCreate(Activity.java:5372)
11-16 16:36:01.949: E/WindowManager(24204): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
11-16 16:36:01.949: E/WindowManager(24204): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
11-16 16:36:01.949: E/WindowManager(24204): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
11-16 16:36:01.949: E/WindowManager(24204): at android.app.ActivityThread.access$700(ActivityThread.java:168)
11-16 16:36:01.949: E/WindowManager(24204): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
11-16 16:36:01.949: E/WindowManager(24204): at android.os.Handler.dispatchMessage(Handler.java:99)
11-16 16:36:01.949: E/WindowManager(24204): at android.os.Looper.loop(Looper.java:176)
11-16 16:36:01.949: E/WindowManager(24204): at android.app.ActivityThread.main(ActivityThread.java:5493)
11-16 16:36:01.949: E/WindowManager(24204): at java.lang.reflect.Method.invokeNative(Native Method)
11-16 16:36:01.949: E/WindowManager(24204): at java.lang.reflect.Method.invoke(Method.java:525)
11-16 16:36:01.949: E/WindowManager(24204): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
11-16 16:36:01.949: E/WindowManager(24204): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
11-16 16:36:01.949: E/WindowManager(24204): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
从所有runOnUiThread's
中删除doInBackground's
。并且不要在doInBackground中启动其他AsyncTasks。重新思考你的设计和方法。