简体   繁体   English

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

[英]How to call method from OnClickListener.onClick method ?

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);           
    }
}

please take a look at the above code.....what's wrong with the code . 请看一下上面的代码.....代码有什么问题。 When i click the button i get nothing. 当我点击按钮时我什么都没得到。 when i click the button i want to get the url of the first google result ...if someone can help me i will appreciate it 当我点击按钮我想得到第一个谷歌结果的网址...如果有人可以帮助我,我会很感激

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

Change the statement surrounded in the try statement to this. 将try语句中包含的语句更改为this。 This will ensure that the right class is being referenced to call the method. 这将确保引用正确的类来调用该方法。

I guess I'm to late to the party, but it might help someone else. 我想我要迟到了,但它可能会帮助别人。

You can't do a network operation on a main thread. 您无法在主线程上执行网络操作。 Your code fails silently with NetworkOnMainThreadException raised by the system. 您的代码在系统引发的NetworkOnMainThreadException静默失败。 If you run this code and check the LogCat output for your application you are going to notice the exception. 如果您运行此代码并检查应用程序的LogCat输出,您将注意到该异常。

Solution is to do a network operation on a worker thread. 解决方案是在工作线程上执行网络操作。 You could use an AsyncTask in this use case. 您可以在此用例中使用AsyncTask

Your code is correct, it just looks like there isn't any way for you to know the method is getting called. 你的代码是正确的,它看起来似乎没有任何方法让你知道该方法被调用。 Consider adding some sort of notification even to your doSomething() method so you can know if the method gets called. 考虑甚至向doSomething()方法添加某种通知,以便您可以知道该方法是否被调用。

Do something like this: 做这样的事情:

public  void doSomething() throws Exception {

        // Show toast when method is called:
        Toast.makeText(this, "doSomething() is getting called", Toast.LENGTH_LONG).show();

        // the rest of doSomthing()


    }

While the code looks correct, the button click listener may not be getting set if an error is occurring before the set listener block. 虽然代码看起来正确,但如果在设置的侦听器块之前发生错误,则可能无法设置按钮单击侦听器。 Wrap your code in an error trap to determine if an error is occurring. 将代码包装在错误陷阱中以确定是否发生错误。 This is also good coding practice - especially when accessing external resources. 这也是很好的编码实践 - 特别是在访问外部资源时。

It may also be that the called method is erring and not completing the tasks. 它也可能是被调用的方法错误而没有完成任务。 You should put a trap in that procedure as well. 你也应该把陷阱放在那个程序中。

Sorry for my bad English. 对不起,我的英语不好。

Actually, you can get the current method's name with the StackTrace. 实际上,您可以使用StackTrace获取当前方法的名称。

Here is a sample: 这是一个示例:

public class Test {

 public static void main(String args[]) {
    trace(Thread.currentThread().getStackTrace());
    new Test().doit();
    trace(Thread.currentThread().getStackTrace());
 }

 public void doit() {
    trace(Thread.currentThread().getStackTrace());
    doitagain();
 }

 public void doitagain() {
    trace(Thread.currentThread().getStackTrace());
 }

 public static void trace(StackTraceElement e[]) {
   boolean doNext = false;
   for (StackTraceElement s : e) {
       if (doNext) {
          System.out.println(s.getMethodName());
          return;
       }
       doNext = s.getMethodName().equals("getStackTrace");
   }
 }

}

I forgot to mention that this approach may not work in all circumstances. 我忘了提到这种方法可能不适用于所有情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM