I've ha problem: I 'm implementing a secondary Activity that give to me user's position. From Page1.java, through a button, open Track.java when I would like to show the coordinates of the user's location. The problem is when I click on this button: the application is closed!
This is the code of Page1.java:
package com.example.giacomob.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Giacomo B on 05/08/2015.
*/
public class Page1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
// String dato1 = getIntent().getExtras().getString("NomeDati1");
//Intent intent = getIntent(); // Point 1
// Bundle bundle = intent.getExtras(); // Point 2
// String data1 = bundle.getString("NomeDati1"); // Point 3
String dato1 = getIntent().getExtras().getString("NomeDati1"); //preleva la stringa
Toast.makeText(this, dato1, Toast.LENGTH_SHORT).show(); //PROVA: questo mi fa comparire una specie di label notifica trasparente con il valore di "data1"
Log.d("TAG", "data1:" + dato1); //credo sia una specie di debug
// String salve = getIntent().getExtras().getString("ciao");
// System.out.println("questo è il valore della prima variabile" +salve);
//FARE CONTROLLO IN CASO IL FILE XML E' VUOTO E QUINDI LA STRINGA E' VUOTA
String[] arr = dato1.split("\\|");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " => " + arr[i]);
}
final ArrayList <String> listp = new ArrayList<String>();
for (int i = 0; i < arr.length; ++i) {
listp.add(arr[i]);
}
// recupero la lista dal layout
final ListView mylist = (ListView) findViewById(R.id.listView1);
// creo e istruisco l'adattatore
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listp);
// inietto i dati
mylist.setAdapter(adapter);
Button b_load=(Button)findViewById(R.id.button_send2);
b_load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openTrack = new Intent(Page1.this, Track.class);
startActivity(openTrack);
}
});
}
This is the code of Track.java:
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
And this is the code of the xml file associate to Track.java, called "activity_track.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="In attesa di essere localizzati..."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:id="#+id/locationText"/>
</RelativeLayout>
This is LogCat's code:
08-08 00:04:23.801 2217-2217/com.example.giacomob.myapplication I/art﹕ Not late-enabling -Xcheck:jni (already on)
08-08 00:04:24.035 2217-2234/com.example.giacomob.myapplication I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398620, error=EGL_SUCCESS
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Root element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ ----------------------------
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ [ 08-08 00:04:25.762 2217: 2217 I/System.out ]
Current Element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Coordinata X : 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Naziome : Italia
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Paese : Cannole
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Via : Piazza San Vincenzo
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 0 => 1
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1 => 2
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 2 => Italia
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 3 => Cannole
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 4 => Piazza San Vincenzo
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa511b960, error=EGL_SUCCESS
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398900, error=EGL_SUCCESS
08-08 00:04:26.893 2217-2217/com.example.giacomob.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.giacomob.myapplication, PID: 2217
java.lang.RuntimeException: Unable to resume activity {com.example.giacomob.myapplication/com.example.giacomob.myapplication.Track}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at com.example.giacomob.myapplication.Track.onResume(Track.java:39)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2978)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This is the update of Track.java
package com.example.giacomob.myapplication;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
// private LocationManager locationManager=null;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
private static final int MIN_DIST = 20;
private static final int MIN_PERIOD = 30000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
// LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
I don't understand the reason for witch the app is closed! Please, help me! Thanks
You never instantiate your LocationManager reference. This must be done in onCreate like this:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
The app crashes due to a Null Pointer Exception.
The answer of andrewdleach is correct; and the exact line to add in onCreate is this:
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
EDIT:
ok, try to use this
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener
{
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (locationManager == null)
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
{
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
if (locationManager != null)
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
Related
I am building an android app and on the main layout i have 3 Image Buttons which when clicked they must each open a new activity.
When I run the app and pressed on them the app crushes. this is the code i am using:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton converterbtn = (ImageButton)findViewById(R.id.btnConvert);
ImageButton placesbtn = (ImageButton)findViewById(R.id.imagBtnPlace);
ImageButton weatherbtn = (ImageButton)findViewById(R.id.imgbtnweather);
//Open Weather Activity
if (weatherbtn.isPressed() == true) {
weatherbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), weather_mainActivity.class);
startActivity(intent);
}
}); //Open Currency Activity
}else if (converterbtn.isPressed() == true) {
converterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), CurrencyConverter_MainActivity.class);
startActivity(intent1);
}
});//Open Places Activity
} else if (placesbtn.isPressed()) {
placesbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), Places_mainActivity.class);
startActivity(intent1);
}
});
}
}
Manifest.xml
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
Any ideas why that happens? All the other posts ive checked are doing it with this way but on mine it doesnt seem to work.
Android Monitor log
01-08 03:00:58.288 22447-22447/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
01-08 03:01:01.127 1236-1547/? D/AudioFlinger: mixer(0xf4480000) throttle end: throttle time(56)
01-08 03:01:01.151 1550-21914/? D/OpenGLRenderer: endAllStagingAnimators on 0x7f0b1b83d400 (RippleDrawable) with handle 0x7f0b1b8bb540
01-08 03:01:01.192 1550-1954/? D/GraphicsStats: Buffer count: 3
Weather_MainActivity.java
package com.android.example.cwapp;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class weather_mainActivity extends AppCompatActivity {
public static final String TAG = weather_mainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
LocationManager locationManager;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
#InjectView(R.id.humidityValue)TextView mHumidityValue;
#InjectView(R.id.precipValue)TextView mPrecipValue;
#InjectView(R.id.summaryLabel)TextView mSummaryLabel;
#InjectView(R.id.iconImageView)ImageView mIconImageView;
#InjectView(R.id.refreshImageView)ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#InjectView(R.id.locationLabel)TextView mLocation;
public double latitude /*= 34.7720*/;
public double longitude /*= 32.4297*/;
//Location Manager
private boolean checkLocation() {
if (!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private final LocationListener locationListenerBest = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "6180f6e1b6747c1da3cb4638ea9d2961";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
float temp = mCurrentWeather.getTemperature();
String temp2 = Float.toString((temp - 32) * (5 / 9));
mTemperatureLabel.setText(temp2 + "");
mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
mLocation.setText(mCurrentWeather.getTimeZone());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment_weather dialog = new AlertDialogFragment_weather();
dialog.show(getFragmentManager(), "error_dialog");
}
};
RUN Log
01-09 21:29:30.827 5610-5610/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.827 5610-5610/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.864 5610-5627/? E/art: Thread attaching while runtime is shutting down: Binder_2
01-09 21:29:30.869 5614-5614/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.870 5614-5614/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.916 1548-1596/? E/InputDispatcher: channel '6ba3a14 com.android.example.cwapp/com.android.example.cwapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-09 21:29:31.830 5633-5633/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:31.830 5633-5633/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:32.033 1195-1309/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
01-09 21:29:33.170 1921-2145/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xedc344f0
01-09 21:30:01.551 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819a240
01-09 21:30:02.902 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8310
01-09 21:30:04.739 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819b580
01-09 21:30:06.655 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8380
01-09 21:30:08.253 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1bed700
01-09 21:30:09.115 5641-5641/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.example.cwapp, PID: 5641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.example.cwapp/com.android.example.cwapp.Places_mainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.android.example.cwapp.Places_mainActivity.onCreate(Places_mainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
01-09 21:30:11.307 1548-1601/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1c8f020
01-09 21:30:11.326 1548-1937/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
Add CurrentWeather.class activity in your mainfest like this
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
<activity android:name=".CurrentWeather"/>
You should display your stack trace, but you don't need View.OnClickListner, not sure if that's causing it, but just have weatherbtn.setOnClickListener(new OnClickListener() {...
Other than that, there isn't anything wrong with how you're calling your activity.
Hello how are you? I'm creating an android app news and is working very well, the only problem is when I'm doing the reading of the text and minimize the app to do something else and then return the app presents this error.
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: FATAL EXCEPTION: main
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at java.util.ArrayList.get(ArrayList.java:304)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory.setAdapterToListview(ActivityDetailStory.java:179)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:171)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:119)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:631)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:153)
part of the error
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ActivityDetailStory extends AppCompatActivity {
int position;
String str_cid, str_cat_id, str_cat_image, str_cat_name, str_title, str_image, str_desc, str_date;
TextView news_title, news_date;
WebView news_desc;
ImageView img_news, img_fav;
DatabaseHandler db;
List<ItemStoryList> arrayOfRingcatItem;
ItemStoryList objAllBean;
final Context context = this;
ProgressBar progressBar;
LinearLayout content;
private AdView mAdView;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_story);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(Constant.CATEGORY_TITLE);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
content = (LinearLayout) findViewById(R.id.content);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
img_fav = (FloatingActionButton) findViewById(R.id.img_fav);
img_news = (ImageView) findViewById(R.id.image);
news_title = (TextView) findViewById(R.id.title);
news_date = (TextView) findViewById(R.id.subtitle);
news_desc = (WebView) findViewById(R.id.desc);
db = new DatabaseHandler(ActivityDetailStory.this);
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet!", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemStoryList objItem = new ItemStoryList();
objItem.setCId(objJson.getString(Constant.CATEGORY_ITEM_CID));
objItem.setCategoryName(objJson.getString(Constant.CATEGORY_ITEM_NAME));
objItem.setCategoryImage(objJson.getString(Constant.CATEGORY_ITEM_IMAGE));
objItem.setCatId(objJson.getString(Constant.CATEGORY_ITEM_CAT_ID));
objItem.setNewsImage(objJson.getString(Constant.CATEGORY_ITEM_NEWSIMAGE));
objItem.setNewsHeading(objJson.getString(Constant.CATEGORY_ITEM_NEWSHEADING));
objItem.setNewsDescription(objJson.getString(Constant.CATEGORY_ITEM_NEWSDESCRI));
objItem.setNewsDate(objJson.getString(Constant.CATEGORY_ITEM_NEWSDATE));
arrayOfRingcatItem.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
//if(arrayOfRingcatItem.size()>0) {
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
str_cat_image = objAllBean.getCategoryImage();
str_cat_id = objAllBean.getCatId();
str_title = objAllBean.getNewsHeading();
str_desc = objAllBean.getNewsDescription();
str_image = objAllBean.getNewsImage();
str_date = objAllBean.getNewsDate();
news_title.setText(str_title);
news_date.setText(str_date);
news_desc.setBackgroundColor(Color.parseColor("#FFFFFF"));
news_desc.setFocusableInTouchMode(false);
news_desc.setFocusable(false);
news_desc.getSettings().setDefaultTextEncodingName("UTF-8");
WebSettings webSettings = news_desc.getSettings();
Resources res = getResources();
int fontSize = res.getInteger(R.integer.font_size);
webSettings.setDefaultFontSize(fontSize);
String mimeType = "text/html; charset=UTF-8";
String encoding = "utf-8";
String htmlText = str_desc;
String text = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///android_asset/Roboto-Light.ttf\")}body {font-family: MyFont;font-size: medium; color: #525252;}</style></head><body>"
+ htmlText + "</body></html>";
news_desc.loadData(text, mimeType, encoding);
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id))
;
{
img_fav.setImageResource(R.drawable.ic_bookmark_white);
}
}
img_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
db.AddtoFavorite(new Pojo(str_cat_id, str_cid, str_cat_name, str_title, str_image, str_desc, str_date));
Toast.makeText(getApplicationContext(), "Leitura Marcada", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_white);
interstitial = new InterstitialAd(ActivityDetailStory.this);
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
AdRequest adRequest = new AdRequest.Builder().build();
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id)) {
db.RemoveFav(new Pojo(str_cat_id));
Toast.makeText(getApplicationContext(), "Leitura desmarcada!", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
}
}
}
});
//}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_story, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
case R.id.menu_share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Estou lendo vários livro com esse app estou adorando, baixe já, Recomendo "+"https://play.google.com/store/apps/details?id="+getPackageName());
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
#Override
protected void onPause() {
// mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
//mAdView.resume();
}
#Override
protected void onDestroy() {
//mAdView.destroy();
super.onDestroy();
}
}
You should do this:
public void setAdapterToListview() {
if(arrayOfRingcatItem.size>0){
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
}
}
EDIT: onResume()
#Override
protected void onResume(){
super.onResume();
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
Or you can save the array in the Application class and use it from there, or in a singleton. The error it's because when the activity go to background Android can release some memory and delete your array.
EDIT 2: You can use SharedPreferences to save the id.
You have to put this code in onCreate:
SharedPreferences opc=getSharedPreferences("AppName", 0);
SharedPreferences.Editor editor =opc.edit();
editor.putInt("ID_SAVED",NEWS_ITEMID); editor.commit();
And in the onResume:
SharedPreferences opc=getSharedPreferences("AppName", 0);
NEWS_ITEMID=opc.getInt("ID_SAVED", -1);
Based on what you stated above everything is working fine except:
minimize the app to do something else and then return the app presents this error
You may need to reinitialize code in:
#Override
public void onResume(){
super.onResume();
// put your code here to repopulate arraylist...
refreshMyData();
}
refreshMyData could have:
public void refreshMyData(){
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
Use this method in your oncreate as well, that way you can have the same method call when creating the activity and resuming.
Sources:
How to use onResume()?
i'm currently working on android maps by following this tutorial http://developer.android.com/training/location/retrieve-current.html, and i keep getting error.there are 4 warnings and i tried to fix it but when i run it again the error message fatal exception still showing
here's the warning messages:
1. the message servicesConnected() from the type LokasiKampus is never used locally
2. the value of local variable kampus is not used
3. the value of local variable laboratorium is not used
4.the value of local variable myCurrentLocation is not used
here's my Java code
package ninth.example.dteinformationcenter;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class LokasiKampus extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
static final LatLng Kampus = new LatLng (-7.775038, 110.373253);
static final LatLng Laboratorium = new LatLng (-7.765437, 110.374496);
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap map;
private GooglePlayServicesClient myLocationClient;
public static class ErrorDialogFragment extends DialogFragment {
private Dialog mDialog;
public ErrorDialogFragment() {
super();
mDialog = null;
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
public void show(FragmentManager supportFragmentManager, String tag) {
// TODO Auto-generated method stub
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
switch(resultCode) {
case Activity.RESULT_OK : break;
}
}
}
**private boolean servicesConnected()** {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d("Location Updated", "Google Play Services is available");
return true;
} else {
Dialog ErrorDialog = GooglePlayServicesUtil
.getErrorDialog(resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (ErrorDialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(ErrorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lokasi_kampus);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.lokasikampus)).getMap();
if (map != null) {
**Marker kampus = map.addMarker(new MarkerOptions().position(Kampus)
.title("Kampus "));
Marker laboratorium = map.addMarker(new MarkerOptions().position(Laboratorium)
.position(Laboratorium)
.title("Laboratorium")
);**
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Kampus, 18));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
LocationClient myLocationClient = new LocationClient(this,this,this);
**Location myCurrentLocation;
myCurrentLocation = myLocationClient.getLastLocation();**
}
#Override
public void onConnected(Bundle dataBundle) {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
Toast.makeText(this, "Disconnected, please re-connect", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch(IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStart() {
super.onStart();
myLocationClient.connect();
}
#Override
protected void onStop() {
myLocationClient.disconnect();
super.onStop();
}
}
this is the error message
FATAL EXCEPTION: main
Process: ninth.example.dteinformationcenter, PID: 1443
java.lang.RuntimeException: Unable to start activity ComponentInfo{ninth.example.dteinformationcenter/ninth.example.dteinformationcenter.LokasiKampus}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
at com.google.android.gms.internal.hb.cn(Unknown Source)
at com.google.android.gms.internal.jg.b(Unknown Source)
at com.google.android.gms.internal.jg$c.cn(Unknown Source)
at com.google.android.gms.internal.jf.getLastLocation(Unknown Source)
at com.google.android.gms.internal.jg.getLastLocation(Unknown Source)
at com.google.android.gms.location.LocationClient.getLastLocation(Unknown Source)
at ninth.example.dteinformationcenter.LokasiKampus.onCreate(LokasiKampus.java:112)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
when i put reverse geocoder function into service class and trying to call in activity ,, i got null pointer exception ..
this is my class
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String tempAddress;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
location = locationManager
.getLastKnownLocation(locationProvider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
String locationgps=LocationManager.GPS_PROVIDER;
location = locationManager
.getLastKnownLocation(locationgps);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS/Data roaming is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public String getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
double latitude=getLatitude();
double longitude=getLongitude();
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
Toast.makeText(getApplicationContext(),"I am at: "+strAddress.toString(),Toast.LENGTH_LONG).show();
// myAddress.setText("I am at: " +strAddress.toString());
tempAddress=strAddress.toString();
return tempAddress;
//Intent intent = new Intent("MyCustomIntent");
// add data to the Intent
// intent.putExtra("strAddress",strAddress.toString());
// intent.setAction("android.provider.Telephony.SMS_RECEIVED");
// sendBroadcast(intent);
// Intent intent = new Intent (Menu.this,IncomingSms.class);
// intent.putExtra("strAddress",strAddress.toString());
// sendBroadcast(intent);
}
else
Toast.makeText(getApplicationContext(), "No Location found", Toast.LENGTH_LONG).show();
//myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Tidak bisa Menerima Alamat ,, harap cek jaringan dan gps hp anda!", Toast.LENGTH_LONG).show();
showSettingsAlert();}
tempAddress="Could not Retrive Address!";
return tempAddress;
}
}
and this is my activity class:
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import javax.xml.transform.Templates;
import mo.locationtracking.GPSTracker;
import mo.sms.IncomingSms;
import info.MonitoringObjek.R;
import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Menu extends Activity implements OnClickListener{
private Button bTambah;
private Button bLihat;
//private Button blokasi;
GPSTracker gps;
private TextView myAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
myAddress = (TextView)findViewById(info.MonitoringObjek.R.id.lokasisekarang);
// blokasi=(Button) findViewById(R.id.button_lokasi);
// blokasi.setOnClickListener(this);
bTambah = (Button) findViewById(R.id.button_tambah);
bTambah.setOnClickListener(this);
bLihat = (Button) findViewById(R.id.button_view);
bLihat.setOnClickListener(this);
// create class object
gps = new GPSTracker(Menu.this);
// check if GPS enabled
if(gps.canGetLocation()){
//double latitude = gps.getLatitude();
//double longitude = gps.getLongitude();
//Geocoder geocoder;
//myAddress.setText("Latitude: "+latitude+"Longitude: "+longitude);
String tempAddress=gps.getMyLocationAddress();
myAddress.setText("I am at: " +tempAddress);
gps.stopUsingGPS();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button_tambah :
Intent i = new Intent(this, CreateData.class);
startActivity(i);
break;
case R.id.button_view :
Intent i2 = new Intent(this, ViewData.class);
startActivity(i2);
break;
}
}
}
and this is my logcat:
05-28 14:47:14.187: E/Trace(5031): error opening trace file: No such file or directory (2)
05-28 14:47:14.688: E/AndroidRuntime(5031): FATAL EXCEPTION: main
05-28 14:47:14.688: E/AndroidRuntime(5031): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.MonitoringObjek/mo.database.Menu}: java.lang.NullPointerException
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.access$600(ActivityThread.java:137)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.os.Handler.dispatchMessage(Handler.java:99)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.os.Looper.loop(Looper.java:213)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.main(ActivityThread.java:4786)
05-28 14:47:14.688: E/AndroidRuntime(5031): at java.lang.reflect.Method.invokeNative(Native Method)
05-28 14:47:14.688: E/AndroidRuntime(5031): at java.lang.reflect.Method.invoke(Method.java:511)
05-28 14:47:14.688: E/AndroidRuntime(5031): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
05-28 14:47:14.688: E/AndroidRuntime(5031): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
05-28 14:47:14.688: E/AndroidRuntime(5031): at dalvik.system.NativeStart.main(Native Method)
05-28 14:47:14.688: E/AndroidRuntime(5031): Caused by: java.lang.NullPointerException
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.location.GeocoderParams.<init>(GeocoderParams.java:50)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.location.Geocoder.<init>(Geocoder.java:83)
05-28 14:47:14.688: E/AndroidRuntime(5031): at mo.locationtracking.GPSTracker.getMyLocationAddress(GPSTracker.java:213)
05-28 14:47:14.688: E/AndroidRuntime(5031): at mo.database.Menu.onCreate(Menu.java:54)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.Activity.performCreate(Activity.java:5008)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
05-28 14:47:14.688: E/AndroidRuntime(5031): ... 11 more
i see inthis post it's say geocoder must declare inside on create in activity .. is that impossible to declare in service class? i need that geocoder still update even my application is closed..
The Location from the android application is not that much accurate you can call the google api webservice using get method and parse the json result and you can get Area Block city street etc
it is more accurate than default one
I am playing around with working with the location but now i keep on getting a nullPointerException when ever i click the button on the app. The button refreshes the location which is displayed. The location is displayed in latitude,longitude, street address,city,country and postal address. here is the code below.
package com.example.metrorails;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
CurrentPosition currentPosition;
String address;
String city;
String country;
String postalCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button refresh;
refresh = (Button)findViewById(R.id.refresh);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentPosition = new CurrentPosition(MainActivity.this);
TextView showresults = (TextView) findViewById(R.id.show_results);
showresults.setTextSize(20);
if(currentPosition.canGetLocation()){
double latitude = currentPosition.getLatitude();
double longitude = currentPosition.getLongitude();
showresults.setText("current latitude: "+latitude +"\n current longitude: "+longitude+
"\n Address is: " +currentPosition.getAddress() + "\n city is: "+currentPosition.getCity()+
"\n Current Country is: "+currentPosition.getCountry() +"\n Area Code : "+currentPosition.getPostalCode());
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
currentPosition.showSettingsAlert();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I'm still having problems with this program. here is the logcat below.
09-09 18:56:52.393: E/AndroidRuntime(1882): FATAL EXCEPTION: main
09-09 18:56:52.393: E/AndroidRuntime(1882): java.lang.NullPointerException
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.location.GeocoderParams. <init>(GeocoderParams.java:50)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.location.Geocoder.<init>(Geocoder.java:83)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.example.metrorails.CurrentPosition.<init>(CurrentPosition.java:71)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.example.metrorails.MainActivity$1.onClick(MainActivity.java:31)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.view.View.performClick(View.java:4240)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.view.View$PerformClick.run(View.java:17721)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Handler.handleCallback(Handler.java:730)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Handler.dispatchMessage(Handler.java:92)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Looper.loop(Looper.java:137)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-09 18:56:52.393: E/AndroidRuntime(1882): at java.lang.reflect.Method.invokeNative(Native Method)
09-09 18:56:52.393: E/AndroidRuntime(1882): at java.lang.reflect.Method.invoke(Method.java:525)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-09 18:56:52.393: E/AndroidRuntime(1882): at dalvik.system.NativeStart.main(Native Method)
09-09 18:57:01.512: I/Process(1882): Sending signal. PID: 1882 SIG: 9
below is the CurrentPosition class.
package com.example.metrorails;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class CurrentPosition extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
public static String address;
public static String city;
private static String country;
private static String postalCode;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public String getAddress(){
return address;
}
public String getCity(){
return city;
}
public String getCountry(){
return country;
}
public String getPostalCode(){
return postalCode;
}
public CurrentPosition(Context context) {
this.mContext = context;
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Geocoder geocode = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocode.getFromLocation(latitude,longitude, 1);
this.address = addresses.get(0).getAddressLine(0);
this.city = addresses.get(0).getAddressLine(1);
this.country = addresses.get(0).getAddressLine(2);
this.postalCode = addresses.get(0).getPostalCode();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}} catch (Exception e) {
e.printStackTrace();
}
this.location = location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(CurrentPosition.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}