在Android的异步任务code的奇怪行为 [英] Strange Behaviour of Async Task code in android
问题描述
我是一个新手,Android和异步任务。
我开发上的按钮布局打开,他的设备经纬度搜索点击其中的应用程序中。
这些经纬度被发送到服务器为取回分支的细节从最接近最远。
我得到一个空指针异常无法理解的AsyncTask是如何工作的AsyncTask的执行不会被调用。下面是code
I am a newbie to android and async task. I am developing a application where in a on click of a button a layout opens and searches for his device latitude and longitude. These latitude and longitude are then sent to a server for getting back the details of branches from nearest to farthest. I am getting an Null pointer Exception cant understand how AsyncTask is working as AsyncTask Execute never gets called. Below is the code
public class FindUs extends ExpandableListActivity implements OnChildClickListener{
GeoPoint geoPoint;
public static String cities[];
LocationManager mlocManager;
double lat,lng;
LocationListener mlocListener = new MyLocationListener();
ProgressDialog progDailog = null;
RequestTask reqTask;
SimpleExpandableListAdapter expListAdapter;
public String city_details[][] = { };
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.findus_layout);
progDailog = new ProgressDialog(FindUs.this);
progDailog.setMessage("Loading...");
progDailog.show();
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
try {
reqTask = new RequestTask();
reqTask.execute( "http://192.168.1.239:8080/StrutsExample/FindUS.slt");
} catch (Exception e) {
e.printStackTrace();
}
expListAdapter =
new SimpleExpandableListAdapter(
this,
createGroupList(),// groupData describes the first-level entries
R.layout.child_row, // Layout for the first-level entries
new String[] { "cityBranch" }, // Key in the groupData maps to display
new int[] { R.id.childname }, // Data under "child" key goes into this TextView
createChildList(), // childData describes second-level entries
R.layout.child_row, // Layout for second-level entries
new String[] { "cityBranchDetails", "rgb" }, // Keys in childData maps to display
new int[] { R.id.childname, R.id.rgb } // Data under the keys above go into these TextViews
);
setListAdapter( expListAdapter );
private List createGroupList() {
ArrayList result = new ArrayList();
//getting null pointer exception when populating cities
for( int i = 0 ; i < cities.length ; ++i ) {
HashMap m = new HashMap();
m.put( "cityBranch",cities[i] );
result.add( m );
}
return (List)result;
}
private List createChildList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < city_details.length ; ++i ) {
// Second-level lists
ArrayList secList = new ArrayList();
for( int n = 0 ; n < city_details[i].length ; n += 2 ) {
HashMap child = new HashMap();
child.put( "cityBranchDetails", city_details[i][n] );
child.put( "rgb", city_details[i][n+1] );
secList.add( child );
}
result.add( secList );
}
return result;
}
//Location Listener Class
public class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc){
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
String Text = "My current location is: " + "Latitude = " + latitude + "Longitude = " + longitude;
Toast.makeText( FindUs.this,Text, Toast.LENGTH_SHORT).show();
String latLongString = "";
if (loc != null) {
latLongString = "Lat:" + latitude + "\nLong:" + longitude;
TextView myLocationText = (TextView)findViewById(R.id.FindUsTextView);
myLocationText.setText("Your Current Position is:\n" + latLongString);
progDailog.dismiss();
}
Toast.makeText( FindUs.this, Text, Toast.LENGTH_SHORT).show();
mlocManager.removeUpdates(mlocListener);
}
@Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Disabled, Please Enable the GPS", Toast.LENGTH_SHORT ).show();
}
@Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
// now the AsyncTask class
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
HttpPost requestDetails = new HttpPost(uri[0]);
SharedPreferences findUsSetDetailsSharedPreference = getSharedPreferences("gpsdetails",MODE_PRIVATE);
String latitude = findUsSetDetailsSharedPreference.getString("latitude", "");
String longitude = findUsSetDetailsSharedPreference.getString("longitude", "");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("latitude", latitude));
postParameters.add(new BasicNameValuePair("longitude", longitude));
requestDetails.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
response = httpclient.execute(requestDetails);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
System.out.println("------------------------->"+responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
String []latandLong = responseString.split("\t");
/********************************************************
below we can see I am populating cities String array variables of FindUs
***********************************************************************************/
FindUs.cities = new String[latandLong.length];
for(int i=0 ; i<latandLong.length;i++)
{
FindUs.cities[i] = latandLong[i];
}
System.out.println(cities.length);
System.out.println(cities);
return responseString;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mlocManager != null) {
mlocManager.removeUpdates(mlocListener);
mlocManager = null;
}
}
@Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
但它从来没有得到reqTask.execute();执行,不会填满该变量。
期待你的回复。
谢谢。
But it never gets reqTask.execute(); executed and doesn't fill up the variable. Looking forward to your reply. thanks.
下面是堆栈跟踪
01-04 19:29:42.759: E/AndroidRuntime(305): FATAL EXCEPTION: main
01-04 19:29:42.759: E/AndroidRuntime(305): java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.stylingandroid.IntelligentLayout/com.stylingandroid.IntelligentLayout.FindUs}: java.lang.NullPointerException
01-04 19:29:42.759: E/AndroidRuntime(305): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-04 19:29:42.759: E/AndroidRuntime(305): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-04 19:29:42.759: E/AndroidRuntime(305): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-04 19:29:42.759: E/AndroidRuntime(305): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-04 19:29:42.759: E/AndroidRuntime(305): at android.os.Handler.dispatchMessage(Handler.java:99)
01-04 19:29:42.759: E/AndroidRuntime(305): at android.os.Looper.loop(Looper.java:123)
01-04 19:29:42.759: E/AndroidRuntime(305): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-04 19:29:42.759: E/AndroidRuntime(305): at java.lang.reflect.Method.invokeNative(Native Method)
01-04 19:29:42.759: E/AndroidRuntime(305): at java.lang.reflect.Method.invoke(Method.java:521)
01-04 19:29:42.759: E/AndroidRuntime(305): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-04 19:29:42.759: E/AndroidRuntime(305): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-04 19:29:42.759: E/AndroidRuntime(305): at dalvik.system.NativeStart.main(Native Method)
01-04 19:29:42.759: E/AndroidRuntime(305): Caused by: java.lang.NullPointerException
01-04 19:29:42.759: E/AndroidRuntime(305): at
`com.stylingandroid.IntelligentLayout.FindUs.createGroupList(FindUs.java:353)
01-04 19:29:42.759: E/AndroidRuntime(305): at`
com.stylingandroid.IntelligentLayout.FindUs.onCreate(FindUs.java:200)
01-04 19:29:42.759: E/AndroidRuntime(305): at
`android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-04 19:29:42.759: E/AndroidRuntime(305): at `
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-04 19:29:42.759: E/AndroidRuntime(305): ... 11 more
异常总是发生在函数createGroupList用于填充的城市。
Exception always occurs at the function createGroupList for populating cities.
推荐答案
很难说清楚没有看到你的code在一个连续的块,但它看起来像你的AsyncTask的面前创建您的适配器(引用市)完成。因此,它是空,这就是为什么你正在执行你的AsyncTask甚至在一个空指针。
Hard to say exactly without seeing your code in one contiguous block but it looks like you are creating your adapter (which references cities) before your asynctask has completed. Therefore it is null and that's why you are getting a null pointer even before your asynctask is executed.
你为什么不尝试初始化,并在您的AsyncTask的onPostExecute方法分配适配器到ListView ...
Why don't you try initialising and assigning your adapter to the listview in the onPostExecute method of your asynctask...
这篇关于在Android的异步任务code的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!