在Android的调用方法方法、Android

2023-09-04 05:06:09 作者:浪女动了情

我想打电话给我写了一个方法。它编译除了一个行...

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

我不是最好的Java的家伙,但我想调用该方法,像这样就得到了响应。 你好是不是然而,显示...

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...

我如何正确地调用该方法?

How do I properly call the method?

推荐答案

编辑:刚刚离开,没有人有任何怀疑,这个答案只针对为什么你得到一个编译时错误。它的没有的地址,你应该做的是哪个线程在什么时间在Android中。

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

我个人建议你把安卓下来的那一刻,学习Java的一个简单的环境(例如控制台应用程序),然后,当你熟悉的语言,重温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.

您正在尝试直接在你的类调用一个方法的声明。你不能做到这一点 - 它必须是一个构造的一部分,初始化块,其他的方法或静态初始化。例如:

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() {
        ....
    }
}

请注意,我的只有的给这个例子向您展示一个有效的Java类。它的不的意思是,其实你应该从你的构造函数调用的方法。

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