2012-09-11 132 views
1

我想將檢索到的數據從服務器發送到我的Android客戶端...我使用json對象來完成此操作。這是我的servlet代碼。在servlet中創建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); 
    } 


} 

}

,這是我的Android端代碼..

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

你在哪裏得到「無數據發現「在服務器端或Android端的異常? – ponraj

+0

請重新格式化代碼..刪除不必要的導入和過多的代碼。使它清脆,易於閱讀。 – Nishant

+0

@ ponraj-它顯示在屏幕上...在這裏它添加爲Toast.makeText(getBaseContext(),「No Data Found」,Toast.LENGTH_LONG).show(); – Dasaya

回答

4

您的servlet只返回N個JSON對象。但是,你給予JSON陣列響應它可能是錯誤嘗試在你的servlet這段代碼

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 done Bro ...最好的..它的工作:D:D在你的代碼中有一些小的錯誤,jArray.put(i,arrayObj);它應該更正爲jArray.add(i,arrayObj); 再次感謝:D:D:D – Dasaya

+1

雅我現在更新感謝:) – ponraj

+0

謝謝@ColdHack我更新了我的答案。 – ponraj

0

在處理json字符串(轉換爲json對象)之前打印來自服務器的響應,以便您可以跟蹤實際原因。你真的得到了json異常。

0

在寫入outputstream之後,您需要這樣關閉Printwriter對象。

out.close() 
0

您需要JSON-LIB-2.4-jdk15.jar文件添加到您的項目類路徑和使用下面的代碼創建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數據:{ 「KEY1」: 「值3」, 「值1」, 「KEY2」: 「值2」, 「KEY3」}