Я новичок в задачах android и async.
Я разрабатываю приложение, в котором при нажатии кнопки открывается макет и выполняется поиск широты и долготы его устройства.
Эти широта и долгота затем отправляются на сервер для получения сведений о филиалах от ближайшего к дальнему.
Я получаю нулевой указатель. Исключение не может понять, как работает AsyncTask, так как AsyncTask Execute никогда не вызывается. Ниже приведен код
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 для населенных пунктов.