Having log errors while launching activities using intents - java

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!!!

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.

Exception while downloading URL in google maps

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)

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".

How do I modify this code for it to work on Android API 3.0?

We are making an Android app that has a login function and mySQL database stored on the server. I found a piece of code and got it to work fine on Android device lower than API level 3.0. Anything beyond that will crash. I was told to use Asynctask to solve my issue. To seperate UI code from the network code? Was told it should be easy but I have no idea how to get it to work. Can anyone should me exactly what I need to do to make this code work? I have spent countless of hours researching into this problem and still no luck. I appreciate any help. Thank you
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Here is also the logCatError
D/AndroidRuntime(10040): Shutting down VM
W/dalvikvm(10040): threadid=1: thread exiting with uncaught exception (group=0x416f2930)
E/AndroidRuntime(10040): FATAL EXCEPTION: main
E/AndroidRuntime(10040): android.os.NetworkOnMainThreadException
E/AndroidRuntime(10040): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(10040): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
E/AndroidRuntime(10040): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
E/AndroidRuntime(10040): at libcore.io.IoBridge.connect(IoBridge.java:112)
E/AndroidRuntime(10040): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
E/AndroidRuntime(10040): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
E/AndroidRuntime(10040): at java.net.Socket.connect(Socket.java:842)
From the ICS and above versions Android won't allowed any network operation in the UI thread.It should be done in separate thread so it won't hang the UI.Try your network communication code in the separate thread.
Refer this Link.It explains why this occurs on Android 3.0 and above.
It is true that android has become very strict about UI thread and wont allow you to perform background calculations on UI thread as it decrease the performance.You were told right to use async task for performing network communications. You can do it by executing asyncTask at onCLick of your register button using new yourTask().execute();.
Then write an asyncTask class like this
private class yourTask extends AsyncTask<Integer, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//show a progress bar
}
#Override
protected String doInBackground(Integer... params) {
// your network communication code will be here.
return 0;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//show the result here
}
}

Categories