2013-05-23 2 views
0

저는 json을 사용하여 ror 웹 사이트에서 가져 와서 listview에 표시하는 안드로이드 응용 프로그램을 만들었습니다. 지금은 우리 응용 프로그램의 데이터를 추가하고 싶습니다. 우리의 listview에 표시해야합니다. 애플 리케이션도 누른 다음 웹 사이트에 표시해야합니다. 어떻게 우리의 애플 리케이션에 게시 방법과 디스플레이를 사용합니다. json을 사용하여 android에서 post 메서드를 사용하는 방법

난에 포스트 방법을 추가 할 같은 목적을 위해 내가 get 메소드를 사용하여도 표시하고 그

public class MainActivity extends ListActivity implements FetchDataListener 
{ 
    private ProgressDialog dialog; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     //setContentView(R.layout.activity_list_item); 
     initView(); 
    } 

    private void initView() 
    { 
     // show progress dialog 
     dialog = ProgressDialog.show(this, "", "Loading..."); 
     String url = "http://floating-wildwood-1154.herokuapp.com/posts.json"; 
     FetchDataTask task = new FetchDataTask(this); 
     task.execute(url); 
    } 

    @Override 
    public void onFetchComplete(List<Application> data) 
    { 
     // dismiss the progress dialog 
     if (dialog != null) 
      dialog.dismiss(); 
     // create new adapter 
     ApplicationAdapter adapter = new ApplicationAdapter(this, data); 
     // set the adapter to list 
     setListAdapter(adapter); 
    } 

    @Override 
    public void onFetchFailure(String msg) 
    { 
     // dismiss the progress dialog 
     if (dialog != null) 
      dialog.dismiss(); 
     // show failure message 
     Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); 
    } 
} 

fetchdatatask.java이 같이

public class FetchDataTask extends AsyncTask<String, Void, String> 
{ 
    private final FetchDataListener listener; 
    private String msg; 

    public FetchDataTask(FetchDataListener listener) 
    { 
     this.listener = listener; 
    } 

    @Override 
    protected String doInBackground(String... params) 
    { 
     if (params == null) 
      return null; 
     // get url from params 
     String url = params[0]; 
     try 
     { 
      // create http connection 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet httpget = new HttpGet(url); 
      // connect 
      HttpResponse response = client.execute(httpget); 
      // get response 
      HttpEntity entity = response.getEntity(); 
      if (entity == null) 
      { 
       msg = "No response from server"; 
       return null; 
      } 
      // get response content and convert it to json string 
      InputStream is = entity.getContent(); 
      return streamToString(is); 
     } 
     catch (IOException e) 
     { 
      msg = "No Network Connection"; 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String sJson) 
    { 
     if (sJson == null) 
     { 
      if (listener != null) 
       listener.onFetchFailure(msg); 
      return; 
     } 
     try 
     { 
      // convert json string to json object 
      JSONObject jsonObject = new JSONObject(sJson); 
      JSONArray aJson = jsonObject.getJSONArray("post"); 
      // create apps list 
      List<Application> apps = new ArrayList<Application>(); 
      for (int i = 0; i < aJson.length(); i++) 
      { 
       JSONObject json = aJson.getJSONObject(i); 
       Application app = new Application(); 
       app.setContent(json.getString("content")); 
       // add the app to apps list 
       apps.add(app); 
      } 
      //notify the activity that fetch data has been complete 
      if (listener != null) 
       listener.onFetchComplete(apps); 
     } 
     catch (JSONException e) 
     { 
      e.printStackTrace(); 
      msg = "Invalid response"; 
      if (listener != null) 
       listener.onFetchFailure(msg); 
      return; 
     } 
    } 

    /** 
    * This function will convert response stream into json string 
    * 
    * @param is 
    *   respons string 
    * @return json string 
    * @throws IOException 
    */ 
    public String streamToString(final InputStream is) throws IOException 
    { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     try 
     { 
      while ((line = reader.readLine()) != null) 
      { 
       sb.append(line + "\n"); 
      } 
     } 
     catch (IOException e) 
     { 
      throw e; 
     } 
     finally 
     { 
      try 
      { 
       is.close(); 
      } 
      catch (IOException e) 
      { 
       throw e; 
      } 
     } 
     return sb.toString(); 
    } 
} 

처럼 사용할 방법을 얻을 수 있습니다 android listview에 표시되고 웹 사이트에도 표시됩니다.

추가 버튼과 같은 메뉴 버튼을 클릭하면 하나의 페이지가 표시됩니다. 해당 페이지에서 데이터를 추가하고 저장을 클릭하면 목록보기 및 게시물에 표시해야합니다. 웹 사이트에서도

어떻게 할 수 있습니까?

답변

0

당신은 HttpPost

@Override 
protected String doInBackground(String... params) 
{ 
    if (params == null) 
     return null; 
    // get url from params 
    String url = params[0]; 
    try 
    { 
     // create http connection 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost request = new HttpPost(url); 
     try{ 
    StringEntity s = new StringEntity(json.toString()); //json is ur json object 
    s.setContentEncoding("UTF-8"); 
    s.setContentType("application/json"); 
    request.setEntity(s); 
    request.addHeader("Accept", "text/plain"); //give here your post method return type 

    HttpResponse response = client.execute(request); 
     // get response 
     HttpEntity entity = response.getEntity(); 
     if (entity == null) 
     { 
      msg = "No response from server"; 
      return null; 
     } 
     // get response content and convert it to json string 
     InputStream is = entity.getContent(); 
     return streamToString(is); 
+0

감사 아슈에 연결되어있는 목록이 코드가 충분하거나 좀 더 필요하다? –

+0

이것은 서버에 데이터를 보내는 코드입니다. json 객체를 사용할 수있는 서버에 post 메소드를 작성해야합니다. – Ashu

+0

실제로 버튼을 클릭하면 팝업 버튼이 추가됩니다. 클릭하면 새로운 하나의 edittexbox가있는 활동을 보여 주며 서버에 가져 오는 방법과 저장 방법을 표시합니다. 우리가 서버 또는 db에 저장할 수있는 목록보기, –

0

을 사용할 수 있습니다 취할해야하는 주요 단계는 다음과 같습니다

가 서버에 데이터를 게시하는 안드로이드 응용 프로그램에 코드를 추가합니다.
온라인으로하는 방법에 대한 예제가 많이 있습니다. 한 가지 예가 있습니다 : How to send POST request in JSON using HTTPClient?

보내는 JSON 데이터를 관리 할 수있는 웹 서비스가 있습니다.
이 작업을 수행하는 방법은 사용중인 서버 측 기술에 따라 다릅니다.

업데이트하여 ListView에

+0

이다, 나는 이것도 서버 측에서하고 싶다. –

0
  public void postData() { 
// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new  
HttpPost("http://abcd.wxyz.com/"); 

try { 
    List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("IDToken1", "username")); 
    nameValuePairs.add(new BasicNameValuePair("IDToken2", "password")); 


    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

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

    if(response != null) { 

     int statuscode = response.getStatusLine().getStatusCode(); 

     if(statuscode==HttpStatus.SC_OK) { 
     String strResponse = EntityUtils.toString(response.getEntity()); 

     } 
    } 

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

나는이 코드를 어떻게 추가해야하는지, listview에서 그것을 가져와야 만한다. , 내가 무엇을 추가하는지 –

+0

서비스를 실행 한 후 HttpResponse를 반환하고 응답을 문자열로 변환하면 구문 분석 할 수 있습니다. –

관련 문제