Why wont my onClick work? - android

It seems like my onClick is malfunctioning, the text won't change when I click it and the button is still enabled after a click.
I'm trying to get a button that (when pressed by the user) updates the location.
Here's my code:
public class Search extends ActionBarActivity {
private double[][] values_gps = new double[100][1];
private Location location;
private TextView textLat;
private TextView textlong;
private Context mContext;
private double CurrentLatitude = 0;
private double CurrentLongitude = 0;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new myLocationListener();
Button refresh = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
textLat = (TextView)findViewById(R.id.Lat);
textlong = (TextView)findViewById(R.id.Long);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
refresh.setEnabled(false);
refresh.setText("SEARCHING");
}
});
}
class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
textLat.setText(Double.toString(location.getLatitude()));
textlong.setText(Double.toString(location.getLongitude()));
lm.removeUpdates(ll);
refresh.setEnabled(true);
refresh.setText("SEARCH");
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}

Button refresh = (Button) findViewById(R.id.button);
must be called after setContentView

Related

How to use a constructer of java class into fragment?

[![enter image description here][1]][1]HI all I am having a problem can anyone tell me how do I resolve this , I want to use a constructer in fragment class:
here is my both classes
AppLocationService:
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#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;
}
}
here is fragment:
public class AddressFragment extends Fragment {
Button ShowAddress;
TextView tvAddress;
AppLocationService appLocationService;
public AddressFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_address, container, false);
tvAddress = (TextView) rootView.findViewById(R.id.input_location);
appLocationService = new AppLocationService(
AddressFragment.this);
ShowAddress = (Button) rootView.findViewById(R.id.btn_location);
ShowAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
//you can hard-code the lat & long if you have issues with getting it
//remove the below if-condition and use the following couple of lines
//double latitude = 37.422005;
//double longitude = -122.084095
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
} else {
showSettingsAlert();
}
}
});
return rootView;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AddressFragment.this);
alertDialog.setTitle("SETTINGS");
alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
AddressFragment.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
break;
default:
locationAddress = null;
}
tvAddress.setText(locationAddress);
}
}
// Inflate the layout for this fragment
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
To answer your question; A Fragment does not derive from Context. To let your code compile, you should change this
appLocationService = new AppLocationService(
AddressFragment.this);
To this
appLocationService = new AppLocationService(getActivity());
However, you should never call a constructor of a Service yourself. You should start it with Context#startService(Intent) (in your case getActivity().startService(new Intent(getActivity(), AppLocationService.class)). To supply any parameters for your service, take a look at Intent#putExtra(String, String)

hi I am getting error "cannot resolve method locationmanager.requestLocationUpdates();

Sir,
thanks for your help, here is the complete code of my program.
hi I am getting error "cannot resolve method locationmanager.requestLocationUpdates();
public class MainActivity extends Activity implements LocationListener {
public Button button;
private TextView textView;
public LocationManager locationmanager;
Context context;
private double lat,lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationmanager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//error !!!!!!
**Error ** locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,this);
}
});
}
#Override
public void onLocationChanged(Location location) {
if(location!=null)
{
lat=location.getLatitude();
lon=location.getLongitude();
textView.append("\n lat:"+lat+" lon:"+lon);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
First, do not use "gps". Use LocationManager.GPS_PROVIDER.
Second, this does not match any signature for requestLocationUpdates(). this is a View.OnClickListener, not a LocationListener or a PendingIntent.
If this code is from an activity or fragment, and that activity or fragment is implementing LocationListener, this MyActivity.this instead of this, where MyActivity is the name of the activity or fragment that is implementing LocationListener.

findViewById in non-Activity class

Still being relatively new to this I'm having issues in finding a view in a non-activity class MyLocation which I'm using in my activity class MainActivity. I'm using MyLocation to get longitude and latitude.
I want to highlight a textview when either GPS or Network has been used. To do so I need to find the textviews in the non-activity class MyLocation.
Here is how I'm calling it in MainActivity:
public class MainActivity extends ActionBarActivity implements LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
}
And here what I tried in MyLocation to find the textviews:
public class MyLocation {
LocationManager lm;
LocationResult locationResult;
private Context context;
TextView tvnetwork, tvgps;
private int defaultTextColor;
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.main, null);
tvnetwork = (TextView) v.findViewById(R.id.tvnetwork);
tvgps = (TextView) v.findViewById(R.id.tvgps);
defaultTextColor = tvgps.getTextColors().getDefaultColor();
tvnetwork.setTextColor(context.getResources().getColor(
R.color.green));
tvgps.setTextColor(defaultTextColor);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
But the views are not found. I already get a NPE # .getSystemService(Context.LAYOUT_INFLATER_SERVICE);. What am I doing wrong?
get a NPE # .getSystemService(Context.LAYOUT_INFLATER_SERVICE);. What
am I doing wrong?
Because context is null in MyLocation class. use MyLocation class constructor to pass MainActivity context in MyLocation to access system services as:
Activity activity;
public MyLocation(Context context,Activity activity){
this.context=context;
this.activity=activity;
}
and in MainActivity create MyLocation class object by passing MainActivity context as:
MyLocation myLocation = new MyLocation(MainActivity.this,this);
Now use context to access system services in MyLocation class
EDIT: Instead of inflating main layout again in onLocationChanged use Activity context to access view from Activity Layout as:
public void onLocationChanged(Location location) {
....
tvnetwork = (TextView) activity.findViewById(R.id.tvnetwork);
tvgps = (TextView) activity.findViewById(R.id.tvgps);
defaultTextColor = tvgps.getTextColors().getDefaultColor();
tvnetwork.setTextColor(context.getResources().getColor(
R.color.green));
tvgps.setTextColor(defaultTextColor);
....
}
Try this way,hope this will help you to solve your problem.
public class MainActivity extends ActionBarActivity implements LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyLocation myLocation = new MyLocation(this);
myLocation.getLocation(this, locationResult);
}
}
public class MyLocation {
LocationManager lm;
LocationResult locationResult;
private Context context;
TextView tvnetwork, tvgps;
private int defaultTextColor;
public void MyLocation(Context context) {
this.context = context;
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
View v = LayoutInflater.from(context).inflate(R.layout.main, null);
tvnetwork = (TextView) v.findViewById(R.id.tvnetwork);
tvgps = (TextView) v.findViewById(R.id.tvgps);
defaultTextColor = tvgps.getTextColors().getDefaultColor();
tvnetwork.setTextColor(context.getResources().getColor(
R.color.green));
tvgps.setTextColor(defaultTextColor);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
}
Why you want to do it in separate class as your are implementing "LocationListener" in Activity itself. And if you want to do in separate class. You can notify the activity by setting custom listners like this
public class MainActivity extends ActionBarActivity implements LocationListener,CustomListner {
TextView tvnetwork, tvgps;
private int defaultTextColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvnetwork = (TextView) v.findViewById(R.id.tvnetwork);
tvgps = (TextView) v.findViewById(R.id.tvgps);
defaultTextColor = tvgps.getTextColors().getDefaultColor();
MyLocation myLocation = new MyLocation(this); // pass listner in constructor
myLocation.getLocation(this, locationResult);
}
#Override
public void highlight(){
// update your view here.
tvnetwork.setTextColor(context.getResources().getColor(
R.color.green));
tvgps.setTextColor(defaultTextColor);
}
public class MyLocation {
LocationManager lm;
LocationResult locationResult;
CustomListner listner;
MyLocation(CustomListner listner){
this.listner = listner;
}
public interface CustomListner{
public void highlight();
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
listner.highlight();
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
}

Multiple onResume() when coming back to my activity from Home

When I am navigating out from my (main) activity and then coming back by clicking the icon on the Home screen - the activity is automatically Resumed->Paused->Resumed.
I am expecting for only one onResume().
My activity creates an AsyncTask in the onResume() function (the activity is not calling to other activities at all) and currently two additional AsyncTasks are created instead of one.
I did some tests and noticed that it happens when this activity is declared as "SingleTask" in the Mainfest. With 'SingleTop" it goes fine and onResume() is called only once.
HELP!
This is my code of the main activity:
public class HomeFinderActivity extends ListActivity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
private Location location;
private static final String LOG_TAG = "::HomeFinderActivity->Asynctask";
private ArrayList<Home> home_parts = new ArrayList<Home>();
private ListViewAdapter m_adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// instantiate ListViewAdapter class
m_adapter = new ListViewAdapter(this, R.layout.row, home_parts);
setListAdapter(m_adapter);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
}
//Asynctask to retrieve cursor from database and sort list by distance
private class SortList extends AsyncTask<Location, Void, ArrayList<Home>> {
#Override
protected ArrayList<Home> doInBackground(Location... location) {
try {
if (home_parts.isEmpty()){
home_parts=Home.getHomeParts(location[0], getApplicationContext());
}
else{
for (Home d : home_parts){
if (location != null){
d.setmDistance((int) (d.getmLatitude()), d.getmLongitude(),(double) (location[0].getLatitude())
, (double) (location[0].getLongitude()));
}
}
}
} finally {
}
Collections.sort(home_parts, new Comparator(){
public int compare(Object o1, Object o2) {
Home p1 = (Home) o1;
Home p2 = (Home) o2;
return (int) p1.getmDistance()- (int) p2.getmDistance();
}
});
return home_parts;
}
protected void onPostExecute(ArrayList<Home> address) {
m_adapter = new ListViewAdapter(HomeFinderActivity.this, R.layout.row, address);
// display the list.
setListAdapter(m_adapter);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
//starting handling location
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
Log.e(LOG_TAG, "onResume() started");
if (location != null) {
onLocationChanged(location);
}
else
{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
Log.e(LOG_TAG, "onPause() started");
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
SortList showList = new SortList();
showList.execute(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
/** Called when the user clicks the Add Entry button */
public void goAddEntry(View view) {
Intent intent = new Intent(this, AddEntry.class);
startActivity(intent);
}
}

Accessing GPS using AsyncTask

Simply, I want to get current location and location changes through GPS via AsyncTask.
I have tried many ways out and also gone through many stuff related it, but cant help myself out. Here is my code, please suggest changes to make to the code.
public class MyGps extends Activity {
/** Called when the activity is first created. */
public static EditText txtLatitude;
public static EditText txtLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GpsAsyncTask gpsTask = new GpsAsyncTask(this, this);
gpsTask.execute(null);
}
}
public class GpsAsyncTask extends AsyncTask<String[], String, String> {
Context context;
Activity activity;
private LocationManager locationManager;
private Location currentLocation;
Double mlat, mlng;
public GpsAsyncTask(Activity act, Context ctx) {
context = ctx;
activity = act;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
String provider = Settings.Secure.getString (context.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps") || provider.contains("network"))
Toast.makeText(context, "Trying to connect GPS", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "GPS is not connected", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String[]... params) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0f, new LocationListener()
{
public void onLocationChanged(Location loc)
{
mlat=loc.getLatitude();
mlng=loc.getLongitude();
return;
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
});
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps") || provider.contains("network"))
{
MyGps.txtLatitude.setText(Double.toString(mlat));
MyGps.txtLongitude.setText(Double.toString(mlng));
}
}
}`

Categories

Resources