gpt4 book ai didi

android - 如何从 OnClickListener.onClick 方法调用方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:07:49 24 4
gpt4 key购买 nike

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLEncoder;

import com.google.gson.Gson;

import android.app.Activity;
import android.os.Bundle;

import android.view.View;

import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class SampleActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
doSomething();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void doSomething() throws Exception {
EditText search2 = (EditText)findViewById(R.id.editText1);
TextView urltext = (TextView)findViewById(R.id.textView1);
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search = search2.toString() + "site:mysite.com";
String charset = "UTF-8";

URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
String voidurlresult = results.getResponseData().getResults().get(0).getUrl().toString();
urltext.setText(voidurlresult);
}
}

请看一下上面的代码.....代码有什么问题。当我点击按钮时,我什么也得不到。当我点击按钮时,我想获得第一个谷歌结果的 url ...如果有人能帮助我,我将不胜感激

最佳答案

button.setOnClickListener(new View.OnClickListener()   {             
public void onClick(View v) {
try {
SampleActivity.this.doSomething();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

把try语句包围的语句改成这个。这将确保引用正确的类来调用该方法。

关于android - 如何从 OnClickListener.onClick 方法调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7813718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com