1

first of all, i'm a newbie and i already follow tutorial to create website using Yii framework as server. a simple website with CRUD function is already build. now i want to connect it with my android application.

my platform : Win 7 64, Eclipse IDE, Android ADT, GenyMotion.

/* Yii Side */

this is my EmployeeController on (protected\controllers\EmployeeController.php)

public function actionGetEmployee($id)
{
    header('Content-type: application/json');
    $employee = Employee::model()->findAll();
    echo CJSON::encode($employee);
    Yii::app()->end();
}

the result from above code is this :

[
{
    "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"
}
]

/* Now on Android side */

this is the main.xml :

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Daftar Biodata Karyawan Online" />

        <TableLayout
            android:id="@+id/tableLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <Button
                    android:id="@+id/btnrefresh"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Refresh" />

                <Button
                    android:id="@+id/btnedit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Edit" />

                <Button
                    android:id="@+id/btnhapus"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hapus" />
            </TableRow>
        </TableLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TableLayout
            android:id="@+id/tableLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1" >
        </TableLayout>
    </LinearLayout>
</LinearLayout>
 </ScrollView>

and this is my Akses_Server_Activity :

    public class Akses_Server_Activity extends Activity{

static String url = "http://10.0.2.2/restayii/index.php/department/getdepartment?id";
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 btnrefresh;

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

    btnrefresh = (Button) findViewById(R.id.btnrefresh);
    btnrefresh.setOnClickListener(new View.OnClickListener() {  
        @Override  
        public void onClick(View v) {
            try {
                Toast.makeText(getApplicationContext(), "Hendy", Toast.LENGTH_LONG).show();
                new MyAsynTask().execute();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }  
    });
}

public class JSONParser {

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

    public JSONObject GetJson(String url) {

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

        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);
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

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

        return jObj;

    }
}

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

    @Override
    protected JSONObject doInBackground(String... arg0) {

        JSONParser json_parse = new JSONParser();
        json_object = json_parse.GetJson(url);
        return null;
    }

    protected void onPostExecute(String Result){
        // com
        try {
            employee = json_object.getJSONArray("employee");
            TableLayout table_layout =(TableLayout) findViewById(R.id.tableLayout);
            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 jobj = employee.getJSONObject(i);
                data_employee[i][0] = jobj.getString(Employee_ID);
                data_employee[i][1] = jobj.getString(Employee_Dept_ID);
                data_employee[i][2] = jobj.getString(Employee_First_Name);
                data_employee[i][3] = jobj.getString(Employee_Last_Name);
                data_employee[i][4] = jobj.getString(Employee_Gender);
                data_employee[i][5] = jobj.getString(Employee_Birth_Date);
                data_employee[i][6] = jobj.getString(Employee_Marital_Status);
                data_employee[i][7] = jobj.getString(Employee_Phone_Number);
                data_employee[i][8] = jobj.getString(Employee_Address);
                data_employee[i][9] = jobj.getString(Employee_Email);
                data_employee[i][10] = jobj.getString(Employee_Ext);
                data_employee[i][11] = jobj.getString(Employee_Hire_Date);
                data_employee[i][12] = jobj.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); 
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
    }

this is the logcat :

11-04 16:23:47.273: E/JSON Parser(1867): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

my problem is : when android app running, i click the refresh button, it not showing the Table Layout that contain employee json data. any help would be very apreciated. thanks.

Damodaran
  • 10,882
  • 10
  • 60
  • 81
Hendy
  • 265
  • 1
  • 6
  • 27

1 Answers1

0

I think you have error when making request from Android app, because <!DOCTYPE is start of webpage. Try to look at the result of request from Android app.

CreatoR
  • 1,654
  • 10
  • 14
  • is it wrong with the code in `protected void onPostExecute(String Result)` ? – Hendy Nov 06 '13 at 01:52
  • i already add Gson library to my project. how can i use this Gson lib to receive employee json data? – Hendy Nov 06 '13 at 04:02
  • any help would be very appreciated. – Hendy Nov 06 '13 at 07:59
  • I don't know Java and Android. I can help you with yii. And I think that is error on yii side when you make request from android. Can you debug response? – CreatoR Nov 06 '13 at 07:59
  • i don't know how to debug response. – Hendy Nov 06 '13 at 08:05
  • :), I think you may set breakpoint in the line where android app receive response from the server and look at the local variable value, which contain this response. It is maybe help you: http://stackoverflow.com/questions/8551818/how-to-debug-android-application-line-by-line-using-eclipse – CreatoR Nov 06 '13 at 08:14
  • so this is EmployeeController inside protected\controllers\EmployeeController.php `class EmployeeController extends Controller { ... public function actionGetEmployee($id) { $this->layout = false; header('Content-type: application/json'); $employee = Employee::model()->findAll(); echo CJSON::encode($employee); Yii::app()->end(); } ... } ` when i open it via this link `http://localhost/restayii/index.php/employee/getemployee?id` it show login page, after i input my user & pass, it showing one page that fill with employee JSON data. can you help CreatoR? thanks – Hendy Nov 06 '13 at 08:31
  • No, with this data I can't help. I need to look at the response, which **receiving Android application** before parsing json, not response in browser, but in Android app. And I want to see to the request url which load in **android app** – CreatoR Nov 06 '13 at 08:40