Java 将AsyncTask添加到onClick侦听器
我已经制作了一个与AsyncTask一起工作的程序,它在程序执行时打印JSON数据列表,但问题是我希望在按下按钮时执行它。如何将AsyncTask的结果放入onClick按钮侦听器?如何从onClick调用AsyncTaskJava 将AsyncTask添加到onClick侦听器,java,android,json,Java,Android,Json,我已经制作了一个与AsyncTask一起工作的程序,它在程序执行时打印JSON数据列表,但问题是我希望在按下按钮时执行它。如何将AsyncTask的结果放入onClick按钮侦听器?如何从onClick调用AsyncTask public class MainActivity extends ActionBarActivity implements LocationListener { double[] avstand; JSONArray jArray; Locat
public class MainActivity extends ActionBarActivity implements LocationListener {
double[] avstand;
JSONArray jArray;
LocationManager lm;
TextView lt, ln;
String provider;
Location l;
ListView list;
StasjonAdapter adapter;
ArrayList<Stasjoner> stasjonListe;
Button nButton;
TextView test;
GPSTracker gps;
Stasjoner stasjon;
double minValue;
String geoUri;
Button instButton;
Button bildeButton;
Button kjorTil;
Button visListe;
File mPhotoFile;
Uri mPhotoFileUri;
String mDisplayFolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.activity_main);
ln=(TextView)findViewById(R.id.visLong);
test=(TextView)findViewById(R.id.test);
lt=(TextView)findViewById(R.id.visLati);
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
//get latitude and longitude of the location
double lat= gps.getLatitude();
double lng= gps.getLongitude();
//display on text view
ln.setText(""+lng);
lt.setText(""+lat);
list = (ListView)findViewById(R.id.list);
stasjonListe = new ArrayList<Stasjoner>();
nButton = (Button)findViewById(R.id.button1);
instButton = (Button)findViewById(R.id.instillinger);
bildeButton = (Button)findViewById(R.id.bildeButton);
kjorTil= (Button)findViewById(R.id.button);
visListe = (Button)findViewById(R.id.visListe);
//new StasjonAsyncTask().execute("http://hotell.difi.no/?dataset=porsgrunn/elbilparkering?"); blogas url, jis grazina html puslapi, reikia daryt requesta i api endpoint, kuris grazina json
new StasjonAsyncTask().execute("http://hotell.difi.no/api/json/porsgrunn/elbilparkering?");
instButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Instillinger.class);
startActivity(intent);
}
});
nButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int value = (int) getMinValue(avstand);
test.setText(stasjonListe.get(value).getLatitude().toString());
test.setText(stasjonListe.get(value).getLongtitude().toString());
String geoURI = "geo:" + stasjonListe.get(value).getLatitude().toString() + ","+ stasjonListe.get(value).getLongtitude().toString() + "?z=";
Uri geo = Uri.parse(geoURI);
Intent geoMap = new Intent(Intent.ACTION_VIEW,geo);
startActivity(geoMap);
}
});
visListe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//StasjonAsyncTask
}
});
bildeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CustomCameraActivity.class);
startActivity(intent);
}
});
kjorTil.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" + gps.getLatitude() +"," + gps.getLongitude() + "&daddr=" + Double.parseDouble(stasjon.getLatitude()) +","+Double.parseDouble(stasjon.getLongtitude())));
startActivity(intent);
}
});
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
public class StasjonAsyncTask extends AsyncTask<String, Void, Boolean>{
@Override
protected Boolean doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
//HttpPost post = new HttpPost(urls[0]); api endpointas nepriima post requestu, pakeiciam i get
HttpGet get = new HttpGet(urls[0]);
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj = new JSONObject(data);
jArray = jObj.getJSONArray("entries");
avstand = new double[jArray.length()];
for(int i=0;i< jArray.length();i++){
stasjon = new Stasjoner();
JSONObject jRealObject = jArray.getJSONObject(i);
stasjon.setId(jRealObject.getString("id"));
stasjon.setKapasitet(jRealObject.getString("kapasitet"));
stasjon.setPlassering(jRealObject.getString("plassering"));
stasjon.setTilgjengelighet(jRealObject.getString("tilgjengelighet"));
stasjon.setBeskrivelse(jRealObject.getString("beskrivelse"));
stasjon.setNavn(jRealObject.getString("navn"));
stasjon.setLongtitude(jRealObject.getString("longitude"));
stasjon.setLatitude(jRealObject.getString("latitude"));
stasjon.setTilgang(jRealObject.getString("tilgang"));
stasjon.setTidsbegrensing(jRealObject.getString("tidsbegrensing"));
double dist = distance(Double.parseDouble(stasjon.getLatitude()), Double.parseDouble(stasjon.getLongtitude()), gps.getLatitude(),gps.getLongitude(), 'K');
stasjon.setAvstand(Double.toString(dist));
avstand[i]= dist;
stasjonListe.add(stasjon);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//Arrays.sort(avstand);
minValue = getMinValue(avstand);
//test.setText(Double.toString(minValue));
if(result== false){
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
} else {
StasjonAdapter adapter = new StasjonAdapter(getApplicationContext(),R.layout.rad, stasjonListe);
list.setAdapter(adapter);
}
}
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
public static double getMinValue(double[] numbers){
double minValue = numbers[0];
int minValueIndex = 0;
for(int i=1;i<numbers.length;i++){
if(numbers[i] < minValue){
minValue = numbers[i];
minValueIndex = i;
}
}
return minValueIndex;
}
}
公共类MainActivity扩展了ActionBarActivity实现了LocationListener{
双支架;
杰索纳雷·贾雷;
位置经理lm;
文本视图lt,ln;
字符串提供者;
地点l;
列表视图列表;
StatsJonaAdapter适配器;
ArrayList StatsJonliste;
按钮按钮;
文本视图测试;
全球定位系统;
Stasjoner stasjon;
双最小值;
字符串geoUri;
按钮指示按钮;
钮扣去毛刺;
按钮kjorTil;
按钮visListe;
文件mPhotoFile;
乌里·姆霍托菲利乌里;
字符串mDisplayFolder;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.activity_main);
ln=(TextView)findViewById(R.id.visLong);
test=(TextView)findViewById(R.id.test);
lt=(文本视图)findViewById(R.id.visLati);
gps=新的GP斯特拉克(MainActivity.this);
//检查是否启用了GPS
if(gps.canGetLocation()){
双纬度=gps.getLatitude();
double longitude=gps.getLongitude();
//\n用于新行
//Toast.makeText(getApplicationContext(),“您的位置是-\nLat:“+纬度+”\nLong:“+经度,Toast.LENGTH\u LONG).show();
}否则{
//找不到位置
//GPS或网络未启用
//要求用户在设置中启用GPS/网络
gps.showSettingsAlert();
}
//获取位置的纬度和经度
双纬度=gps.getLatitude();
double lng=gps.getLongitude();
//在文本视图上显示
ln.setText(“+lng”);
lt.setText(““+lat”);
list=(ListView)findViewById(R.id.list);
statsjonliste=newarraylist();
nButton=(按钮)findViewById(R.id.button1);
instButton=(按钮)findViewById(R.id.Installinger);
bildeButton=(按钮)findViewById(R.id.bildeButton);
kjorTil=(按钮)findviewbyd(R.id.Button);
visListe=(按钮)findViewById(R.id.visListe);
//新建StatsJonaSyncTask()。执行(“http://hotell.difi.no/?dataset=porsgrunn/elbilparkering?blogas url、jis grazina html puslapi、reikia daryt requesta i api端点、kuris grazina json
新建StatsJonaSyncTask()。执行(“http://hotell.difi.no/api/json/porsgrunn/elbilparkering?");
instButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
意向意向=新意向(MainActivity.this,Instillinger.class);
星触觉(意向);
}
});
nButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
int value=(int)getMinValue(avstand);
test.setText(statsjonliste.get(value.getLatitude().toString());
test.setText(statsjonliste.get(value.getLongtudity().toString());
字符串geoURI=“geo:”+stasjonListe.get(value).getLatitude().toString()+”,“+stasjonListe.get(value).getLongtentity().toString()+”?z=“;
urigeo=Uri.parse(geoURI);
意向geoMap=新意向(意向.行动视图,geo);
星触觉(geoMap);
}
});
visListe.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//StasjonAsyncTask
}
});
bildeButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
意向意向=新意向(MainActivity.this、CustomCameraActivity.class);
星触觉(意向);
}
});
kjorTil.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
意向意向=新意向(android.content.Intent.ACTION\u视图,
解析http://maps.google.com/maps?saddr=“+gps.getLatitude()+”、“+gps.getLatitude()+”&daddr=“+Double.parseDouble(statsjon.getLatitude())+”、“+Double.parseDouble(statsjon.getLongtude()));
星触觉(意向);
}
});
}
@凌驾
已更改位置上的公共无效(位置){
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
}
公共类StatsJonaSyncTask扩展了AsyncTask{
@凌驾
受保护的布尔doInBackground(字符串…URL){
试一试{
HttpClient=new DefaultHttpClient();
//HttpPost=新的HttpPost(URL[0]);api端点为nepriima post requestu,pakeiciam i get
HttpGet=新的HttpGet(URL[0]);
HttpResponse response=client.execute(get);
int status=response.getStatusLine().getStatusCode();
如果(状态==200){
HttpEntity=response.getEntity();
字符串数据=EntityUtils.toString(实体);
JSONObject jObj=新的JSONObject(数据);
jArray=jObj.getJSONArray(“条目”);
avstand=新的双精度[jArray.length()];
for(int i=0;ipublic class StasjonAsyncTask extends AsyncTask<String, Void, Boolean>{
private MainActivity myActivity;
public StasjonAsyncTask(MainActivity myActivity){
this.myActivity=myActivity;
}
...
new StasjonAsyncTask(this).execute("http://hotell.difi.no/api/json/porsgrunn/elbilparkering?");
visListe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//StasjonAsyncTask
new StasjonAsyncTask().execute("http://hotell.difi.no/api/json/porsgrunn/elbilparkering?");
}
});