2012-09-11 3 views
1

검색된 데이터를 서버에서 안드로이드 클라이언트로 보내고 싶습니다. json 객체를 사용했습니다. 다음은 내 서블릿 코드입니다.서블릿에서 json 객체 만들기

import java.io.IOException; 
import java.io.PrintWriter; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import net.sf.json.JSONArray; 
import net.sf.json.JSONObject; 

    public class AvailabilityResponse extends HttpServlet { 

@Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 

    response.setContentType("application/json"); 
    PrintWriter out=response.getWriter(); 

     String br_id; 
     br_id=request.getParameter("branchname"); 

    try{ 
     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
      Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root"); 
      Statement st=con.createStatement(); 
      ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'"); 
      while(rs.next()){ 

     String s = rs.getString("atmbrno"); 
     String t = rs.getString("atmbrname"); 

     JSONObject arrayObj = new JSONObject(); 

     arrayObj.put("atmbrno",s); 
     arrayObj.put("atmbrname",t); 


     out.print(arrayObj); 
     } 
     rs.close(); 
     st.close(); 
      } 
    catch(Exception e){ 
      out.print(e); 
    } 


} 

}

그리고 이것은 내 안드로이드 사이드 코드입니다 ..

import java.util.ArrayList; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.ParseException; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.ClientProtocolException; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.content.Intent; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.os.Bundle; 

public class CheckAvailability extends Activity{ 

Button but1,but2; 
EditText brName; 
TextView txt1; 
String text; 


public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.availability); 

    brName =(EditText)findViewById(R.id.editText1); 
    but1 = (Button)findViewById(R.id.button5); 
    but2 = (Button)findViewById(R.id.button6); 
    txt1 = (TextView)findViewById(R.id.textView3); 



    but1.setOnClickListener(new View.OnClickListener(){ 

     public void onClick(View v){ 

      String result = null; 
      InputStream is = null; 
      StringBuilder sb=null; 

      ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 

      postParameters.add(new BasicNameValuePair("branchname", brName.getText().toString())); 

     //http post 
        try{ 
         HttpClient httpclient = new DefaultHttpClient(); 
         HttpPost httppost = new HttpPost("http://10.0.2.2:8080/hello/AvailabilityResponse"); 
         httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 
         HttpResponse response = httpclient.execute(httppost); 
         HttpEntity entity = response.getEntity(); 
         is = entity.getContent(); 
        }catch(Exception e){ 
         Log.e("log_tag", "Error in http connection"+e.toString()); 
        } 

     //convert response to string 
        try{ 
         BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
         sb = new StringBuilder(); 
         sb.append(reader.readLine() + "\n"); 
         String line="0"; 

          while ((line = reader.readLine()) != null) { 
           sb.append(line + "\n"); 
          } 
          is.close(); 
          result=sb.toString(); 

        }catch(Exception e){ 
         Log.e("log_tag", "Error converting result "+e.toString()); 
         } 

       //paring data 
         String atm_id; 
         String atm_name; 

         try{ 
         JSONArray jArray = new JSONArray(result); 
         JSONObject json_data=null; 

         for(int i=0;i<jArray.length();i++){ 
           json_data = jArray.getJSONObject(i); 
           atm_id=json_data.getString("atmbrno"); 
           atm_name=json_data.getString("atmbrname"); 

           //txt1.setText(atm_name); 
         } 

         }catch(JSONException e1){ 
          Toast.makeText(getBaseContext(), "No DATA Found", Toast.LENGTH_LONG).show(); 

         }catch (ParseException e1){ 
          e1.printStackTrace(); 
         } 





     } 
}); 

} }

하지만 난 그것을 실행할 때 항상 "데이터 없음"예외 날 수 있습니다 ... 어느 누구도 나를 도울 수 있습니까 ???

+0

당신이 데이터 "얻을 서버 쪽 또는 안드로이드 쪽에서 예외가 발견되었습니다. – ponraj

+0

코드를 다시 포맷하십시오. 불필요한 가져 오기와 과도한 코드를 제거하십시오. 선명하고 읽기 쉽도록하십시오. – Nishant

+0

@ ponraj- 화면에 표시 ... Toast.makeText (getBaseContext(), "No Data Found", Toast.LENGTH_LONG) .show(); – Dasaya

답변

4

서블릿은 N 개의 JSON 객체 만 반환합니다. 하지만 당신은

try{ 
    Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root"); 
      Statement st=con.createStatement(); 
      ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'"); 
      int i=0; 
      JSONArray jArray = new JSONArray(); 
      while(rs.next()){ 

     String s = rs.getString("atmbrno"); 
     String t = rs.getString("atmbrname"); 

     JSONObject arrayObj = new JSONObject(); 

     arrayObj.put("atmbrno",s); 
     arrayObj.put("atmbrname",t); 

     jArray.add(i,arrayObj); 
     i++; 
     } 
     rs.close(); 
     st.close(); 
     out.print(jArray); 
    } 
+2

Wel 완료 Bro ... U r 최고 ... 작동 중입니다. D : D ur 코드에 작은 문제가 있습니다. jArray.put (i, arrayObj); jArray.add (i, arrayObj);로 수정해야합니다. 다시 한번 감사드립니다. D : D : D – Dasaya

+1

나중에 감사합니다. – ponraj

+0

Thanks @ColdHack 답을 업데이트했습니다. – ponraj

0

실제 이유를 추적 할 수 있도록 json string (json 객체로 변환)을 처리하기 전에 서버의 응답을 인쇄하십시오. U는 실제로 json 예외를 얻고 있습니다.

0

outputstream에 글을 작성한 후 Printwriter과 같은 모양으로 닫아야합니다.

out.close() 
0

당신은 당신의 프로젝트 클래스 경로 및 사용에 다음과 같은 코드를 JSON-lib 디렉토리-2.4-jdk15.jar 파일을 추가 할 필요가 서블릿에서이 코드를 시도 그것은 실수가 될 수 있습니다 JSON 배열에 해당 응답을 제공 JSON 객체를 생성한다.

JSONObject jsonData = new JSONObject(); 
    jsonData.put("key1", "value1"); 
    jsonData.put("key2", "value2"); 
    jsonData.put("key3", "value3"); 
    System.out.println("JSON data: "+jsonData.toString()); 

콘솔 당신은 출력을 얻을 것이다 : JSON 데이터 : { "키 1": "VALUE3" "값 1", "키 2": "값 2", "KEY3"}

관련 문제