我试着打电话给我写的方法.它编译除了一行...
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不是最好的java人,但我认为调用这样的方法会得到回应.然而,"Hello"没有显示......
我该如何正确调用该方法?
编辑:只是为了不让任何人怀疑,这个答案只解决了为什么你得到一个编译时错误.它并没有解决,你应该在哪个线程,并在Android的什么时间做什么.
就个人而言,我建议您暂时放下Android,在更简单的环境中学习Java(例如控制台应用程序)然后,当您对该语言感到满意时,重新访问Android并了解Android开发的所有要求 - 这显然是不仅仅是语言.
您试图直接在类中调用方法作为语句.你不能这样做 - 它必须是构造函数,初始化程序块,其他方法或静态初始化程序的一部分.例如:
// 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() {
....
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我只给出了这个示例来向您展示一个有效的Java类.这并不意味着您实际上应该从构造函数中调用该方法.