Thursday, September 26, 2013

Connecting Android with MySQL,PHP

I'm going to show you how simple Android app will call  php script to perform basic operation(insert,view,delete and update).First android app calls a PHP script in order to perform an operation. PHP  script then connect to MySQL database to perform the operation.
data flow is

  Android app -> php script -> mysql


1.What is XAMPP server

XAMPP server provides an environment to develop PHP,MySQL web application.By installing this software you will be installing the Apache,PHP and MySQL.Ones you install the xampp server You can test your server by opening the address localhost/ in your browser.Also you can check phpmyadmin by opening localhost/phpmyadmin


2.Run a php script

Now environment is fixed to develop the project.You have to create php script inside the xampp folder where you install the xampp server(In my case D:\xampp)and go to the htdoc. Create folder Android_connect and include all the php script inside that folder to run.To check the output localhost/android_connect/example.php

     

3.Creating MySQL database

Now open phpmyadmin by opening the address localhost/phpmyadmin/ in your browser. You can use the PhpMyAdmin tool to create a database and a table



4.Connecting MySQL database Using PHP

Open the connection to database and close connection when not needed have to have two php script.
db_config_mdl,db_connect_mdl

References

5.Basic operation

5.a).View data in a List View

Create a new php file called mdl_getall_subjects.php and write the following code. This file will get all the enroll subjects details by taking user id as post parameter.


<?php

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect_mdl.php';

// connecting to db
$db = new DB_CONNECT();

if (isset($_GET["userid"])) {
$userid =$_GET['userid']; 
$result = mysql_query("select c.id as id,c.fullname as subject from mdl_course c where c.id IN(select e.courseid as courseid from mdl_enrol e,mdl_user_enrolments ue where ue.userid='$userid' and e.id=ue.enrolid and e.enrol='self')") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
// products node
    $response["subjects"] = array();

    while ($row = mysql_fetch_array($result)) {
$subject = array();
        // temp user array        
$subject["id"] = $row["id"];
        $subject["subject"] = $row["subject"];

        // push single product into final response array
        array_push($response["subjects"], $subject);
    }
// success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No courses found";

    // echo no users JSON
    echo json_encode($response);
}
}
else{
echo "testing this";
}

?>



5.b).Create data in a List View

Create a new php file called mdl_create_reply.php and write the following code. This file will reply forum by taking postid, subjects,message and username as post parameter.


<?php



// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['id']) && isset($_POST['subject']) && isset($_POST['message']) && isset($_POST['username']) ) {
     
$id = $_POST['id'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
$username=$_POST['username'];
   
    

    // include db connect class
    require_once __DIR__ . '/db_connect_mdl.php';

    // connecting to db
    $db = new DB_CONNECT();



$get_username=mysql_query("select id from mdl_user where username='$username'");

if (mysql_num_rows($get_username) > 0) {
    // looping through all results


$userid=null;

    while ($row = mysql_fetch_array($get_username)) {


     
$userid = $row["id"];
      
    }

}


//________________________________________________________________________________________________________________________________________________________

//$result_mdldiscussion=mysql_query("INSERT INTO mdl_forum_discussions(id,course,forum,name,firstpost,userid) VALUES('','$course','$forum_id','$subject',5,'$userid')");

//$select_fdid=mysql_query("select fd.id from mdl_forum_discussions fd");

   // $select_fpid=mysql_query("select fp.id from mdl_forum_posts fp where fp.parent='$select_fdid' and fp.subject='$subject' ");
$select_fdid=mysql_query("select fd.id from mdl_forum_posts fp,mdl_forum_discussions fd where fd.id=fp.discussion and fp.subject='$subject' ");
// $select_fpid=mysql_query("select fp.id from mdl_forum_posts fp where fp.parent='$id'");

$select_ftime=mysql_query("select created from mdl_forum_posts fp where fp.subject='$subject' ");

$fdid = array();
$fpid = array();
if (mysql_num_rows($select_fdid) > 0) {
    // looping through all results


    while ($row = mysql_fetch_array($select_fdid)) {


     
$fdid["id"] = $row["id"];
      
    }

}

$discussion_id=$fdid["id"];


  
//$fdid = array();

if (mysql_num_rows($select_fpid) > 0) {
    // looping through all results


    while ($row = mysql_fetch_array($select_fpid)) {


     
$fpid["id"] = $row["id"];
      
    }

}

$post_id=$fpid["id"];
// mysql inserting a new row

date_default_timezone_set('Asia/Colombo');
//$serverTime = date('Y-m-d  H:i:s', time());
$serverTime = time();
    
    $result = mysql_query("INSERT INTO mdl_forum_posts(id,discussion,parent,userid,created,modified,message,subject) VALUES('','$discussion_id','$id','$userid','$serverTime','$serverTime','$message', '$subject')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Post successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}


?>

5.b).Delete data in a List View

Create a new php file called mdl_delete_forum_reply.php and write the following code. This file will delete reply forum by taking postid, userid as get parameter.



<?php

// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect_mdl.php';
// connecting to db
$db = new DB_CONNECT();

if (isset($_GET["id"])&& isset($_GET["userid"]) ) {

$id=$_GET['id'];
$userid=$_GET['userid'];
$delete_reply = mysql_query("DELETE FROM mdl_forum_posts where id='$id' AND userid='$userid'") or die(mysql_error());

$result = mysql_query($query) or die("Unable to Delete forum reply : ". mysql_error());  
}
?>





Wednesday, August 7, 2013

Unit testing with JUnit

In Java, the standard unit testing framework is known as JUnit. Unit tests target small units of code, e.g. a method or a class, (local tests) whereas component and integration tests targeting to test the behavior of a component or the integration between a set of components or a complete application consisting of several components.
Unit tests ensure that code works as intended. They are also very helpful to ensure that the code still works as intended in case you need to modify code for fixing a bug or extending functionality. Having a high test coverage of your code allows you to continue developing features without having to perform lots of manual tests.

Tested Class – the class that is being tested.
Tested Method – the method that is tested.
Test Case – the testing of a class’s method against some specified conditions.
Test Case Class – a class performing the test cases.
Test Case Method – a Test Case Class’s method implementing a test case.
Test Suite – a collection of test cases that can be tested in a single batch.
AnnotationDescription
@Test
public void method()
The annotation @Test identifies that a method is a test method.
@Before
public void method()
This method is executed before each test. This method can prepare the test environment (e.g. read input data, initialize the class).
@After
public void method()
This method is executed after each test. This method can cleanup the test environment (e.g. delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
@BeforeClass
public static void method()
This method is executed once, before the start of all tests. This can be used to perform time intensive activities, for example to connect to a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@AfterClass
public static void method()
This method is executed once, after all tests have been finished. This can be used to perform clean-up activities, for example to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@IgnoreIgnores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
@Test (expected = Exception.class)Fails, if the method does not throw the named exception.
@Test(timeout=100)Fails, if the method takes longer than 100 milliseconds.
JUnit provides static methods in the Assert class to test for certain conditions. These assertion methods typically start with asserts and allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value, and throws an AssertionException if the comparison test fails.
The following table gives an overview of these methods. Parameters in [] brackets are optional.
StatementDescription
fail(String)Let the method fail. Might be used to check that a certain part of the code is not reached. Or to have a failing test before the test code is implemented.
assertTrue([message], boolean condition)Checks that the boolean condition is true.
assertsEquals([String message], expected, actual)Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays.
assertsEquals([String message], expected, actual, tolerance)Test that float or double values match. The tolerance is the number of decimals which must be the same.
assertNull([message], object)Checks that the object is null.
assertNotNull([message], object)Checks that the object is not null.
assertSame([String], expected, actual)Checks that both variables refer to the same object.
assertNotSame([String], expected, actual)Checks that both variables refer to different objects.
Unit Testing in Eclips using Junit
Lets create a simple java application
Adding test cases for that class
Test case class
















Tuesday, July 2, 2013

Customized List View

How to customized the list view 

Today I'm going to explained how to design list view with your custom styles and colors instead of using default list view style

In this article i custom designed a list view which contains an image on left side, time and arrow at the right end and a title in middle. I used Relative Layout as parent node and placed all the remaining items using relative positioning properties. Check the following image

dicussion_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_selector"
    android:orientation="horizontal"
    android:padding="5dip" >

    <!--  ListRow Left sied Thumbnail image -->
    <LinearLayout android:id="@+id/thumbnail3c"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="3dip"
        android:layout_alignParentLeft="true"
        
        android:layout_marginRight="5dip">

        <ImageView
            android:id="@+id/list_image"
            android:layout_width="35dip"
            android:layout_height="35dip"
            
            android:src="@drawable/forumsdefaultprofilepic" />

    </LinearLayout>

   

    <TextView
        android:id="@+id/txtMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail3c"
        android:layout_toRightOf="@+id/thumbnail3c"
        android:text="forum"
        android:textColor="#040404"
        android:textSize="10dip"
        android:textStyle="bold"
        android:typeface="sans" />

   

    <TextView
        android:id="@+id/txtUser"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtMessage"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail3c"
        android:text="Replier"
        android:textColor="#343434"
        android:textSize="7dip"
        android:textStyle="bold|italic" />

    <!-- Rightend Duration -->

    <TextView
        android:id="@+id/txtTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/txtUser"
        android:layout_marginRight="5dip"
        android:gravity="right"
        android:text="time"
        android:textColor="#10bcc9"
        android:textSize="5dip"
        android:textStyle="bold" />

     <!-- Rightend Arrow -->
     <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/arrow"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"/>
     
                 
                    <TextView
            android:id="@+id/txtUserid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="110dp"
            android:layout_marginRight="120dp"
            android:text="aaaaa"
            android:textColor="#040404"
            android:textSize="5dip"
            android:textStyle="bold"
            android:typeface="sans"
            android:visibility="gone" />

         <TextView
            android:id="@+id/txtPid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="130dp"
            android:layout_marginRight="140dp"
            android:text="aaaaa"
            android:textColor="#040404"
            android:textSize="5dip"
            android:textStyle="bold"
            android:typeface="sans"
            android:visibility="gone" />


</RelativeLayout>
LazyAdapter.java
package others; import com.project.androm.*; import java.util.ArrayList; import java.util.HashMap; import android.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class LazyAdapter3c extends BaseAdapter { private Runnable _run; private Activity _activity; private ArrayList<HashMap<String, String>> _data; private static LayoutInflater _inflater=null; Context mContext; public static String Postuid; public LazyAdapter3c(Activity a, ArrayList<HashMap<String, String>> d) { _activity = a; _data=d; _inflater = (LayoutInflater)_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public LazyAdapter3c(Runnable runnable,Activity a, ArrayList<HashMap<String, String>> subjectsList,Context pContext) { // TODO Auto-generated constructor stub _run=runnable; _activity = a; _data=subjectsList; _inflater = (LayoutInflater)_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mContext=pContext; } public int getCount() { return _data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = _inflater.inflate(com.project.androm.R.layout.discussion_row3c, null); TextView title1 = (TextView)vi.findViewById(com.project.androm.R.id.txtMessage); TextView title2 = (TextView)vi.findViewById(com.project.androm.R.id.txtUser); TextView title4 = (TextView)vi.findViewById(com.project.androm.R.id.txtUserid); TextView title3 = (TextView)vi.findViewById(com.project.androm.R.id.txtTime); TextView title5 = (TextView)vi.findViewById(com.project.androm.R.id.txtPid); title1.setText(_data.get(position).get("message")); title2.setText(_data.get(position).get("username")); title3.setText(_data.get(position).get("created")); title5.setText(_data.get(position).get("id")); title4.setText(_data.get(position).get("userid")); return vi; } }


Sunday, March 17, 2013

Adding data to a Spinner

Adding data to a Spinner

Hi..friends,Today i want to show you how to add data to a spinner.Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a drop down menu with all other available values, from which the user can select a new one.You can get idea by looking below code.
package com.project.androm.dinuka;
import java.util.ArrayList;
import java.util.List;
import com.project.androm.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class Mdl_CategorySelection extends Activity implements
OnItemSelectedListener {
String sem = "";

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mdl_categoryselection);

// Spinner element
Spinner spinnerSem = (Spinner) findViewById(R.id.spinnerSemesterSub);

spinnerSem.setOnItemSelectedListener(this);

// Spinner Drop down elements
List<String> categories1 = new ArrayList<String>();
categories1.add("1st Semester");
categories1.add("2nd Semester");

// Creating adapter for spinner
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, categories1);

// Drop down layout style - list view with radio button
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner
spinnerSem.setAdapter(dataAdapter1);
sem = spinnerSem.getSelectedItem().toString();
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
if (item.contains("Year")) {
year = item;
} else if (item.contains("Semester")) {
sem = item;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
}

xml file