2016-01-27 53 views
1

我想在我的android應用程序中顯示來自我的遠程sql服務器的數據。我正在使用網絡服務。我能夠連接並插入,但不能用JSON顯示。從遠程sqlserver檢索數據到android應用程序

這是來自Web的服務的代碼

public DataTable RequestDetails(string request_name) 
    { 
     DataTable requestDetails = new DataTable(); 
     requestDetails.Columns.Add(new DataColumn("Request ID", typeof(String))); 
     requestDetails.Columns.Add(new DataColumn("Date", typeof(String))); 

     if(dbConnection.State.ToString() == "Closed") 
     { 
      dbConnection.Open(); 
     } 

     string query = "select ID_Requests,request_date from Requests where request_by='" + request_name + "'"; 

     SqlCommand command = new SqlCommand(query, dbConnection); 
     SqlDataReader reader = command.ExecuteReader(); 

     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       requestDetails.Rows.Add(reader["Request ID"], reader["Date"]); 
      } 
     } 

     reader.Close(); 
     dbConnection.Close(); 
     return requestDetails; 
    } 

這是Android代碼:

protected class AsyncLoadDeptDetails extends 
     AsyncTask<DeptTable, JSONObject, ArrayList<DeptTable>> { 
    ArrayList<DeptTable> deptTable = null; 

    @Override 
    protected ArrayList<DeptTable> doInBackground(DeptTable... params) { 
     // TODO Auto-generated method stub 

     RestAPI api = new RestAPI(); 
     try { 

      JSONObject jsonObj = api.RequestDetails(params[1].getName()); 

      JSONParser parser = new JSONParser(); 

      deptTable = parser.parseDepartment(jsonObj); 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      Log.d("AsyncLoadDeptDetails", e.getMessage()); 

     } 

     return deptTable; 
    } 

    @Override 
    protected void onPostExecute(ArrayList<DeptTable> result) { 
     // TODO Auto-generated method stub 

     for (int i = 0; i < result.size(); i++) { 
      data.add(result.get(i).getNo() + " " + result.get(i).getName()); 
     } 

     adapter.notifyDataSetChanged(); 

     Toast.makeText(context, "Loading Completed", Toast.LENGTH_SHORT).show(); 
    } 

} 

而且JSONParser代碼:

public ArrayList<DeptTable> parseDepartment(JSONObject object) 
{ 
    ArrayList<DeptTable> arrayList=new ArrayList<DeptTable>(); 
    try { 
     JSONArray jsonArray=object.getJSONArray("Value"); 
     JSONObject jsonObj=null; 
     for(int i=0;i<jsonArray.length();i++) 
     { 
      jsonObj=jsonArray.getJSONObject(i); 
      arrayList.add(new DeptTable(jsonObj.getInt("Request ID"), jsonObj.getString("Date"))); 
     } 

    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     Log.d("JSONParser => parseDepartment", e.getMessage()); 
    } 
    return arrayList; 
} 

回答

0

我會用菲德勒什麼類似,並看看正在返回的數據。我一直無法從服務中返回.NET Datatable,所以如果是我,我會在發送之前將數據錶轉換爲JSON。這已在幾個帖子之前討論過,但這裏有一個很好的答案: https://stackoverflow.com/a/17398078/3299157

相關問題