实现onClickListener无法正常工作

时间:2015-12-08 01:08:53

标签: java android

我正在尝试连接一个按钮,按下按钮时会显示纬度和经度。它似乎没有工作,似乎无法弄清楚为什么。任何帮助将不胜感激。

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();
 }
 }

布局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>

3 个答案:

答案 0 :(得分:1)

对于初学者,您的按钮不在布局页面线性布局中,

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

此外,您需要将此添加到您的onCreate方法,将其从onCreateOptionsMenu()中取出

然后在oncreate()中:

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

.../...
});

如上所述删除android:onClick="clickFunc",因为您没有此方法,并且您已为该按钮创建了onclicklistener。

你打电话:

onLocationChanged();

参数Location location

 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));

我倾向于将Location location一个类变量初始化为null(默认情况下),然后在使用位置检查的方法中

if(location!=null)

除此之外,我认为如果你让这个工作到这个阶段,我建议问一个新问题,因为它有点长。分别尝试和处理以下两个问题:

  1. 如何获取您的位置(测试/记录它以查看您是否获得了位置)

  2. 在线交流(运行单独的测试以查看您的通信代码是否正常工作)

  3. 您会发现这更容易调试。

    因此,如果您的应用在编辑后仍然崩溃,我建议您发布create a Minimal, Complete, and Verifiable example。正如我在屏幕截图中注意到的那样,你在整个地方都在改变你的代码,在这种情况下无法回答。

    请包含您的logcat。

答案 1 :(得分:0)

正如cw fei所说,你已经设置了OnClickListener所以你应该从XML文件中删除定义。

此外,您似乎在按下按钮时呼叫onLocationChanged()。这将没有实际效果,因为每次GPS位置更改时都会调用此方法。反过来,这会在您的位置发生变化时拨打sendPosToServer()

也许您想在按下按钮时调用sendPosToServer(),只需让onLocationChanged()将新的long和lat存储在类变量中?

答案 2 :(得分:0)

你使用Thread.run(),它将阻止UI线程。你应该使用Thread.start();