Introduction
If you want to create an Android app and want to read data from a MySQL database and send data. We will create a Web Service in PHP, read from the MySQL database, and let the Android connect with the Web Service and send data, and the Web Service will save it and another Web Service will read data from MySQL and send it to the Android app.
1.What is XAMPP Server
XAMPP is Free and Open Source Cross-Platform Web Server Solution Stack. It comes with Apache Web Server, MySQL Database, PHP adn Perl Programming Languages. Together with these there is an SMTP and FTP server included as well.
2. Installing and Running XAMPP Server
Just download the package from www.apachefriends.org/download.html’ website unzip in a folder on your hard disk. I prefer to put it in the root of the drive e.g. D:\ on my Windows 7 laptop. Now go to the folder and run xampp-control.exe; this will open up a control panel. Click start button in front of each of the components to run them. Once you click start for Apache you can type localhost in your web browser of choice and you will get XAMPP home page. You can now put your web applications in htdocs folder inside xampp folder and they will be served in your web browser.
3. Creating and Running PHP Project
Now you have the environment ready to develop a PHP & MySQL project. Go to the location where you installed XAMPP server (In my case i installed in C:\xampp\) and go to htdocs folder and create a new folder for your project. You have to place all your project files inside this folder.
Create a folder called estate.
4. Creating MySQL Database and Tables
In this tutorial i am creating a simple database with four tables. Now open phpmyadmin by opening the address http://localhost/phpmyadmin/ in your browser. You can use the PhpMyAdmin tool to create a database and a table.
I am creating a database named android4u and a tables message,property,tb_user and user.
CREATE DATABASE android4u;
now create table message
Table structure for table `message`
CREATE TABLE IF NOT EXISTS `message` (
`mid` int(12) NOT NULL AUTO_INCREMENT,
`name` varchar(43) NOT NULL,
`email` varchar(43) NOT NULL,
`msg` varchar(122) NOT NULL,
PRIMARY KEY (`mid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
//Dumping data for table `message`
--
INSERT INTO `message` (`mid`, `name`, `email`, `msg`) VALUES
(1, 'Nitesh Kumar', 'kumar.nitesh703@gmail.com', 'Maann..for me i want to buy without coming to you'),
(2, 'Abhishek Rana', 'abhishek@gmail.com', 'I need land for my farm.');
-- Table structure for table `property`
--
CREATE TABLE IF NOT EXISTS `property` (
`pid` int(12) NOT NULL AUTO_INCREMENT,
`contact` varchar(100) NOT NULL,
`name` varchar(123) NOT NULL,
`location` varchar(123) NOT NULL,
`status` varchar(123) NOT NULL,
`price` int(12) NOT NULL,
`description` varchar(213) NOT NULL,
`activation` varchar(23) NOT NULL,
`Image` varchar(100) NOT NULL,
PRIMARY KEY (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
--
-- Dumping data for table `property`
--
INSERT INTO `property` (`pid`, `contact`, `name`, `location`, `status`, `price`, `description`, `activation`, `Image`) VALUES
(8, '', 'Home ', 'Nitesh', 'For Rent', 300000, '3 Bedrooms + Self Contained', 'Yes', 'upload/cfc.jpeg'),
(9, '', 'House', 'Abhishek', 'For Sale', 20000000, 'Big and Large - 3Bedrooms', 'Yes', 'upload/background2.jpg'),
(10, '', 'Plot of Land', 'Akash', 'For Sale', 200000000, '100 x 100, Water, Electricity, Roads', 'Yes', 'upload/rrrrr.jpeg'),
(11, '', 'Land', 'Braja', 'For Sale', 100000000, '100 Acres, Suitable for a farm', 'Yes', 'upload/carpark4.jpg');
-- --------------------------------------------------------
--
-- Table structure for table `tb_user`
--
CREATE TABLE IF NOT EXISTS `tb_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`firstname` varchar(100) NOT NULL,
`lastname` varchar(100) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `tb_user`
--
INSERT INTO `tb_user` (`user_id`, `username`, `password`, `firstname`, `lastname`) VALUES
(4, 'admin', 'admin', 'Nitesh', 'Kumar'),
(3, 'admin1', 'admin1', 'Abhishek', 'Rana');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(100) NOT NULL,
`lastname` varchar(100) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`location` varchar(100) NOT NULL,
`contact` varchar(100) NOT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`uid`, `firstname`, `lastname`, `username`, `password`, `location`, `contact`) VALUES
(1, 'ss', 'ss', 'user', 'user', 'ff', '454'),
(3, 'Nitesh', 'Kumar', 'admin', 'admin', 'India', '09867827323');
5. Connecting to MySQL database using PHP
Now the actual server side coding starts. Create a PHP class to connect to MySQL database. The main purpose of this class is to open a connection to database and close the connection whenever its not needed. So create two files called db_config.php and db_connect.php
db_config.php – will have database connection variables
db_connect.php – a class file to connect to database
db_connect.php – a class file to connect to database
Following is code for two php files
db_config.php
<?php
/*
* All database connection variables
* This is for localhost
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "android4u"); // database name
define('DB_SERVER', "localhost"); // db server
/*
* All database connection variables
* This is for webhost
*/
define('DB_USER', "root"); // db user that you have created for server
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "android4u"); // database name
define('DB_SERVER', "123.63.96.32"); // db server like whatever is your server ip
?>
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
login.php
<?php
//load and connect to MySQL database stuff
require("db_config.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
uid,
firstname,
lastname,
username,
password
FROM user
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" />
<br /><br />
Password:<br />
<input type="password" name="password" placeholder="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
<a href="register.php">Register</a>
<?php
}
?>
new_user.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['location']) && isset($_POST['contact'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$username = $_POST['username'];
$password = $_POST['password'];
$location = $_POST['location'];
$contact = $_POST['contact'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO user(firstname, lastname, username, password, location, contact) VALUES('$fname', '$lname', '$username','$password','$location','$contact')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully Registered.";
// 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);
}
?>
new_property.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['contact']) && isset($_POST['name']) && isset($_POST['location']) && isset($_POST['status']) && isset($_POST['price'])
&& isset($_POST['description'])) {
$contact = $_POST['contact'];
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$price = $_POST['price'];
$description = $_POST['description'];
$activation = 'No';
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO property(contact, name, location, status, price, description, activation) VALUES('$contact','$name', '$location', '$status','$price','$description','$activation')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Property Successfully Added.";
// 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);
}
?>
comments.php
<?php
/*
Our "db_config.php" file connects to database every time we include or require
it within a php script. Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("config.php");
//initial query
$query = "Select * FROM property where activation = 'Yes'";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["post_id"] = $row["pid"];
$post["username"] = $row["price"];
$post["title"] = $row["name"];
$post["message"] = $row["location"];
$post["status"] = $row["status"];
// $post["Image"] = base64_encode(file_get_contents("C://wamp/www/smart real estate/admin/upload/"$row["Image"]));
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
new_msg.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['msg']) ) {
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['msg'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO message(name, email, msg) VALUES('$name', '$email','$msg')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully Messgae.";
// 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);
}
?>
Until now, we built a simple api for our table. We are now done with the server side coding (PHP) and its time to take a break and start our actual android application coding.
6. Creating Android Application
Create a new project in your Eclipse IDE by filling the required details.
1. Create new project in Eclipse IDE by going to File ⇒ New ⇒ Android Project and name the Activity class name as MainActivity.
2. Open your AndroidManifest.xml file and add following code. First i am adding all the classes i am creating to manifest file. Also i am adding INTERNET Connect permission.
Now create a new xml file under res ⇒ layout folder and name it as activity_main.xml This layout file contains login screen details.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- username -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Username:"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- username input -->
<EditText android:id="@+id/inputname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- password -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Password:"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- password input -->
<EditText android:id="@+id/inputpassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"
android:inputType="textPassword"/>"
<!-- Button Login -->
<Button android:id="@+id/btnlogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login"/>
<!-- Button Create Account -->
<Button android:id="@+id/btncreate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Not Registered, Here!!"/>
<!-- Button Quit -->
<Button android:id="@+id/btnquit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Quit"/>
</LinearLayout>
reg_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- firstname -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="FirstName:"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- firstname input -->
<EditText android:id="@+id/fname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- lastname -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="LastName:"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- lastname input -->
<EditText android:id="@+id/lname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- username -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Username:"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- username input -->
<EditText android:id="@+id/uname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- password -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Password:"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- password input -->
<EditText android:id="@+id/pass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"
android:inputType="textPassword"/>
<!-- address -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Address"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- address input -->
<EditText android:id="@+id/addr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- contact -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Contact:"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- contact input -->
<EditText android:id="@+id/contact"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- Button Register -->
<Button android:id="@+id/btnreg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"/>
<!-- Button Cancel -->
<Button android:id="@+id/btncancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"/>
</LinearLayout>
</ScrollView>
main_screen1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<!-- Sample Dashboard screen with Two buttons -->
<Button android:id="@+id/btnViewProducts"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="All Property"
android:layout_marginTop="25dip"/>
<Button android:id="@+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add New Property"
android:layout_marginTop="25dip"/>
<Button android:id="@+id/btnContact"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Contact Us"
android:layout_marginTop="25dip"/>
<Button android:id="@+id/btnlogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Logout"
android:layout_marginTop="25dip"/>
</LinearLayout>
add_comments.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/arrowstars" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Android Remote Server Tutorial"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<EditText
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/submit"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/TextView01"
android:ems="10"
/>
<EditText
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/imageView1"
android:text="Title" />
<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="Submit" />
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/title"
android:layout_marginTop="14dp"
android:text="Message" />
</RelativeLayout>
add_property.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Name Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Property Name"
android:textSize="17dip" />
<!-- Input Name -->
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true" />
<!-- Location Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Location"
android:textSize="17dip" />
<!-- Input Location -->
<EditText
android:id="@+id/location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:lines="2" />
<!-- Name Status -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Status"
android:textSize="17dip" />
<!-- Input Status -->
<EditText
android:id="@+id/status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true" />
<!-- Price Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Price(UGX)"
android:textSize="17dip" />
<!-- Input Price -->
<EditText
android:id="@+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:inputType="numberDecimal"
android:singleLine="true" />
<!-- Description Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Description"
android:textSize="17dip" />
<!-- Input description -->
<EditText
android:id="@+id/desc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:gravity="top"
android:lines="3" />
<!-- Button Create Product -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Image(If any)"
android:textSize="17dip" />
<ImageView
android:id="@+id/imgView"
android:layout_width="292dp"
android:layout_height="wrap_content"
android:layout_weight="1.14"
android:src="@drawable/cx" />
<Button
android:id="@+id/browse"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Browse for Image" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Contact Info"
android:textSize="17dip" />
<!-- Input description -->
<EditText
android:id="@+id/cont"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:gravity="top"
android:lines="2" />
<Button
android:id="@+id/btnNew"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit" />
<!-- Button Cancel -->
<Button
android:id="@+id/btnKanso"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel" />
</LinearLayout>
</ScrollView>
all_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(@android:id/list)
-->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
message.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Name Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Full Name"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input Name -->
<EditText android:id="@+id/inputfname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- Price Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Email Address"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input Price -->
<EditText android:id="@+id/inputemail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"
android:inputType="textEmailAddress"/>"
<!-- Description Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Message"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input description -->
<EditText android:id="@+id/inputmessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:lines="4"
android:gravity="top"/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- Button Create Product -->
<Button android:id="@+id/btnSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send Message"
android:layout_weight="1"/>
<!-- Button Create Product -->
<Button android:id="@+id/btnBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Go Back"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
read_comments.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff" >
<LinearLayout
android:id="@+id/top_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="@drawable/blue_gradient"
android:orientation="horizontal" >
<TextView
style="@style/BlackText"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="All Valid Property"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/bottom_layover"
android:layout_below="@+id/top_layover"
android:background="#fff"
android:divider="@android:color/transparent"
android:scrollbars="none" />
<LinearLayout
android:id="@+id/bottom_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="@drawable/blue_gradient"
android:orientation="horizontal"
android:weightSum="2" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<LinearLayout
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_weight="3.13" >
<Button
android:id="@+id/post_comment"
style="@style/WhiteText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/black_button"
android:onClick="addComment"
android:text="Go Back" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</RelativeLayout>
single_post.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#f0f0f0"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/post_border_style"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:background="@drawable/post_background_style"
android:orientation="horizontal" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cx" />
<LinearLayout
android:id="@+id/box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:paddingBottom="2dip"
android:paddingLeft="5dp"
android:paddingTop="6dip"
android:textColor="#333"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingLeft="8dp"
android:textColor="#888" >
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="5dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Price: "
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#acacac"
android:textStyle="bold" >
</TextView>
<LinearLayout
android:id="@+id/box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="@+id/state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#ff0000"
android:textStyle="bold" >
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/splash"
>
</LinearLayout>
JSON Parser Class
I used a JSON Parser class to get JSON from URL. This class supports two http request methods GET and POST to get json from url.
JSONParser.java
package com.example.estate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
}
MainActivity.java
package com.example.estate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.estate.RegActivity;
//import com.example.androidhive.NewProductActivity;
import com.example.estate.R;
import com.example.estate.JSONParser;
import com.example.estate.MainActivity;
//import com.example.estate.ReadComments;
import com.example.estate.RegActivity;
//import com.example.estate.Login.AttemptLogin;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
Button btnlogin;
Button btnreg;
Button btncancel;
EditText username;
EditText password;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://10.0.2.2/Estate_Conny/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Buttons
btnlogin = (Button) findViewById(R.id.btnlogin );
btnreg = (Button) findViewById(R.id.btncreate);
btncancel = (Button) findViewById(R.id.btnquit);
username = (EditText) findViewById(R.id.inputname);
password = (EditText) findViewById(R.id.inputpassword);
btnreg.setOnClickListener(this);
btnlogin.setOnClickListener(this);
btncancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnlogin:
new AttemptLogin().execute();
break;
case R.id.btncreate:
Intent i = new Intent(this, RegActivity.class);
startActivity(i);
break;
case R.id.btnquit:
finish();
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Logging in User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String user = username.getText().toString();
String pass = password.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pass));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(MainActivity.this, ScreenActivity.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
MessageActivity.java
package com.example.estate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MessageActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText name;
EditText email;
EditText msg;
Button btnsend;
Button btncancel;
// url to create new product
private static String url_new_user = "http://10.0.2.2/Estate_Conny/new_msg.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messages);
// Edit Text
name = (EditText) findViewById(R.id.inputfname);
email = (EditText) findViewById(R.id.inputemail);
msg = (EditText) findViewById(R.id.inputmessage);
// Create button
btnsend = (Button) findViewById(R.id.btnSend);
btncancel = (Button) findViewById(R.id.btnBack);
// button click event
btnsend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
btncancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
Intent i = new Intent(getApplicationContext(), ScreenActivity.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MessageActivity.this);
pDialog.setMessage("Sending Message..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Message = msg.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", Name));
params.add(new BasicNameValuePair("email", Email));
params.add(new BasicNameValuePair("msg", Message));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
finish();
Intent i = new Intent(getApplicationContext(), ScreenActivity.class);
startActivity(i);
// closing this screen
//finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
NewPropertyActivity.java
package com.example.estate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class NewPropertyActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
private static int RESULT_LOAD_IMAGE = 1;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputContact;
EditText inputLocation;
EditText inputStatus;
EditText inputPrice;
EditText inputDesc;
Button btnAdd;
Button btnCancel;
Button btnLoad;
// url to create new product
private static String url_new_property = "http://10.0.2.2/Estate_Conny/new_property.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_property);
// Edit Text
inputName = (EditText) findViewById(R.id.name);
inputLocation = (EditText) findViewById(R.id.location);
inputStatus = (EditText) findViewById(R.id.status);
inputPrice = (EditText) findViewById(R.id.price);
inputDesc = (EditText) findViewById(R.id.desc);
inputContact = (EditText) findViewById(R.id.cont);
// Create button
btnAdd = (Button) findViewById(R.id.btnNew);
btnCancel = (Button) findViewById(R.id.btnKanso);
btnLoad = (Button) findViewById(R.id.browse);
// button click event
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
btnLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ScreenActivity.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewPropertyActivity.this);
pDialog.setMessage("Adding Property Record..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String Contact = inputContact.getText().toString();
String Name = inputName.getText().toString();
String Location = inputLocation.getText().toString();
String Status = inputStatus.getText().toString();
String Price = inputPrice.getText().toString();
String Description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("contact", Contact));
params.add(new BasicNameValuePair("name", Name));
params.add(new BasicNameValuePair("location", Location));
params.add(new BasicNameValuePair("status", Status));
params.add(new BasicNameValuePair("price", Price));
params.add(new BasicNameValuePair("description", Description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_new_property,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), ScreenActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
ReadComments.java
package com.example.estate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class NewPropertyActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
private static int RESULT_LOAD_IMAGE = 1;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputContact;
EditText inputLocation;
EditText inputStatus;
EditText inputPrice;
EditText inputDesc;
Button btnAdd;
Button btnCancel;
Button btnLoad;
// url to create new product
private static String url_new_property = "http://10.0.2.2/Estate_Conny/new_property.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_property);
// Edit Text
inputName = (EditText) findViewById(R.id.name);
inputLocation = (EditText) findViewById(R.id.location);
inputStatus = (EditText) findViewById(R.id.status);
inputPrice = (EditText) findViewById(R.id.price);
inputDesc = (EditText) findViewById(R.id.desc);
inputContact = (EditText) findViewById(R.id.cont);
// Create button
btnAdd = (Button) findViewById(R.id.btnNew);
btnCancel = (Button) findViewById(R.id.btnKanso);
btnLoad = (Button) findViewById(R.id.browse);
// button click event
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
btnLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ScreenActivity.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewPropertyActivity.this);
pDialog.setMessage("Adding Property Record..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String Contact = inputContact.getText().toString();
String Name = inputName.getText().toString();
String Location = inputLocation.getText().toString();
String Status = inputStatus.getText().toString();
String Price = inputPrice.getText().toString();
String Description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("contact", Contact));
params.add(new BasicNameValuePair("name", Name));
params.add(new BasicNameValuePair("location", Location));
params.add(new BasicNameValuePair("status", Status));
params.add(new BasicNameValuePair("price", Price));
params.add(new BasicNameValuePair("description", Description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_new_property,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), ScreenActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
RegActivity.java
package com.example.estate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText fname;
EditText lname;
EditText username;
EditText password;
EditText location;
EditText contact;
Button btnreg;
Button btncancel;
// url to create new product
private static String url_new_user = "http://10.0.2.2/Estate_Conny/new_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg_activity);
// Edit Text
fname = (EditText) findViewById(R.id.fname);
lname = (EditText) findViewById(R.id.lname);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
location = (EditText) findViewById(R.id.addr);
contact = (EditText) findViewById(R.id.contact);
// Create button
btnreg = (Button) findViewById(R.id.btnreg);
btncancel = (Button) findViewById(R.id.btncancel);
// button click event
btnreg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
btncancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegActivity.this);
pDialog.setMessage("Registering New User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String Firstname = fname.getText().toString();
String Lastname = lname.getText().toString();
String Username = username.getText().toString();
String Password = password.getText().toString();
String Address = location.getText().toString();
String Contact = contact.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fname", Firstname));
params.add(new BasicNameValuePair("lname", Lastname));
params.add(new BasicNameValuePair("username", Username));
params.add(new BasicNameValuePair("password", Password));
params.add(new BasicNameValuePair("location", Address));
params.add(new BasicNameValuePair("contact", Contact));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
ScreenActivity.java
package com.example.estate;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ScreenActivity extends Activity{
Button btnView, btnNew;
Button btnlogout;
Button btncontact;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen1);
// Buttons
btnView = (Button) findViewById(R.id.btnViewProducts);
btnNew = (Button) findViewById(R.id.btnAdd);
btnlogout = (Button) findViewById(R.id.btnlogout);
btncontact = (Button) findViewById(R.id.btnContact);
// view products click event
btnView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching All products Activity
finish();
Intent i = new Intent(getApplicationContext(), ReadComments.class);
startActivity(i);
}
});
btnNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching All products Activity
finish();
Intent i = new Intent(getApplicationContext(), NewPropertyActivity.class);
startActivity(i);
}
});
// view products click event
btncontact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
// Launching create new product activity
Intent i = new Intent(getApplicationContext(), MessageActivity.class);
startActivity(i);
}
});
btnlogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching create new product activity
finish();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
Splash.java
package com.example.estate;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent gotoStart = new Intent("com.example.estate.MainActivity");
startActivity(gotoStart);
}
}
};timer.start();
}
}
Here our java portion is completed.
Now open your manifest
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.estate"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:configChanges="keyboardHidden|orientation"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name="com.example.estate.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Registration Activity -->
<activity
android:name=".RegActivity"
android:label="User Registration" >
</activity>
<activity
android:name=".ScreenActivity"
android:label="Welcome::" >
</activity>
<activity
android:name=".NewPropertyActivity"
android:label="Post a property/holding" >
</activity>
<activity
android:name=".AllProductsActivity"
android:label="Available Properties" >
</activity>
<activity
android:name=".EditProductActivity"
android:label="Property Details" >
</activity>
<activity
android:name=".MessageActivity"
android:label="Talk to the Admin" >
</activity>
<activity
android:name=".ReadComments"
android:label="Property" >
</activity>
<activity
android:name=".AddComment"
android:label="Property" >
</activity>
</application>
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Here we complete this project run the app in emulator and let me know if any problem you face.
"Enjoy Coding"
.
No comments:
Post a Comment