我知道存在这样的问题,但在这种情况下我很困惑。我正在使用以下代码:
package com.example.GetALocation2;
import com.example.GetALocation2.MyLocation.LocationResult;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class GetALocation2 extends Activity {
public static final String LOG_TAG = "------------------GetALocation2";
Double latitude;
TextView tv;
MyLocation myLocation = new MyLocation();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.thetext);
tv.setText("Yo there!");
Log.e(LOG_TAG, "Toast will be shown");
Toast.makeText(getBaseContext(), "This is the start!", Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "Toast was shown");
locationClick();
}
private void locationClick() {
Log.e(LOG_TAG, "Triggered location click");
myLocation.getLocation(this, locationResult);
}
public void yoThereNull(){
Toast.makeText(getBaseContext(), "Location is unknown.", Toast.LENGTH_SHORT).show();
}
public void yoThereNotNull(){
Toast.makeText( getBaseContext(), "I got the location! Yeah! >>> " + GetALocation2.this.latitude, Toast.LENGTH_SHORT).show();
}
public LocationResult locationResult = new LocationResult(){
@Override
public void gotLocation(final Location location){
//Got the location!
Log.d(LOG_TAG, "Entered gotLocation()");
try{
if( location == null ){
Log.d( LOG_TAG, "Null Location is returned" );
yoThereNull();
}else{
Log.d( LOG_TAG, "A location is found/returned" );
GetALocation2.this.latitude = location.getLatitude();
yoThereNotNull();
}
}catch (NullPointerException e) {
Log.e(LOG_TAG, e.toString());
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
};
};
}
当location返回null并调用yoThereNull()方法时,logcat说:在没有调用looper.prepare的线程内创建处理程序
但是当location返回一个值时,一切正常。吐司出现了。
在我的情况下,任何人都知道如何处理这个问题?我是java和android的新手,非常感谢任何帮助! :)
答案 0 :(得分:6)
可以替换
吗?yoThereNotNull();
带
GetALocation2.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
yoThereNotNull();
}
});
答案 1 :(得分:0)
您在此行中遇到问题:
Toast.makeText( getBaseContext(), "I got the location! Yeah! >>> " + GetALocation2.this.latitude, Toast.LENGTH_SHORT).show();
尝试使用该活动。
Toast.makeText( this, "I got the location! Yeah! >>> " + GetALocation2.this.latitude, Toast.LENGTH_SHORT).show();
答案 2 :(得分:0)
当你在另一个线程内手动创建一个线程时会发生这个错误等等。这是Android无法处理的一个条件。这就是为什么他们给出了一个名为AsyncTask
的东西,你可以用它来做在背景中做的事情..当这个ecxeption arrises你不能总是说你的代码中有错误..有时你的代码是干净的但仍然Android操作系统将抛出此异常。所以一定要使用AsyncTask而不是创建一个Thread by自己..