我是android和异步任务的新手。 我正在开发一个应用程序,在点击按钮时打开布局并搜索他的设备纬度和经度。 然后将这些纬度和经度发送到服务器,以便从最近到最远的地方获取分支的详细信息。 我得到一个Null指针异常无法理解AsyncTask是如何工作的AsyncTask执行永远不会被调用。以下是代码
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();已执行但未填写变量。 期待你的回复。 感谢。
下面的是堆栈跟踪
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中。
答案 0 :(得分:2)
第二个代码块何时执行?由于代码片段太多,我在查看正在发生的事情时遇到了一些麻烦,但是如果您的AsyncTask需要在继续之前完成,那么您应该从任务中添加一个回调,以便在任务时运行其余的代码已完成。 AsyncTask将您带到onPostExecute()
中的主线程,因此您可以使用那里的数据。
答案 1 :(得分:2)
很难说没有在一个连续的块中看到你的代码,但看起来你在asynctask完成之前创建了你的适配器(它引用了城市)。因此它为null,这就是为什么在执行asynctask之前你得到一个空指针。
为什么不尝试在asynctask的onPostExecute方法中初始化并将适配器分配给listview ...
答案 2 :(得分:1)
AsyncTask
在另一个线程中执行。在调用execute()之后,只要进入下一行代码,就不能指望它完成。任何依赖于任务完成的事情都需要在任务的onPostExecute()
方法中发生。