Saturday, December 8, 2012

Connect Android and Mysql via PHP Webservice Part 2

Hi readers
This is the part two of the Android PHP connection
You can find Part 1 HERE

 First we'll see the structure of the project

As you can see we have class representations for the Employee and the Loginresult they are to be used by GSON to generate the objects for us.

The Constants class contains the constants such as the URL of the Web service and the user id of the currently logged in user.

The server access class handles the interaction between the server and the Application The classes PHPClientActivity and the EmployeeListActivity are for the activities.

 In the layouts section we have 3 layouts one for the Login activity , one for the Employee list activity and the third one is for the employee list item which is shown in the list.

Now we'll see the server access class the explanation is given as inline comment

public class ServerAccess {

 //Convert an inputstream to a string
 public static String convertStreamToString(InputStream is)
    {
     BufferedReader reader = new BufferedReader(new InputStreamReader(is));
     StringBuilder sb = new StringBuilder();

     String line = null;
     try {
      while ((line = reader.readLine()) != null) {
       sb.append(line + "\n");
      }
     }
     catch (IOException e) {
      Log.e("PHP Client","Error : "+e.getMessage());
     }
     finally {
      try {
       is.close();
      } catch (IOException e1) {
       Log.e("PHP Client","Error : "+e1.getMessage());
      }
     }
     return sb.toString();
    }

 //Get the response form the server as an object
 public Object getResponseObject(ArrayList Parameters,Class c)
 {
  try{
   //Create a HTTP Client
   HttpClient httpclient = new DefaultHttpClient();

   //Create and object to Post values to the server
   //The url is specified in the Constants class to increase modifiability
   HttpPost httppost = new HttpPost(Constants.SERVICE_URL);

   //Set the attributes to be posted as Parameters
   httppost.setEntity(new UrlEncodedFormEntity(Parameters));

   //Execute the post and get the response
   HttpResponse response = httpclient.execute(httppost);

   //Get the response as ans entity
   HttpEntity entity = response.getEntity();

   //Get the content of the response as a stream
   InputStream stream=entity.getContent();

   //Convert the stream to a GSON object
         String result= convertStreamToString(stream);

         //Create a GSON object
         Gson gson=new Gson();

         //Convert the respose string to a object of the given type
         //Here Object class is used so that we can use the same method to get any
         //class's object as response
   Object responseObject=gson.fromJson(result, c);
   //Return the object
         return responseObject;
  }catch(Exception e){
   Log.e("PHP Client", "Error in http connection"+e.toString());
   return null;
  }
 }

 //Verify the login and return user id or 0
 public int getUserID(String Username,String Password)
 {
  //Create an arraylist to store the parameters and values as key value pairs
  ArrayList parameters=new ArrayList();

  //Please make sure the spellings of the keys are correct
  //Set the method name
  parameters.add(new BasicNameValuePair("method","verifyLogin"));
  //Set the username
  parameters.add(new BasicNameValuePair("username",Username));
  //Set the password
  parameters.add(new BasicNameValuePair("password",Password));
  //Get the result from the server using the getresponse method
  LoginResult o= (LoginResult)getResponseObject(parameters,LoginResult.class);
  return Integer.parseInt(o.result);
 }

 //Get the employees
 public Employee[] getEmployees(int id)
 {
  //Create the arraylist to set the parameters of the post
  ArrayList parameters=new ArrayList();
  //Set the method name
  parameters.add(new BasicNameValuePair("method","getEmployees"));
  parameters.add(new BasicNameValuePair("id",String.valueOf(id)));

  //Get the array of employee arrays as the result
  Employee[] o= (Employee[])getResponseObject(parameters,Employee[].class);
  return o;
 }
}
Now we'll see the Activity class Here i've provided the code only for the button click event
ServerAccess ss=new ServerAccess();
 Constants.USER_ID=ss.getUserID(txtUsername.getText().toString(), txtPassword.getText().toString());
 if(Constants.USER_ID==0)
 {
  Toast.makeText(getApplicationContext(), "Invalid Username or Password", Toast.LENGTH_LONG).show();
 }
 else
 {
  Intent employeeListActivity=new Intent(getApplicationContext(),EmployeesListActivity.class);
  startActivity(employeeListActivity);
 }
Now we'll see the code for the Listing part
public class EmployeesListActivity extends Activity {

 ListView listEmployeeDetails;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.employeeslist);

  listEmployeeDetails=(ListView)findViewById(R.id.listViewEmployees);
  //Get the employee array from the server access class
  ServerAccess ss=new ServerAccess();
  Employee[] employeesArray= ss.getEmployees(Constants.USER_ID);
  //Set the adapter with our custom view so that the Employee name and his/her address will be shown
  listEmployeeDetails.setAdapter(new EmployeeAdapter(this, R.layout.employeeitem, employeesArray));

 }

 private class EmployeeAdapter extends ArrayAdapter
 {
  //Array to have the objects
  private Employee[] array;

  public EmployeeAdapter(Context context, int textViewResourceId,
    Employee[] objects) {
   super(context, textViewResourceId, objects);
   array=objects;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   //Set the view for each item in the list view
   View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.employeeitem, null);
            }
            //Get the Textviews from the row view and set the appropriate values for them
            TextView labelName=(TextView) v.findViewById(R.id.labelName);
            TextView labelAddress=(TextView)v.findViewById(R.id.labelAddress);
            labelName.setText(array[position].name);
            labelAddress.setText(array[position].address);
   return v;
  }
 }
}

Make sure you give the Uses internet permission in the manifest file.

you can DOWNLOAD SAMPLE HERE 


App screenshots
Happy Coding
-Guruparan Giritharan-
 Please leave a comment

7 comments:

  1. Hi i get a problem with the line:
    import com.google.gson.Gson;
    "these import cannot be resolved"
    and i get a ! next to the PHPClient folder, what could it be?

    ReplyDelete
  2. Hi Please check whether you have the gson library included in the class path.

    ReplyDelete
  3. Thanks i fix that, but now i get one error at the line of code: Object responseObject= gson.fromJson(result, c); "Type safety:Unchecked invocation fromJson(String, Class) of the generic method fromJson(String, Class) of type Gson"

    ReplyDelete
  4. Hi Logan
    try to clean and build the project
    and copy the Gson.jar to the src folder and add the jar to the classpath

    ReplyDelete
  5. Hi where can i find the php code for this example

    ReplyDelete
  6. Hi Ben
    Please use the download link provided

    http://www.mediafire.com/download/n9td7fqe8fi3ghu/Android+Php+sample+by+guruparan.blog.com.zip

    ReplyDelete
  7. Hi, I was able to resolve the Gson.jar issue, compiled and ran the application on my android device but once I click on the login button the application crashes and gives a message 'Unfortunately PHPClient has stopped '

    How can I resolve this?
    Thanks

    ReplyDelete