【发布时间】:2014-07-27 06:10:57
【问题描述】:
当代码在没有扩展活动和 oncreate 方法调用的情况下运行时会报错:
public class RequestActivity {
//extends Activity{
//protected void onCreate(android.os.Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://www.example.com/login");
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
//following error in below 2 lines
//========errors:=================
//Multiple markers at this line
//- Syntax error on token "add", = expected after this token
//- Syntax error on token(s), misplaced construct(s)
nameValuePair.add(new BasicNameValuePair("email", "user@gmail.com"));
nameValuePair.add(new BasicNameValuePair("message",
"Hi, trying Android HTTP post!"));
//==============================================
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
}
当类通过活动扩展并将代码放在 oncreate 方法中时,它运行良好。那么为什么这在以前的情况下不起作用。
错误在代码中被标记为注释。
完整代码的要点: https://gist.github.com/prashantdawar/72f86fa497b677e1bc85
【问题讨论】:
-
但是为什么你在
Activity中运行这段代码呢?最好创建separate class或AsyncTask来运行此代码.... -
我建议您阅读 Android 文档或 google 获取 Android 教程。
-
就是这样。创建独立类时,它会给出上面代码中描述的错误。 @MD
-
创建一个独立的类而没有活动给出错误。它关于数据结构而不是关于活动。 @代码学徒
-
你得到什么错误?我们应该猜测吗?
标签: java android list android-activity