java Android中的调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11401385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:56:47  来源:igfitidea点击:

Calling Method in Android

javaandroid

提问by GK1667

I am trying to call a method I have written. It compiles except for one line...

我正在尝试调用我编写的方法。它编译除了一行...

public class http extends Activity {

httpMethod();            //will not compile



public void httpMethod(){
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://site/api/");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        String test = "hello";

        TextView myTextView = (TextView) findViewById(R.id.myTextView);
        myTextView.setText(test);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}    
}

I'm not the best java guy, but I would think calling the method like so would get a response. "Hello" is not displayed however...

我不是最好的 Java 人,但我认为像这样调用方法会得到响应。“你好”没有显示但是...

How do I properly call the method?

如何正确调用该方法?

回答by Jon Skeet

EDIT: Just to leave no-one in any doubt, this answer only addresses why you're getting a compile-time error. It does notaddress what you should be doing in which thread and at what time in Android.

编辑:只是为了让任何人都没有任何疑问,这个答案只解决了为什么你会遇到编译时错误。它没有解决您应该在 Android 中的哪个线程以及何时执行的操作。

Personally I would recommend that you put Android down for the moment, learn Java in a simpler environment (e.g. console apps) and then, when you're comfortable with the language, revisit Android and learn all the requirements of Android development - which are obviously much more than just the language.

我个人建议您暂时放下 Android,在更简单的环境(例如控制台应用程序)中学习 Java,然后,当您熟悉该语言时,重新访问 Android 并学习 Android 开发的所有要求 - 这显然是不仅仅是语言。



You're trying to call a method as a statement directly within your class. You can't do that - it has to be part of a constructor, initializer block, other method, or static initializer. For example:

您试图在类中直接将方法作为语句调用。你不能这样做——它必须是构造函数、初始化块、其他方法或静态初始化器的一部分。例如:

// TODO: Rename this class to comply with Java naming conventions
public class http extends Activity {
    // Constructor is able to call the method... or you could call
    // it from any other method, e.g. onCreate, onResume
    public http() {
        httpMethod();
    }

    public void httpMethod() {
        ....
    }
}

Note that I've onlygiven this example to show you a valid Java class. It doesn'tmean you should actually be calling the method from your constructor.

请注意,我给出这个示例只是为了向您展示一个有效的 Java 类。这并不意味着您实际上应该从构造函数中调用该方法。

回答by kosa

httpMethod();       

should be inside some other method/constructor (or) assigned to variable. I suspect your requirement might be calling calling httpMethod()in either onCreate()(or) onResume()because you are extending Activity.

应该在分配给变量的其他方法/构造函数(或)中。我怀疑你的要求可能会被调用调用httpMethod()在任一onCreate()(或)onResume()因为要扩展活动。

回答by Squonk

I think perhaps you need to learn more about Android Application Fundamentalsand in particular the Activityclass and the Activitylifecycle.

我认为您可能需要更多地了解 Android应用程序基础知识,尤其是Activity类和Activity生命周期。

Your first problem is related to attempting to set a test string on your TextView.

您的第一个问题与尝试在您的TextView.

DO NOT attempt to do this in any method which is called by the constructor. Perhaps more importantly, forget about ever defining a constructor (or constructors) for any class you create which extends Activity.

不要尝试在构造函数调用的任何方法中执行此操作。也许更重要的是,忘记为您创建的任何扩展类定义构造函数(或构造函数)Activity

In order to be able to manipulate the UI elements of an Activity, the content view must be inflated. This is done either implicitly using setContentView(...)or explicitly using LayoutInflater. It is most usual to do this in onCreate(...)and until this is done, attempting to use findViewById(...)will return null. This is why attempting to do anything with the UI from an Activityconstructor will fail unless you explicitly inflate your layout within the constructor (or another method called by it). I'm not sure it's even possible to inflate the layout at this point and it's certainly not something I'd recommend even if it is possible. As I said, forget about constructors for Activities.

为了能够操作 的 UI 元素Activity,内容视图必须膨胀。这是通过隐式使用setContentView(...)或显式使用来完成的LayoutInflater。最常见的onCreate(...)是这样做,直到完成,尝试使用findViewById(...)将返回null。这就是为什么尝试从Activity构造函数对 UI 执行任何操作都会失败的原因,除非您在构造函数(或由它调用的其他方法)中显式膨胀布局。我不确定此时是否可以扩大布局,即使可能,我也不推荐这样做。正如我所说,忘记Activities.

To do what you want to do (for test purposes) you would need to do something like...

要做你想做的事情(出于测试目的),你需要做一些类似的事情......

public class HttpActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        httpMethod();
    }

    public void httpMethod() {
        ...
    }
}

Your second problem, as Maxim's comment on your question, even though my example will work for older versions of Android, more recent versions will throw an exception if you attempt to perform network operations on the main thread (aka UI thread) as they are potentially time-consuming and can cause the thread to be blocked. As Maxim suggests you should do this with an AsyncTaskor on some other Threadthan the main (UI) thread.

你的第二个问题,正如Maxim对你的问题的评论,即使我的例子适用于旧版本的Android,如果你尝试在主线程(又名UI线程)上执行网络操作,更新的版本会抛出异常,因为它们可能是耗时且可能导致线程被阻塞。正如 Maxim 建议的那样,您应该使用AsyncTask或 在Thread主(UI)线程以外的其他线程上执行此操作。