来 self 的 previous question
我收到 NullPointor 异常。所以我对我的代码做了一些更改,现在显示了进度条,但出现以下错误。
11-17 23:39:51.373: ERROR/AndroidRuntime(495): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
11-17 23:39:51.373: ERROR/AndroidRuntime(495): java.lang.RuntimeException: An error occured while executing doInBackground()
11-17 23:39:51.373: ERROR/AndroidRuntime(495): at android.os.AsyncTask$3.done(AsyncTask.java:200)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): at java.lang.Thread.run(Thread.java:1096)
11-17 23:39:51.373: ERROR/AndroidRuntime(495): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
代码是...
public class JsonExampleActivity extends ListActivity {
/** Called when the activity is first created. */
ProgressDialog mDialog;
final String TAG="a.c.b";
JSONFunction JSONfunction;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
new JSONPasingShowList().execute();
}
public void updateWithNewLocation(Location location2) {
if(location2!=null) {
double geoLat = location2.getLatitude();
double geoLng = location2.getLongitude();
}
}
class JSONPasingShowList extends AsyncTask<String, Integer,ArrayList<HashMap<String,String>>>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(JsonExampleActivity.this);
mDialog.setCancelable(true);
mDialog.setMessage("Loading...");
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setProgress(0);
mDialog.show();
}
@Override
protected ArrayList<HashMap<String,String>> doInBackground(String... params) {
double latitude[]=new double[20];
double longitude[]=new double[20];
String reference[]=new String[20];
double distance[]=new double[20];
LocationManager locationManager;
String context=Context.LOCATION_SERVICE;
locationManager=(LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
double geoLat = location.getLatitude();
Log.v(TAG, "hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"+geoLat);
double geoLng = location.getLongitude();
Log.v(TAG, "hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"+geoLng);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json=JSONFunction.getJSONfromURL("https://maps.googleapis.com/maps/api/place/search/json?location=37.422006,-122.084095&radius=1000&types=doctor&sensor=true&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
try{
JSONArray JArray = json.getJSONArray("results");
Log.v(TAG, "getting results");
for(int i=0;i<JArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = JArray.getJSONObject(i);
JSONObject location1=e.getJSONObject("geometry").getJSONObject("location");
latitude[i]=location1.getDouble("lat");
longitude[i]=location1.getDouble("lng");
reference[i]=e.getString("reference");
Log.v(TAG, reference[i]);
distance[i]=GetLatAndLng.gps2m(geoLat, geoLng,latitude[i] ,longitude[i]);
map.put("id", String.valueOf(i));
map.put("name", "" + e.getString("name"));
map.put("vicinity", "Address " + e.getString("vicinity")+" "+"Disance:"+distance[i]);
mylist.add(map);
} }catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
final Intent intent=new Intent(JsonExampleActivity.this ,GetLatAndLng.class);
Bundle b=new Bundle();
b.putStringArray("key", reference);
intent.putExtras(b);
return mylist;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
mDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(JsonExampleActivity.this, result , R.layout.listview,
new String[] { "name", "vicinity", },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
mDialog.dismiss();
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(JsonExampleActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
final Intent intent=new Intent(JsonExampleActivity.this ,GetLatAndLng.class);
intent.putExtra("clickedid",position);
startActivity(intent);
}
});
}
public class MySimpleAdapter extends SimpleAdapter {
public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
// TODO Auto-generated constructor stub
}
}
}
}
出了什么问题? 提前致谢!!!
最佳答案
Can't create handler inside thread that has not called Looper.prepare()
您正在从 doInBackground 内部访问 UI 线程上的某些内容。这是不允许的。
*编辑:我已经看到了一切。对我来说,最不寻常的是那些行:
updateWithNewLocation(location); // What does this do? Could you tell me?
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener); // I don't think this is it
尝试将所有这些位置更新内容移动到 onProgressUpdate 中。我在这里是瞎子,因为我看不到您的代码,但我猜测它对 UI 做了一些事情。试试这个:
@Override
protected void onProgressUpdate(Location... locations) {
super.onProgressUpdate(values);
updateWithNewLocation(location);
}
但正如我所说,我不确定,因为除非您在此处发布该代码,否则我不知道 updateWithNewLocation 的作用。
关于android - 异步任务执行 doInBackground() 时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8172338/
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake
我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe