2014-04-26 2 views
0

간단한 프로젝트를 수행하여 android를 배우고 있습니다. 레이아웃이 완료되었고 백엔드와 통신해야하는 시점에 있습니다. 전에 PHP/JSON을 많이 사용 해왔고 백엔드에서해야 할 일을 정확히 알고 있습니다. 다음 두 가지 질문이 있습니다.Android - 백엔드와 통신하십시오.

1 - JSON을 처리 할 때 사용해야하는 어댑터는 무엇입니까? 백엔드는 한 번에 10 개의 레코드를 보내고 다음 10 개를 스크롤하여 사용자가보기를 스크롤 할 때 데이터 세트가 변경되도록합니다.

2 - 사용하게됩니다. 포인트 1에서 언급 한 JSON 데이터를 얻으려면 HTTP가 필요하며, 앤드 로이드에서 백엔드와의 통신에 선호되는 방법이 있습니까?

Parse 또는 다른 클라우드 솔루션을 사용하고 싶지 않습니다.

답변

1

Android에는 JSON 구문 분석 기능과 HTTP 클라이언트가 내장되어 있습니다. 단계별 지침을 반환 된 JSON 데이터를 HTTP 요청을하고 구문 분석이이 유래 게시물을 살펴보십시오 :

How to parse JSON in Android

그러나,이 게시물 이전 DefaultHttpClient을 사용합니다. 이것은 Froyo 이하에서만 권장됩니다. 보다 새로운 코드의 경우 Google에서는 진저 브레드 및 상위 API 시스템에서 HttpURLConnection을 대신 사용하는 것이 좋습니다. 이들의 기능은 여기에 매우 유사하다 안드로이드의 HttpURLConnection의에 대한 참조입니다 :

HttpURLConnection | Android Developers

1
1. You will have to have a something which will communicate with the server for that just copy this code :- 

public class ConnectionClass 
{ 
    Context context; 
    public ConnectionClass(Context ctx) { 
     this.context=ctx; 
    } 
    public String connectToServer(String urlLink) 
    { 

     try 
     { 

      HttpClient client = new DefaultHttpClient(); 
      HttpPost http_get = new HttpPost(urlLink); 



      HttpResponse responses; 
      responses = client.execute(http_get); 
      if (responses != null) 
      { 
       InputStream in = responses.getEntity().getContent(); 
       String a = convertStreamToString(in); 
       return a; 
      } 

     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    String convertStreamToString(InputStream is) { 

     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try 
     { 
      while ((line = reader.readLine()) != null) 
      { 
       sb.append(line); 
      } 
     } 
     catch (Exception e) 
     { 

      //Toast.makeText(context, e.toString()+" io2", Toast.LENGTH_LONG).show(); 
     } 
     finally 
     { 
      try 
      { 
       is.close(); 
      } 
      catch (Exception e) 
      { 

      } 
     } 
     return sb.toString(); 
    } 
} 

2. To use that and keeping in mind dat newer version of android does not allow executing network operations on mainthread i will give a simple example to run on onCreate() of the activity using AsyncTask this is something like Ajax in web . 





    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     context=this; 
     ConnectionClass cc=new ConnectionClass(context); 
     new AsyncTask<String, Void, String>() 
     { 


      @Override 
      protected String doInBackground(String... arg) { 
       String data=cc.connectToServer(arg[0]); 
       return data; 
      } 

      protected void onPostExecute(String result) 
      { 
       super.onPostExecute(result); 
       try 
       { 
        JSONObject jobj=new JSONObject(result); 
        String idval=jobj.getString("id"); 
        Toast.makeToast(context,idval,2000).show(); 
       } catch (Exception e) 
       { 
        e.printStackTrace(); 
       } 
      } 
     }.execute("http://mydomain.com/fetchjson.php"); 

    } 
관련 문제