Reputation: 1623
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);
}
}
But it never gets reqTask.execute(); executed and doesn't fill up the variable. Looking forward to your reply. thanks.
below is the stack trace
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
Exception always occurs at the function createGroupList for populating cities.
Upvotes: 0
Views: 644
Reputation: 201138
AsyncTask
executes in another thread. You can't expect it to be complete as soon as you get to the next line of code after you've called execute() on it. Anything that depends on the task being complete needs to happen in the task's onPostExecute()
method.
Upvotes: 1
Reputation: 8072
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.
Why don't you try initialising and assigning your adapter to the listview in the onPostExecute method of your asynctask...
Upvotes: 2
Reputation: 1882
When is the 2nd code block executed? I'm having some trouble seeing what's going on due to too many code fragments, but if your AsyncTask needs to have finished before you continue, then you should add a callback from the task so that you run the rest of the code when the task has finished. The AsyncTask hands you off to the main thread in onPostExecute()
, so you can use the data from there.
Upvotes: 2