2015-12-08 90 views
3

我試圖連接一個按鈕,當它被按下時,顯示的是經度和緯度。它似乎沒有工作,似乎無法弄清楚爲什麼。任何幫助,將不勝感激。實現onClickListener不工作

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> 

回答

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()添加到您的onCreate方法,把它拿出來你的onCreateOptionsMenu()

的:

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類變量intialised爲空(因爲它會在默認情況下),然後在

if(location!=null) 

超過這個使用位置簽到你的方法,我認爲,如果你得到這個工作,到這個階段,我建議問一個新的問題,因爲它有點長。嘗試和處理以下兩個單獨的問題:

  1. 你如何讓你的位置(測試/日誌,看看是否你得到一個位置)

  2. 在線交流(單獨運行測試看看你的通信代碼是否工作)

你會發現這更容易調試。

因此,如果您的應用在編輯後仍然崩潰,我建議您發佈create a Minimal, Complete, and Verifiable example。正如我在你的屏幕截圖中注意到的那樣,你正在改變你的代碼,並且在這種情況下無法回答。

請包括您的logcat。

+0

我已經做了你說的一切,但我仍然收到錯誤sendPosToServer();在onClick方法中 http://pastie.org/10617269 https://www.dropbox.com/s/do42e3r0193z0wf/Screen%20Shot%202015-12-08%20at%2002.06.05.png?dl = 0 – Tuks

+0

錯誤的sendPosToServer();是: 類型ShowLocationActivity中的sendPosToServer方法(double,double)不適用於參數() 並返回true的錯誤; 虛空方法無法返回值 – Tuks

+0

不知道爲什麼? :/ – Tuks

0

由於cw fei表示您已經設置了OnClickListener,所以您應該從XML文件中刪除定義。

此外,它看起來像你在按鈕上按onLocationChanged()。這將不會有實際效果,因爲每次您的GPS位置發生變化時都會調用此方法。當您的位置發生變化時,這又會調用sendPosToServer()

也許你想打電話sendPosToServer()在按鈕上按下,只需onLocationChanged()將新的long和lat存儲在類變量中?

+0

我已經做了你和cw fei建議的所有事情,但我仍然在onClick方法中發送sendPosToServer()錯誤,並且返回true。請看MrsEd的回答中的評論.. – Tuks

0

你使用Thread.run(),它會阻塞UI線程。你應該使用Thread.start();