2011-05-11 50 views
0

我是Android編程的新手。我試圖用post發佈一些數據到服務器。我GOOGLE了它,並用此想出了:postData無法解析爲類型

public void postData() { 
    // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 
     try { 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
      nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

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

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

    } 

我的問題是我得到這個代碼的第一行錯誤:

  • POSTDATA不能被解析爲一個類型
  • 語法令牌「{」,刪除標記「無效」,@此令牌
  • 語法錯誤錯誤預期

我使用Eclipse和我使用d Shift + Ctrl + o獲取所有導入。

+0

你的錯誤可能是高於此行...你缺少@Override或關閉大括號...等等... – forsvarir 2011-05-11 20:09:07

+0

能告訴你的整個代碼? – 2011-05-11 20:09:14

回答

1

你的問題(根據你迄今給出的信息)是你在類的外部聲明瞭功能postData

Java中的函數需要在類中聲明。或者,你意外地關閉了以前的班級,因爲有太多的}(在這種情況下,你應該在額外的}上有錯誤),或者你還沒有申報班級。

的類可以是這個樣子:

public class MyPoster { 

    public void postData() { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 
     try { 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
      nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

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

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

    } 
} 
+0

謝謝你的幫助。我試着把這個函數放在一個類中,但它仍然給我一個錯誤。經過一番閱讀,我終於明白了問題所在。我只發佈了一部分代碼。整個事情都在onCreate方法中。當我將它移到外面時,它開始工作:) – 2011-05-12 17:44:56