【问题标题】:list add error without activity in android列出在android中没有活动的添加错误
【发布时间】: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 classAsyncTask 来运行此代码....
  • 我建议您阅读 Android 文档或 google 获取 Android 教程。
  • 就是这样。创建独立类时,它会给出上面代码中描述的错误。 @MD
  • 创建一个独立的类而没有活动给出错误。它关于数据结构而不是关于活动。 @代码学徒
  • 你得到什么错误?我们应该猜测吗?

标签: java android list android-activity


【解决方案1】:

我怀疑问题是当您注释掉 onCreate() 方法时,您的代码不再是有效的 Java。请记住,代码必须放在 some 方法中。它可以是任何你想要的名字,不一定是onCreate

【讨论】:

  • 真的。但我不能投票给你,因为我的声誉由于 -ve 投票而下降到 15 分以下。喜欢给你点赞。
  • @devprashant 如果此答案有助于解决问题,请接受。您将获得 2 分并可以投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多