【问题标题】:how to get json data from framework (Yii)如何从框架(Yii)获取 json 数据
【发布时间】:2013-11-11 07:49:03
【问题描述】:

我正在尝试从我使用 Yii 框架构建的网站获取 json 数据。

当我打开 mozilla 并转到 http://localhost/restayii/index.php/employee/getemployee?id 时,它会显示员工 json 数据。

这是我的员工 jsondata:

{"employee":[{"id":"1","departmentId":"1","firstName":"Hendy","lastName":"Nugraha","gender":"female","birth_date":"1987-03-16","marital_status":"Single","phone":"856439112","address":"Tiban Mutiara View ","email":"hendy.nugraha87@yahoo.co.id","ext":"1","hireDate":"2012-06-30 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"2","departmentId":"2","firstName":"Jay","lastName":"Branham","gender":"male","birth_date":"0000-00-00","marital_status":"Single","phone":"0","address":"","email":"jaymbrnhm@labtech.org","ext":"2","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"3","departmentId":"3","firstName":"Ahmad","lastName":"Fauzi","gender":"male","birth_date":"0000-00-00","marital_status":"Single","phone":"0","address":"","email":"ahmadfauzi@labtech.org","ext":"3","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"4","departmentId":"1","firstName":"Henny","lastName":"Lidya Simanjuntak","gender":"female","birth_date":"1986-01-27","marital_status":"Married","phone":"2147483647","address":"Tiban Mutiara View ","email":"henokh_v@yahoo.com","ext":"1","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"5","departmentId":"2","firstName":"sfg","lastName":"sfgsfg","gender":"male","birth_date":"2013-10-23","marital_status":"Single","phone":"356356","address":"sfgsfg","email":"sfgsfg","ext":"4","hireDate":"2012-05-30 00:00:00","leaveDate":"0000-00-00 00:00:00"}]}

这是在 Android Activity 上。

Akses_Server_Aktivity :

public class Akses_Server_Activity extends Activity {

static String url ;
static final String Employee_ID = "id";
static final String Employee_Dept_ID = "departmentId";
static final String Employee_First_Name = "firstName";
static final String Employee_Last_Name = "lastName";
static final String Employee_Gender = "gender";
static final String Employee_Birth_Date = "birth_date";
static final String Employee_Marital_Status = "marital_status";
static final String Employee_Phone_Number = "phone";
static final String Employee_Address = "address";
static final String Employee_Email = "email";
static final String Employee_Ext = "ext";
static final String Employee_Hire_Date = "hireDate";
static final String Employee_Leave_Date = "leaveDate";
JSONArray employee = null;
JSONObject json_object;
Button callService;
EditText ip;
HashMap<String, String> map = new HashMap<String, String>();
String get_ip;
ProgressDialog pDialog;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.service_resta);

    ip = (EditText)findViewById(R.id.ip_address);
    get_ip = ip.getText().toString();
    callService = (Button) findViewById(R.id.call_services);
    callService.setOnClickListener(new View.OnClickListener() {  
        @Override  
        public void onClick(View v) {
            try {
                // masuk ke class Task
                new Task().execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }  
    });
}

private class Task extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute(){
        super.onPreExecute();

        // tampilkan progress dialog
        pDialog = new ProgressDialog(Akses_Server_Activity.this);
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {

            JSONParser json_parse = new JSONParser();

            url = "http://10.0.2.2/restayii/protected/controllers/EmployeeController.php";
            employee= json_parse.GetJson(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result){
        // masuk ke method LoadEmployee()
        LoadEmployee();

    }
}

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

    // Constructor
    public JSONParser(){

    }

    public JSONObject GetJson(String url) {

        // masuk ke class myasyntask
        new MyAsynTask().execute();
        return jObj;

    }

    public class MyAsynTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {

            return null;
        }

        protected void onPostExecute(JSONArray Result){
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            try {
                jObj = new JSONArray(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

private void LoadEmployee(){
    try {
        employee = json_object.getJSONArray("employee");

        TableLayout table_layout =(TableLayout) findViewById(R.id.table_layout);
        table_layout.removeAllViews();
        int jml_baris = employee.length();
        String [][] data_employee = new String [jml_baris][13];
        for(int i=0;i<jml_baris;i++){
            JSONObject Result = employee.getJSONObject(i);
            data_employee[i][0] = Result.getString(Employee_ID);
            data_employee[i][1] = Result.getString(Employee_Dept_ID);
            data_employee[i][2] = Result.getString(Employee_First_Name);
            data_employee[i][3] = Result.getString(Employee_Last_Name);
            data_employee[i][4] = Result.getString(Employee_Gender);
            data_employee[i][5] = Result.getString(Employee_Birth_Date);
            data_employee[i][6] = Result.getString(Employee_Marital_Status);
            data_employee[i][7] = Result.getString(Employee_Phone_Number);
            data_employee[i][8] = Result.getString(Employee_Address);
            data_employee[i][9] = Result.getString(Employee_Email);
            data_employee[i][10] = Result.getString(Employee_Ext);
            data_employee[i][11] = Result.getString(Employee_Hire_Date);
            data_employee[i][12] = Result.getString(Employee_Leave_Date);
        }

        TableLayout.LayoutParams ParameterTableLayout = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
        for(int j=0; j<jml_baris; j++){  
            TableRow  table_row = new TableRow(null);  
            table_row.setBackgroundColor(Color.BLACK);  
            table_row.setLayoutParams(ParameterTableLayout);  
            TableRow.LayoutParams ParameterTableRow = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);  
            ParameterTableRow.setMargins(1,1,1,1);
            for(int kolom = 0; kolom < 13; kolom++){
                TextView TV= new TextView(null);
                TV.setText(data_employee[j][kolom]);  
                TV.setTextColor(Color.BLACK);  
                TV.setPadding(1, 4, 1, 4);  
                TV.setGravity(Gravity.LEFT);  
                TV.setBackgroundColor(Color.BLUE);  
                table_row.addView(TV,ParameterTableRow);  
            }   
            table_layout.addView(table_row); 
            pDialog.dismiss();
        }
    } catch (Exception e) {

    }
}

}

(在 Android 上)

问题是:

当这个应用程序启动时,我单击按钮刷新,它没有显示包含员工 json 数据的表行。但是logcat上也没有错误。我在 Task extends AsyncTask http://10.0.2.2/restayii/protected/controllers/EmployeeController.php 上的 url 有问题吗?

或者当我从 mozilla http://localhost/restayii/index.php/employee/getemployee?id 打开它时,我应该用相同的链接替换它吗?

编辑:

我已经在任务类扩展 AsyncTask 中将 url 更改为 http://localhost/restayii/index.php/employee/getemployee?id,但仍然不会从本地主机获取员工 json 数据。

请,任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: android json yii android-asynctask


    【解决方案1】:

    我已经找到答案了。我的问题是在子类 Task extends asyntask 和 jsonParser 子类中。

    private class Task extends AsyncTask<JSONObject, Void, JSONObject>{
        @Override
        protected JSONObject doInBackground(JSONObject... params) {
            try {
                JSONParser json_parser = new JSONParser();
                json_object = json_parser.getJson(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return json_object;
        }
    
        @Override
        protected void onPostExecute(JSONObject result){
            LoadEmployee(result);
        }
    }
    
    private class JSONParser {
        .....
        public JSONObject getJson(String url) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpget);
                BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
                StringBuffer hasil = new StringBuffer();
                String line = "";
                while ((line = rd.readLine()) != null) {
                    hasil.append(line);
                }
                json = hasil.toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jObj;
        }
    }
    

    现在我可以从我的 Yii 网络服务中获取所有 json 数据。希望它会帮助别人。

    【讨论】:

      【解决方案2】:

      我知道,调用 ajax 数据时必须刷新 android 屏幕... 也许这会给你指明方向......

      【讨论】:

      • 你能再具体一点吗?我还是这个 android 编程的新手
      • 我也是 :) 但我试图在 phonegap android 应用程序上获取 json 数据。我看到如果第一次加载页面,我可以看到数据。然后当我刷新数据时,没有错误,但我看不到数据。在谷歌上搜索问题后,我发现了一个关于这个问题的评论。它说如果您调用 ajax 数据,您需要刷新屏幕...
      • 抱歉回复晚了。那么我应该添加什么代码到这个应用程序中,让它刷新?我已经更改了网址,但仍然没有在表格行上显示任何 json 数据。任何帮助将不胜感激。
      【解决方案3】:

      现在您在 AsyncTask 中使用了错误的 URL。正确的 URL 类似于 http://localhost/restayii/index.php/employee/getemployee?id

      【讨论】:

      • 我已经在 Task extends Asynctask 类(在 doInBackground 中)上将 url 更改为 http://localhost/restayii/index.php/employee/getemployee?id,但它仍然没有显示员工 json 数据
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多