从远程sqlserver检索数据到android应用程序

时间:2016-01-27 14:11:10

标签: c# android json web-services

我想在我的Android应用程序中显示来自远程sql-server的数据。我正在使用网络服务。我能够连接和插入但不能用JSON显示。

这是来自网络服务的代码

 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;
}

1 个答案:

答案 0 :(得分:0)

我会使用Fiddler或类似的东西,看一下返回的数据。我一直无法从服务返回.NET Datatable,所以如果是我,我会在发送之前将数据表转换为JSON。之前已在几个帖子中对此进行了讨论,但这里有一个很好的答案: https://stackoverflow.com/a/17398078/3299157