Exception while downloading URL in google maps - java

Part of my application has a map which should display place in map when entered in a auto filled text view.
I could able to handle exception but map is not displaying the correct place, Log cat shows a message saying "Exception while downloading URL".I am not sure where the problem is.
MainActivity
public class Autocomplete extends FragmentActivity {
AutoCompleteTextView atvPlaces;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
GoogleMap googleMap;
final int PLACES=0;
final int PLACES_DETAILS=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_autocomplete);
// Getting a reference to the AutoCompleteTextView
atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
atvPlaces.setThreshold(1);
// Adding textchange listener
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
// Setting an item click listener for the AutoCompleteTextView dropdown list
atvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long id) {
ListView lv = (ListView) arg0;
SimpleAdapter adapter = (SimpleAdapter) arg0.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(index);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
}
});
}
private String getAutoCompleteUrl(String place){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyCfdXATlz7jtM6MEvy9Xh_3_g_Ivc5ysXE";
// place to be be searched
String input = "input="+place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input+"&"+types+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
return url;
}
private String getPlaceDetailsUrl(String ref){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=YOUR_API_KEY";
// reference of place
String reference = "reference="+ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
private int downloadType=0;
// Constructor
public DownloadTask(int type){
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch(downloadType){
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS :
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>> {
int parserType = 0;
public ParserTask(int type){
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try{
jObject = new JSONObject(jsonData[0]);
switch(parserType){
case PLACES :
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS :
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
}
}catch(Exception e){
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
switch(parserType){
case PLACES :
String[] from = new String[] { "description"};
int[] to = new int[] { android.R.id.text1 };
// Creating a SimpleAdapter for the AutoCompleteTextView
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
atvPlaces.setAdapter(adapter);
break;
case PLACES_DETAILS :
HashMap<String, String> hm = result.get(0);
// Getting latitude from the parsed data
double latitude = Double.parseDouble(hm.get("lat"));
// Getting longitude from the parsed data
double longitude = Double.parseDouble(hm.get("lng"));
// Getting reference to the SupportMapFragment of the activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap from SupportMapFragment
googleMap = fm.getMap();
LatLng point = new LatLng(latitude, longitude);
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(point);
CameraUpdate cameraZoom = CameraUpdateFactory.zoomBy(5);
// Showing the user input location in the Google Map
googleMap.moveCamera(cameraPosition);
googleMap.animateCamera(cameraZoom);
MarkerOptions options = new MarkerOptions();
options.position(point);
options.title("Position");
options.snippet("Latitude:"+latitude+",Longitude:"+longitude);
// Adding the marker in the Google Map
googleMap.addMarker(options);
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
ParseDetailsJsonParser.java
package zybo.example.ramz.map_webview;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PlaceDetailsJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
Double lat = Double.valueOf(0);
Double lng = Double.valueOf(0);
HashMap<String, String> hm = new HashMap<String, String>();
List<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
try {
lat = (Double)jObject.getJSONObject("result").getJSONObject("geometry").getJSONObject("location").get("lat");
lng = (Double)jObject.getJSONObject("result").getJSONObject("geometry").getJSONObject("location").get("lng");
} catch (JSONException e) {
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
hm.put("lat", Double.toString(lat));
hm.put("lng", Double.toString(lng));
list.add(hm);
return list;
}
}
Logcat
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.016 + 62ca4eb + acd831d + 9f8b442 + e027a02 + cba30ba + 53c303a + a649d79 + 23e16f8 + 5e97da7 + cbd2a44 + 33d072a + 7aacf06 + 72b33e7 + 28f6f60 + b4c13d8 + NOTHING
09-30 14:44:58.321 2965-3120/zybo.example.ramz.map_webview I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-30 14:44:58.390 2965-3120/zybo.example.ramz.map_webview D/OpenGLRenderer﹕ Enabling debug mode 0
09-30 14:44:58.485 2965-3120/zybo.example.ramz.map_webview V/RenderScript﹕ Application requested CPU execution
09-30 14:44:58.498 2965-3120/zybo.example.ramz.map_webview V/RenderScript﹕ 0xb82914f0 Launching thread(s), CPUs 4
09-30 14:45:05.291 2965-3043/zybo.example.ramz.map_webview D/Volley﹕ [8830] a.a: HTTP response for request=<[ ] https://clients4.google.com/glm/mmap/api 0x99e6744e NORMAL 1> [lifetime=7134], [size=60], [rc=200], [retryCount=0]
09-30 14:45:05.298 2965-2965/zybo.example.ramz.map_webview D/Volley﹕ [1] p.b: 7147 ms: [ ] https://clients4.google.com/glm/mmap/api 0x99e6744e NORMAL 1
09-30 14:45:05.712 2965-3044/zybo.example.ramz.map_webview D/Volley﹕ [8831] a.a: HTTP response for request=<[ ] https://csi.gstatic.com/csi?s=maps_android_api&v=3&action=map_start_up&it=map_load.1581,on_create.1,on_resume.1,init.378&irt=1581,379,399,378 0x4d844933 NORMAL 2> [lifetime=6368], [size=0], [rc=204], [retryCount=0]
09-30 14:45:05.759 2965-2965/zybo.example.ramz.map_webview D/Volley﹕ [1] p.b: 6416 ms: [ ] https://csi.gstatic.com/csi?s=maps_android_api&v=3&action=map_start_up&it=map_load.1581,on_create.1,on_resume.1,init.378&irt=1581,379,399,378 0x4d844933 NORMAL 2
09-30 14:45:14.452 2965-3124/zybo.example.ramz.map_webview D/Exception while downloading url﹕ java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Delhi, India&types=geocode&sensor=false&key=AIzaSyCfdXATlz7jtM6MEvy9Xh_3_g_Ivc5ysXE
09-30 14:45:14.459 2965-3124/zybo.example.ramz.map_webview D/Background Task﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
09-30 14:45:17.503 2965-3124/zybo.example.ramz.map_webview D/Exception﹕ org.json.JSONException: End of input at character 0 of
09-30 14:45:17.516 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ org.json.JSONException: No value for result
09-30 14:45:17.519 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:389)
09-30 14:45:17.519 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at org.json.JSONObject.getJSONObject(JSONObject.java:609)
09-30 14:45:17.520 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at zybo.example.ramz.map_webview.PlaceDetailsJSONParser.parse(PlaceDetailsJSONParser.java:25)
09-30 14:45:17.520 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at zybo.example.ramz.map_webview.Autocomplete$ParserTask.doInBackground(Autocomplete.java:280)
09-30 14:45:17.520 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at zybo.example.ramz.map_webview.Autocomplete$ParserTask.doInBackground(Autocomplete.java:254)
09-30 14:45:17.520 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-30 14:45:17.521 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-30 14:45:17.521 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-30 14:45:17.521 2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

Related

NullPointer Exception while adding data from android to mysql database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm getting NullPointerException while adding data from android app to MySQL database, so when I click to create a new product this exception occurs. This is my code to add new product in my database:
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.56.1/products/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// creating new product in background thread
new CreateNewProduct().execute(name,price,description);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = args[0],
price = args[1],
description = args[2];
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
**line 102** JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
I checked out my PHP code and it works fine:
<?php
$con = mysql_connect('localhost', 'root','');
mysql_select_db('database',$con);
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
$sql = "insert into products(name, price, description)
values('$name','$price','$description')";
mysql_query($sql);
?>
Logcat:
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:856)
aused by: java.lang.NullPointerException
at com.example.hanen.test1.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:102)
at com.example.hanen.test1.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:68)
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:856) 
I don't have the answer to your question, because you haven't included line numbers on your listing, and I'm not going to hand-number them. Finding and fixing this type of error, though, is dead simple. Here are the steps:
Turn on line numbers in your IDE
Find the line in your code that corresponds to the topmost line in the stacktrace that refers to a line in your code. In this case that is line 102 in the file NewProductActivity.java
On that line, there will be an expression that looks like variable.something.
When that line is executed variable is null. Find out why.

Driving distance and travel time duration between two locations in Google Map Android API V2

I am trying to implement this example in android studio:
driving distance and travel time duration between two locations
I am facing errors during runtime as follows:
E/GMPM: getGoogleAppId failed with status: 10
E/GMPM: Uploading is not possible. App measurement disabled
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.start.yogeshp.location, PID: 7332
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.start.yogeshp.location/com.start.yogeshp.location.MainActivity}: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
at android.app.Activity.setContentView(Activity.java:2144)
at com.start.yogeshp.location.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
Caused by: java.lang.NullPointerException
at java.lang.VMClassLoader.findLoadedClass(Native Method)
at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.support.v4.app.Fragment.isSupportFragmentClass(Fragment.java:457)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2248)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:314)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377) 
at android.app.Activity.setContentView(Activity.java:2144) 
at com.start.yogeshp.location.MainActivity.onCreate(MainActivity.java:40) 
at android.app.Activity.performCreate(Activity.java:5937) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
These are my files:
MainActivity.java
public class MainActivity extends FragmentActivity {
GoogleMap map;
ArrayList<LatLng> markerPoints;
TextView tvDistanceDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
// Initializing
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// Setting onclick event listener for the map
map.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Already two locations
if(markerPoints.size()>1){
markerPoints.clear();
map.clear();
}
// Adding new item to the ArrayList
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(markerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(markerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
map.addMarker(options);
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if(result.size()<1){
Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
} }
DirectionsJSONParser.java:
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
}
routes.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
} }
activity_main.xml:
i used two fields in relative layout:
<TextView
android:id="#+id/tv_distance_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:layout_alignParentTop="true" />
<fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_distance_time" />
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<permission
android:name="com.start.yogeshp.location.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.start.yogeshp.location.permission.MAPS_RECEIVE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="key" />
</application>
and finally added "compile 'com.google.android.gms:play-services:8.3.0'" to my build.gradle file.
in your layout you forgot the class attribute
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_distance_time">

Fragment inner class error throws Fatal Exception which is using a AsyncTask to update UI views

Below is my code using inner class Fragment. Also I am using an AsyncTask to perform some background operation. It throws a Fatal Exception while executing.
public class LocationFragment extends Fragment {
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//gps class
GPSTracker gps;
double latitude,longitude;
public TextView current_location;
private static final String BC_URL = "http://manfredinfotech.com/projects/workshop/get_location.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
public LocationFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// create class object
gps = new GPSTracker(getActivity());
// check if GPS enabled
View rootView = inflater.inflate(R.layout.fragment_location, container, false);
current_location = (TextView) rootView.findViewById(R.id.current_location);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getActivity(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
new GetLocation().execute();
}
return rootView;
}
class GetLocation extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args){
int success;
try{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("lat",String.valueOf(latitude)));
params.add(new BasicNameValuePair("lon", String.valueOf(longitude)));
JSONObject json = jsonParser.makeHttpRequest(BC_URL, "POST", params);
System.out.println("JSON" + json);
// check your log for json response
Log.d("Here", json.toString());
success = json.getInt(TAG_SUCCESS);
if(success == 1){
if(pDialog.isShowing())pDialog.dismiss();
System.out.println(json.getString(TAG_MESSAGE));
current_location.setText(json.getString(TAG_MESSAGE));
//return json.getString(TAG_MESSAGE);
} else {
if(pDialog.isShowing())pDialog.dismiss();
current_location.setText("Not location found");
System.out.println("Failed!");
//return json.getString(TAG_MESSAGE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
Now this line current_location.setText(json.getString(TAG_MESSAGE));
throws error. Below is the Stacktrace for the exception I am getting.
> 08-20 12:30:44.242 27109-27190/com.mipl.trupco E/AndroidRuntime﹕
> FATAL EXCEPTION: AsyncTask #1
> Process: com.mipl.trupco, PID: 27109
> java.lang.RuntimeException: An error occured while executing doInBackground()
> at android.os.AsyncTask$3.done(AsyncTask.java:304)
> at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
> at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
> at java.util.concurrent.FutureTask.run(FutureTask.java:242)
> at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
> at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
> at java.lang.Thread.run(Thread.java:818)
> Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
> original thread that created a view hierarchy can touch its views.
> at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357)
> at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:874)
> at android.view.View.requestLayout(View.java:17476)
> at android.view.View.requestLayout(View.java:17476)
> at android.view.View.requestLayout(View.java:17476)
> at android.view.View.requestLayout(View.java:17476)
> at android.support.v4.widget.DrawerLayout.requestLayout(DrawerLayout.java:749)
> at android.view.View.requestLayout(View.java:17476)
> at android.view.View.requestLayout(View.java:17476)
> at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
> at android.view.View.requestLayout(View.java:17476)
> at android.widget.TextView.checkForRelayout(TextView.java:6871)
> at android.widget.TextView.setText(TextView.java:4057)
> at android.widget.TextView.setText(TextView.java:3915)
> at android.widget.TextView.setText(TextView.java:3890)
> at com.mipl.trupco.LocationFragment$GetLocation.doInBackground(LocationFragment.java:99)
> at com.mipl.trupco.LocationFragment$GetLocation.doInBackground(LocationFragment.java:65)
> at android.os.AsyncTask$2.call(AsyncTask.java:292)
> at java.util.concurrent.FutureTask.run(FutureTask.java:237)
>             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
>             at
Please help
You have to move the portion of the background task that updates the ui on to the main thread. There is a simple piece of code for this:
runOnUiThread(new Runnable() {
#Override
public void run() {
//Update your UI
}
});
Activity.runOnUiThread
Or you can write the code in onPostExecute of Asynctask.
You are manipulating your layout, i.e. your current_location textview from background thread (doInBackground). This is not allowed, the error states this out. For manipulating view elements you should use onPreExecute or onPostExecute methods.
The error is in your doInBackground() whenever success == 1 or not because you try to edit the textview current_location from a thread.
So simple solution is to override onPostExecute() method inside your GetLocation class, return the text that you want to it and there you can set it. edit this inside the doInBackground()
if(success == 1){
if(pDialog.isShowing())pDialog.dismiss();
System.out.println(json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
} else {
if(pDialog.isShowing())pDialog.dismiss();
System.out.println("Failed!");
return "Not location found";
}
and add this new method to after doInBackground()
#Override
protected void onPostExecute(String result) {
if(result != null)
current_location.setText(result);
}

App Crashes But Method Still Works?

I am trying to delete an item in my listview but keep getting an ArrayOutOfBoundException yet my LOG shows successful deletion from my Localhost and if you open it back it reflects the changes...
Not to sure how to fix the Exception that causes my app to crash? Any Ideas?
Class with Async Tasks:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_locations);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
deleteLocation = (Button) findViewById(R.id.deleteLocation);
locationCount = (TextView) findViewById(R.id.locationCount);
lo = (ListView) findViewById(android.R.id.list);
//setup adapter first //now no items, after getting items (LoadAllLocations) will update it
adapter = new SimpleAdapter(
ViewAllLocations.this, profileList,
R.layout.locationitem, new String[]{TAG_ID,
TAG_LATITUDE, TAG_LONGITUDE},
new int[]{R.id.id, R.id.latitude, R.id.longitude});
// updating listview
setListAdapter(adapter);
// Loading products in Background Thread
new LoadAllLocation().execute();
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
id = i.getStringExtra(TAG_ID);
// Get listview
ListView lo = getListView();
lo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);
}
});
}
/**
* **************************************************************
* Background Async Task to Delete Product
*/
class DeleteLocation extends AsyncTask<String, String, Integer> {
int deleteItemPosition;
public DeleteLocation(int position) {
// TODO Auto-generated constructor stub
this.deleteItemPosition = position;
}
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(ViewAllLocations.this);
//pDialog.setMessage("Deleting Location...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(true);
// pDialog.show();
}
/**
* Deleting product
*/
protected Integer doInBackground(String... args) {
String selectedId = args[0];
// Check for success tag
int success = 0; //0=failed 1=success
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", selectedId));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
//if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
// Intent i = getIntent();
// send result code 100 to notify about product deletion
//setResult(100, i);
//you cant update UI on worker thread, it must be done on UI thread
// Toast.makeText(getApplicationContext(), "Location Deleted",
// Toast.LENGTH_SHORT).show();
//finish();
// }
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog once product deleted
if (result == 1) {
//success
//delete from list and update listview
profileList.remove(deleteItemPosition);
adapter.notifyDataSetChanged();
//pDialog.dismiss();
} else {
//failed
}
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllLocation extends AsyncTask<String, String, Integer> {
int success;
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Loading Locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected Integer doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_LOCATION);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// UserLocation.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog after getting all products
pDialog.dismiss();
locationCount.setText("" + profileList.size());
if (result == 1) {
//success
//update adapter items
adapter.notifyDataSetChanged();
} else {
//failed
//launch activity here
}
}
}
LOG: Delete Successful but still an error?
04-25 20:08:32.463 22736-23492/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
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:856)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.ankhit.saveme.ViewAllLocations$DeleteLocation.doInBackground(ViewAllLocations.java:144)
at com.example.ankhit.saveme.ViewAllLocations$DeleteLocation.doInBackground(ViewAllLocations.java:117)
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:856)
04-25 20:08:32.713 22736-22736/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
04-25 20:08:32.733 22736-23498/com.example.ankhit.saveme D/Delete Product﹕ {"message":"Profile successfully deleted","success":1}
Your problem is originating from here
new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);
You are running two separate tasks, but only the second task is given a parameter. Therefore, the first task
new DeleteLocation(position).execute();
throws an exception, here
protected Integer doInBackground(String... args) {
String selectedId = args[0];
...
}
args[0] is out-of-bounds because no args were passed to execute.
The second task is done in a different thread and manages to finish before the exception from the first task is passed back up the call stack, which is why it still "works".

Having log errors while launching activities using intents

I am trying to launch a new activity by passing intents as data
I have posted the log
How to resolve the errors
RatingDescriptionFilterActivity.java
public class RatingDescriptionFilterActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String DISTANCE = "distance";
static String RATING = "rating";
static String FLAG = "flag";
private String url = "----------------- url----------";
String TYPE_FILTER;
String PRICE_FILTER;
String RATE_FILTER;
String DISTANCE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
//Bundle extras = getIntent().getExtras();
TYPE_FILTER = getIntent().getStringExtra("REST1");
PRICE_FILTER = getIntent().getStringExtra("PriceBar");
RATE_FILTER = getIntent().getStringExtra("DistanceBar");
DISTANCE_FILTER = getIntent().getStringExtra("RatingBar");
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(RatingDescriptionFilterActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String newurl = "?" + "Key=" + DISTANCE_FILTER.trim() + "&Key1=" + RATE_FILTER.trim() + "&Key2=" + PRICE_FILTER.trim() + "&Key3=" + TYPE_FILTER.trim();
Log.i ("newurl", newurl.toString ());
jsonobject = JSONfunctions.getJSONfromURL("------------url-----------"+newurl);
Log.i ("jsonobject", jsonobject.toString ());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(RatingDescriptionActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(RatingDescriptionActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(RatingDescriptionActivity.FLAG, "-----url-----"+jsonobject.getString("restaurantIMAGE"));
map.put(RatingDescriptionActivity.DISTANCE, jsonobject.getString("restaurantDISTANCE"));
map.put(RatingDescriptionActivity.RATING, jsonobject.getString("restaurantRATING"));
map.put(RatingDescriptionActivity.PRICE, jsonobject.getString("restaurantPrice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(RatingDescriptionFilterActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Log::
10-21 17:55:46.756: E/AndroidRuntime(1061): FATAL EXCEPTION: AsyncTask #2
10-21 17:55:46.756: E/AndroidRuntime(1061): java.lang.RuntimeException: An error occured while executing doInBackground()
10-21 17:55:46.756: E/AndroidRuntime(1061): at android.os.AsyncTask$3.done(AsyncTask.java:200)
10-21 17:55:46.756: E/AndroidRuntime(1061): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-21 17:55:46.756: E/AndroidRuntime(1061): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-21 17:55:46.756: E/AndroidRuntime(1061): at
line is RatingDescriptionFilterActivity.java:87 is
String newurl = "?" + "Key=" + DISTANCE_FILTER.trim() + "&Key1=" + RATE_FILTER.trim() + "&Key2=" + PRICE_FILTER.trim() + "&Key3=" + TYPE_FILTER.trim();
Problem is arising in getting the value from seek bars in filters.java
How to debug the errors
I hope you are using Eclipse, so you can put breakpoint on this line and debug your application, you can also use expressions view to find out value for each of DISTANCE_FILTER, RATE_FILTER, PRICE_FILTER, TYPE_FILTER
here are steps to debug android application
1) you need to set android:debuggable="true" in your application in the AndroidManifest.xml. if you haven't set that setting, debugging will not be enabled.
2) either start the app by right clicking on the project and select Debug As->Android Application or by running it normally and later in the DDMS perspective select the running app in your devices pane and click on the green bug.
3) once a breakpoint has been hit you can step over (f6) or step into (f5) (check the Run menu for more commands).
Cheers!!!

Categories