简体   繁体   中英

Implementing onClickListener not working

I am trying to connect a button that when it is pressed the Latitude and Longitude is displayed. It doesn't seem to be working and can't seem to figure out why. Any help would be appreciated.

ShowActivityLocation.java:

package com.democo.android.locationapi.simple;

import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ShowLocationActivity extends Activity implements LocationListener    {
private TextView latitudeField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_location); // Your main activity
latitudeField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);

StrictMode.ThreadPolicy policy = new 
        StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);    

// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

// Initialize the location fields
if (location != null) {
  System.out.println("Provider " + provider + " has been selected.");
  onLocationChanged(location);
} else {
  latitudeField.setText("Location not available");
  longitudeField.setText("Location not available");
}
}

@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);
    Button btngetLoc = (Button) findViewById(R.id.getLoc);

    btngetLoc.setOnClickListener(new OnClickListener() {

        public void onClick(View view) {
            onLocationChanged();
        }

    });
    return true;
 }

 /* Request updates at startup */
 @Override
 protected void onResume() {
 super.onResume();
 locationManager.requestLocationUpdates(provider, 400, 1, this);
 }

 /* Remove the locationlistener updates when Activity is paused */
 @Override
 protected void onPause() {
 super.onPause();
 locationManager.removeUpdates(this);
 }

 @Override
 public void onLocationChanged(Location location) {
 int lat = (int) (location.getLatitude());
 int lng = (int) (location.getLongitude());
 latitudeField.setText(String.valueOf(lat));
 longitudeField.setText(String.valueOf(lng));

 new Thread(new Runnable() {
    @Override
    public void run() {
        sendPosToServer(location.getLatitude(), location.getLongitude());
 }
 }).run();

 }

 public void sendPosToServer(double lat, double lon) {
  URL url;
  HttpURLConnection conn;
  BufferedReader rd;

  String fullURL="http://10.0.2.2:8080/LocationRecorder/UploadLocation'lat='+lat+'lon='+lon";

  try {
        Log.i(“SendPos”,"Sending request for sensor data to: "+fullURL);
    url = new URL(fullURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
    // Issue the GET to send the data
    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        // read the result to process response and ensure data sent
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        rd.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

   }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {
 // TODO Auto-generated method stub

 }

 @Override
 public void onProviderEnabled(String provider) {
 Toast.makeText(this, "Enabled new provider " + provider,
    Toast.LENGTH_SHORT).show();

  }

 @Override
 public void onProviderDisabled(String provider) {
 Toast.makeText(this, "Disabled provider " + provider,
    Toast.LENGTH_SHORT).show();
 }
 }

Layout XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" 
tools:context=".MainActivity" >

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="40dip"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="5dip"
        android:text="Latitude: "
        android:textSize="20dip" >
    </TextView>

    <TextView
        android:id="@+id/TextView02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="unknown"
        android:textSize="20dip" >
    </TextView>
</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/TextView03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="5dip"
        android:text="Longitude: "
        android:textSize="20dip" >
    </TextView>

    <TextView
        android:id="@+id/TextView04"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="unknown"
        android:textSize="20dip" >
    </TextView>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <Button
        android:id="@+id/getLoc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Location" 
        android:onClick="clickFunc"
        />

</LinearLayout>

For starters your button isn't within your layout page linear layout,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linearLayout1" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2">

    </LinearLayout>

    <LinearLayout >

        <Button
        android:id="@+id/getLoc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Location" 
        //android:onClick="clickFunc"
        />
    </LinearLayout>
// Add this
</LinearLayout>

Also you need to add this to your onCreate method, take it out of your onCreateOptionsMenu()

Then in the oncreate():

Button btngetLoc = (Button) findViewById(R.id.getLoc);

.../...
});

And as mentioned removed android:onClick="clickFunc" as you don't have this method and you have created an onclicklistener for the button.


You call:

onLocationChanged();

Which takes the parameter Location location

 public void onLocationChanged(Location location) {

so none of the following code will work:

int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latitudeField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));

I would be inclined to make Location location a class variable intialised to null (as it would by default) and then in your methods using location check for

if(location!=null)

Beyond this, I think if you get this working to this stage, I suggest asking a new question, as it's getting a bit long. Try and deal with the following two issues separately:

  1. How you are getting your location (test it /log it to see if you are getting a location)

  2. Online communication (run separate tests to see if your communication code is working)

You will find this much easier to debug.

So if your app is still crashing after the edits, I suggest you post a create a Minimal, Complete, and Verifiable example . As I notice in your screen shot you are changing bits of your code all over the place and it is impossible to answer in this situation.

Please include your logcat.

As cw fei said you've already set the OnClickListener so you should remove the definition from the XML file.

Additionally, it looks like you are calling onLocationChanged() on the button press. This will have no real effect since this method is called every time your GPS location changes. This, in turn, is going to call sendPosToServer() when your location changes.

Maybe you want to call sendPosToServer() on the button press and simply have onLocationChanged() store the new long and lat in a class variable?

you use the Thread.run(),It will block the UI thread. you should use Thread.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM