I have a problem again with AsyncTask in Android.
I made a simple AsyncTask class to display multiple markers on a MapView. But starting the activity, there is a NullPointerException - I think this is caused by the MapView...
public class MapDetail extends MapActivity {
// JSON Node names
private static final String TAG_NEWNAME = "name";
private static final String TAG_LONG = "long";
private static final String TAG_LAT = "lat";
// Variablen
private MapController mc;
private List<Overlay> mapOverlays;
private Drawable drawable;
private MapItemizedOverlay itemizedoverlay;
private MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.offers);
// getting intent data
Bundle extras = getIntent().getExtras();
String url = extras.getString("url");
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.marker);
itemizedoverlay = new MapItemizedOverlay(drawable, this);
new MyAsyncTask().execute(url);
}
And this is my AsyncTask:
public class MyAsyncTask extends AsyncTask<String, Void, MapItemizedOverlay > {
#Override
protected MapItemizedOverlay doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
JSONArray locations = jParser.getJSONArrayFromUrl(params[0]);
for (int i = 0; i < locations.length(); i++) {
JSONObject c;
try {
c = locations.getJSONObject(i);
// Storing each json item in variable
String firma = c.getString(TAG_NEWNAME);
String longitude = c.getString(TAG_LONG);
String latitude = c.getString(TAG_LAT);
System.out.println("Kriege ich daten"+longitude+"und"+latitude);
double x = Double.parseDouble(latitude);
double y = Double.parseDouble(longitude);
GeoPoint point = new GeoPoint((int)(x * 1E6),(int)(y * 1E6) );
OverlayItem overlayitem = new OverlayItem(point, firma, null);
itemizedoverlay.addOverlay(overlayitem);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(itemizedoverlay.toString());
return itemizedoverlay;
}
#Override
protected void onPostExecute(MapItemizedOverlay result) {
mapOverlays.add(result);
mapView.getOverlays().add(result);
LocationManager myLocationManager;
LocationListener myLocationListener;
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,myLocationListener);
GeoPoint initGeoPoint = new GeoPoint( (int)(myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude()*1000000),
(int)(myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude()*1000000));
mc.animateTo(initGeoPoint);
mc.setZoom(6);
mapView.invalidate();
}
}}
My Log:
01-06 19:49:23.703: E/AndroidRuntime(6064): FATAL EXCEPTION: main
01-06 19:49:23.703: E/AndroidRuntime(6064): java.lang.NullPointerException
01-06 19:49:23.703: E/AndroidRuntime(6064): at de.main.MapDetail$MyAsyncTask.onPostExecute(MapDetail.java:150)
01-06 19:49:23.703: E/AndroidRuntime(6064): at de.main.MapDetail$MyAsyncTask.onPostExecute(MapDetail.java:1)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.Handler.dispatchMessage(Handler.java:99)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.Looper.loop(Looper.java:137)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-06 19:49:23.703: E/AndroidRuntime(6064): at java.lang.reflect.Method.invokeNative(Native Method)
01-06 19:49:23.703: E/AndroidRuntime(6064): at java.lang.reflect.Method.invoke(Method.java:511)
01-06 19:49:23.703: E/AndroidRuntime(6064): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-06 19:49:23.703: E/AndroidRuntime(6064): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-06 19:49:23.703: E/AndroidRuntime(6064): at dalvik.system.NativeStart.main(Native Method)
Related
During development, there was a similar problem and also because of the fact that I am a novice, do not know how to handle it, thanks in advance to those who help!
I tried to change something to rewrite over and all else fails, I can not understand at what point I did something wrong
Activity
public class FormActivity extends AppCompatActivity {
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
///=================================
/////Автоматическийм расчет веремени
EditText et1 = (EditText) findViewById(R.id.formtime);
EditText et2 = (EditText) findViewById(R.id.formdate);
SimpleDateFormat df1 = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd ");
Calendar c = Calendar.getInstance();
String e1 = df1.format(c.getTime());
String e2 = df2.format(c.getTime());
et1.setText(e1);
et2.setText(e2);
/////Конец расчета времени
}
public void GeoClick(View v){
String svcName = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(svcName);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
Location l = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(l);
locationManager.requestLocationUpdates(provider, 5000, 10, locationListener);
}
private void updateWithNewLocation(Location location) {
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String latLongString = "No location found";
String addressString = "No address found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {}
}
myLocationText.setText("Your Current Position is:\n" +
latLongString + "\n\n" + addressString);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {updateWithNewLocation(location);}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
}
Error
{FATAL EXCEPTION: main java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3591)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3586)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: provider==null
at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1153)
at ru.ochakovo.ochakoco.FormActivity.GeoClick(FormActivity.java:56)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3586)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method) }
You are getting this error most probably, due to un-avialability of GPS Providers. Please ask the person to check settings if Gps Provider or Network Provider has been enabled into Location settings..Hope so it is helpful for you
I think your provider empty null value...
I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasdasdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}
I am currently creating a Android GoogleMaps app and have stored a list of Locations on a database on an online server. I'm pulling them through successfully and now I want to use the Actionbar searchview to create a listview that the user can search and it will change the currently loaded data to only show the ones linked to the currently selected Location.
However I am coming across the error of cannot be cast to android.content.Context when trying to put the arraylist into the adapter after changing the ListViewAdapter code to be a runnable due to where I am calling it. My main activity code is as follows:
TownSelector ts;
ListView townList;
ListViewAdapter townAdapter; <---set variable for adapter here
String[] townID;
String[] townName;
ArrayList<TownSelector> arraylist = new ArrayList<TownSelector>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.search);
setUpMapIfNeeded();
// Hashmap for ListView
locationList = new ArrayList<HashMap<String, String>>();
// Locate the ListView in listview_main.xml
townList = (ListView) findViewById(R.id.listview);
}
class LoadAllInfo extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> paramsLocations = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject jsonLocations = jParser.makeHttpRequest(url_all_locations, "GET", paramsLocations);
//Get all offer
if(jsonLocations != null)
{
// Check your log cat for JSON reponse
Log.d("All Locations: ", jsonLocations.toString());
try {
// Checking for SUCCESS TAG
int success = jsonLocations.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Offers
locations = jsonLocations.getJSONArray(TAG_LOCATIONS);
// looping through All Offers
for (int i = 0; i < locations.length(); i++) {
JSONObject c = locations.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_LID);
String locationName = c.getString(TAG_LNAME);
// creating new HashMap
HashMap<String, String> locationsListMap = new HashMap<String, String>();
// adding each child node to HashMap key => value
locationsListMap.put(TAG_LID, id);
locationsListMap.put(TAG_LNAME, locationName);
// adding HashList to ArrayList
locationList.add(locationsListMap);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into map marker
* */
//TODO setMapMarkers
townID = new String[locationList.size()];
townName = new String[locationList.size()];
for(int l = 0; l <= (locationList.size() - 1); l++)
{
Log.d("Hello", "location loop");
Log.d("Hello", locationList.get(l).toString().split("Location_ID=")[1].split(",")[0]);
townID[l] = locationList.get(l).toString().split("Location_ID=")[1].split(",")[0];
Log.d("Hello", locationList.get(l).toString().split("Location_Name=")[1].split(",")[0].replace("}",""));
townName[l] = locationList.get(l).toString().split("Location_Name=")[1].split(",")[0].replace("}","");
}
for (int i = 0; i < townID.length; i++)
{
ts = new TownSelector(townID[i], townName[i]);
// Binds all strings into an array
arraylist.add(ts);
}
// Pass results to ListViewAdapter Class
townAdapter = new ListViewAdapter(this, arraylist); <--Create new instant of adapter here
// Binds the Adapter to the ListView
townList.setAdapter(townAdapter); //This is the line that causes a crash
}
});
}
}
ListViewAdapter code:
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<TownSelector> locationlist = null;
private ArrayList<TownSelector> arraylist;
public ListViewAdapter(Runnable runnable, List<TownSelector> locationlist) {
mContext = (Context) runnable;
this.locationlist = locationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<TownSelector>();
this.arraylist.addAll(locationlist);
}
I changed the ListViewAdapter code to the what is below after finding this stackflow question android callback fails in fragment fails cannot be cast to android.content.Context
public ListViewAdapter(Context context,Runnable runnable, List<TownSelector> locationlist) {
mContext = context;
this.runnable = runnable;
this.locationlist = locationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<TownSelector>();
this.arraylist.addAll(locationlist);
}
error callstack:
09-22 03:58:03.467: E/AndroidRuntime(15586): FATAL EXCEPTION: main
09-22 03:58:03.467: E/AndroidRuntime(15586): Process: biz.nickbullcomputing.bevnav, PID: 15586
09-22 03:58:03.467: E/AndroidRuntime(15586): java.lang.ClassCastException: biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo$1 cannot be cast to android.content.Context
09-22 03:58:03.467: E/AndroidRuntime(15586): at biz.nickbullcomputing.bevnav.ListViewAdapter.<init>(ListViewAdapter.java:25)
09-22 03:58:03.467: E/AndroidRuntime(15586): at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo$1.run(MainActivity.java:409)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.app.Activity.runOnUiThread(Activity.java:4794)
09-22 03:58:03.467: E/AndroidRuntime(15586): at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo.onPostExecute(MainActivity.java:376)
09-22 03:58:03.467: E/AndroidRuntime(15586): at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo.onPostExecute(MainActivity.java:1)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.AsyncTask.finish(AsyncTask.java:632)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.Handler.dispatchMessage(Handler.java:102)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.Looper.loop(Looper.java:157)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.app.ActivityThread.main(ActivityThread.java:5867)
09-22 03:58:03.467: E/AndroidRuntime(15586): at java.lang.reflect.Method.invokeNative(Native Method)
09-22 03:58:03.467: E/AndroidRuntime(15586): at java.lang.reflect.Method.invoke(Method.java:515)
09-22 03:58:03.467: E/AndroidRuntime(15586): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
09-22 03:58:03.467: E/AndroidRuntime(15586): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
09-22 03:58:03.467: E/AndroidRuntime(15586): at dalvik.system.NativeStart.main(Native Method)
this part in your asyncTask townAdapter = new ListViewAdapter(this, arraylist); is not correct. your editor should have shown error. you need to pass YourActivityName.this just this is sending LoadAllInfo as context which is wrong
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I created a layout named activity_category and activity named CategoryActivity the code of which is as follows
public class CategoryActivity extends Activity {
private LazyItemLoadAdapter adapter;
private int[] selectionId;
private Item[] item_data;
private GridView grid;
private TextView textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_category);
ActionBarUtils.setActionBar(this);
String id=getIntent().getExtras().getString("id");
try{
AsyncData data=new AsyncData();
data.execute(Constants.SERVER+"cat_adlist.php?id="+id);
grid = (GridView) findViewById(R.id.gridViewAllItems);
}catch(NotFoundException n){
}
}
private class AsyncData extends AsyncTask<String, Void, Item[]>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Item[] doInBackground(String... params) {
String str=null;
try {
str = CustomHttpClient
.executeHttpGet(params[0]);
Log.i("Category Data", str);
JSONArray array = new JSONArray(str);
item_data = new Item[array.length()];
selectionId = new int[array.length()];
for (int i = 0; i < item_data.length; i++) {
JSONObject jdata = array.getJSONObject(i);
String path = Constants.THUMBS
+ jdata.getString("name");
int itemid = jdata.getInt("id");
item_data[i] = new Item(itemid, path, jdata.getString("title"),
jdata.getString("price"));
selectionId[i] = jdata.getInt("subcategory_id");// change the
// field name
// here
}
}catch(JSONException j){
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return item_data;
}
#Override
protected void onPostExecute(Item[] result) {
adapter = new LazyItemLoadAdapter(CategoryActivity.this, R.layout.text_below_images, result);
grid.setAdapter(adapter);
if (result.length == 0) {
grid.setVisibility(View.GONE);
textview.setVisibility(View.VISIBLE);
} else {
grid.setVisibility(View.VISIBLE);
textview.setVisibility(View.GONE);
}
TextView numResults=(TextView) findViewById(R.id.textView2);
numResults.setText("Found "+String.valueOf(result.length)+" results");
setProgressBarIndeterminateVisibility(false);
super.onPostExecute(result);
}
}
}
The logcat is as follows -
05-07 17:09:58.340: E/AndroidRuntime(2242): FATAL EXCEPTION: main
05-07 17:09:58.340: E/AndroidRuntime(2242): Process: com.opaxlabs.salepurchase, PID: 2242
05-07 17:09:58.340: E/AndroidRuntime(2242): java.lang.NullPointerException
05-07 17:09:58.340: E/AndroidRuntime(2242): at com.opaxlabs.salepurchase.CategoryActivity$AsyncData.onPostExecute(CategoryActivity.java:115)
05-07 17:09:58.340: E/AndroidRuntime(2242): at com.opaxlabs.salepurchase.CategoryActivity$AsyncData.onPostExecute(CategoryActivity.java:1)
05-07 17:09:58.340: E/AndroidRuntime(2242): at android.os.AsyncTask.finish(AsyncTask.java:632)
05-07 17:09:58.340: E/AndroidRuntime(2242): at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-07 17:09:58.340: E/AndroidRuntime(2242): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
05-07 17:09:58.340: E/AndroidRuntime(2242): at android.os.Handler.dispatchMessage(Handler.java:102)
05-07 17:09:58.340: E/AndroidRuntime(2242): at android.os.Looper.loop(Looper.java:136)
05-07 17:09:58.340: E/AndroidRuntime(2242): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-07 17:09:58.340: E/AndroidRuntime(2242): at java.lang.reflect.Method.invokeNative(Native Method)
05-07 17:09:58.340: E/AndroidRuntime(2242): at java.lang.reflect.Method.invoke(Method.java:515)
05-07 17:09:58.340: E/AndroidRuntime(2242): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-07 17:09:58.340: E/AndroidRuntime(2242): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-07 17:09:58.340: E/AndroidRuntime(2242): at dalvik.system.NativeStart.main(Native Method)
As you can see I am getting a null pointer exception. initially it was because I was using a wrong layout but I have corrected that but the problem persists. Please help me with your suggestions. Thanks in advance.
You forget to initialize your TextView textview which is in your onPostExecute method.
#Override
protected void onPostExecute(Item[] result) {
TextView textview =(TextView) findViewById(R.id.textView2);
adapter = new LazyItemLoadAdapter(CategoryActivity.this, R.layout.text_below_images, result);
grid.setAdapter(adapter);
if (result.length == 0) {
grid.setVisibility(View.GONE);
textview.setVisibility(View.VISIBLE);
} else {
grid.setVisibility(View.VISIBLE);
textview.setVisibility(View.GONE);
}
TextView numResults=(TextView) findViewById(R.id.textView2);
numResults.setText("Found "+String.valueOf(result.length)+" results");
setProgressBarIndeterminateVisibility(false);
super.onPostExecute(result);
}
First of all the best practice which I think you should follow is to organise your code in blocks. Initialise all your views after setContentView() no matter when you are using them. If you start doing this you won't have exceptions thrown like this one which you have.
The problem in your code is that you are not initialising your textView variable and using it in your onPostExecute() method of AsyncTask. Your onCreate should look like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_category);
grid = (GridView) findViewById(R.id.gridViewAllItems);
textview = (TextView) findViewById(R.id.myTextView);
numResults = (TextView) findViewById(R.id.textView2);
// Start your AsyncTask here ...
}
I've built some class named "item", here is it: (thats the whole code)
public class item {
private int id;
private String title;
private String desc;
private double lat;
private double lon;
private String pub;
private int p;
private int n;
public item(int id, String title, String desc, double lat, double lon, String pub, int p, int n) {
super();
this.id = id;
this.title = title;
this.desc = desc;
this.lat = lat;
this.lon = lon;
this.pub = pub;
this.p = p;
this.n = n;
}
Now I have to make a List<item> and add() "item"s to it, but for some reason my application crushes.
Thats the Activity:
public class MainActivity extends Activity {
List<item> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
LOGCAT:
08-10 16:32:46.710: D/AndroidRuntime(2934): Shutting down VM
08-10 16:32:46.710: W/dalvikvm(2934): threadid=1: thread exiting with uncaught exception (group=0x41a0a930)
08-10 16:32:46.777: E/AndroidRuntime(2934): FATAL EXCEPTION: main
08-10 16:32:46.777: E/AndroidRuntime(2934): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testitems/com.example.testitems.MainActivity}: java.lang.NullPointerException
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.access$600(ActivityThread.java:153)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.os.Looper.loop(Looper.java:137)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.main(ActivityThread.java:5227)
08-10 16:32:46.777: E/AndroidRuntime(2934): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 16:32:46.777: E/AndroidRuntime(2934): at java.lang.reflect.Method.invoke(Method.java:511)
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
08-10 16:32:46.777: E/AndroidRuntime(2934): at dalvik.system.NativeStart.main(Native Method)
08-10 16:32:46.777: E/AndroidRuntime(2934): Caused by: java.lang.NullPointerException
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.example.testitems.MainActivity.onCreate(MainActivity.java:18)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.Activity.performCreate(Activity.java:5104)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)
08-10 16:32:46.777: E/AndroidRuntime(2934): ... 11 more
Appreciate your help guys!
Initialize your markers list
List<item> markers=new ArrayList<item>();
try this
public class MainActivity extends Activity {
ArrayList<item> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
You have to initialize the list before you use it.
setContentView(R.layout.activity_main);
List<item> markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
Any object should be initialized before using its methods, however you seem to forgot this step before adding data in your list. Initialize markers before adding data in it.
List<item> markers=new ArrayList<item>();
In the code you have not initialize the arraylist object to remove these errors
see the following steps mention below:
First allocate memory to the Arraylist object like this
public class MainActivity extends Activity {
ArrayList markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
Secondly to handle the error use the try and the catch block .
public class MainActivity extends Activity {
ArrayList markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
catch(Exception e)
{
//Write to android ddms logger.
or
make a Toast Message
}
}
Free the resources which has been intialize like arraylist etc.
By putting finally block after the catch Block.