the idea of my application the user click in buttons and then it will display all course that is in mysql data base
and if he click on the specific course it will display the information of it i use (php - wamp server - josn - java)
so her is my php code that
db_config.php in folder SmsPhp
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "sms"); // database name
define('DB_SERVER', "localhost"); // db server
?>
and 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();
}
}
?>
and view_all_course.php
<?php
/*
* Following code will list all the course
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all courses from course table
$result = mysql_query("SELECT *FROM course") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// products node
$response["course"] = array();
while ($row = mysql_fetch_array($result))
{
// temp user array
$course = array();
$course["CourseID"] = $row["CourseID"];
$course["Code"] = $row["Code"];
$course["Name"] = $row["Name"];
$course["OfficeHours"] = $row["OfficeHours"];
$course["CreditHours"] = $row["CreditHours"];
$course["Description"] =$row["Description"];
$course["MaxAbsenceDays"]= $row["MaxAbsenceDays"];
$course["ExamsDates"] = $row["ExamsDates"];
// push single product into final response array
array_push($response["course"], $course);
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
}
?>
and view_course.php
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["CourseID"]))//Determine if a variable is set and is not NULL return true or false
{
$CourseID = $_GET['CourseID']; // get the value
// get a course from course table
$result = mysql_query("SELECT *FROM course WHERE CourseID = $CourseID");//sends a unique query
if (!empty($result)) // if not empty return false ! = true inside
{
// check for empty result
if ( mysql_num_rows($result) > 0) //Retrieves the number of rows from a result set
{
$result = mysql_fetch_array($result);//Returns an array that corresponds to the fetched
$course = array();
$course["CourseID"] = $result["CourseID"];
$course["Code"] =$result["Code"];
$course["Name"] = $result["Name"];
$course["OfficeHours"] = $result["OfficeHours"];
$course["CreditHours"] = $result["CreditHours"];
$course["Description"] = $result["Description"];
$course["MaxAbsenceDays"]= $result["MaxAbsenceDays"];
$course["ExamsDates"] = $result["ExamsDates"];
// success
$response["success"] = 1;
// user node
$response["course"] = array();
array_push($response["course"],$course); //put array $course in arry response at index course
// echoing JSON response
echo json_encode($response); //Returns a string containing the JSON representation of value.
} else {
// no course found =0
$response["success"] = 0;
$response["message"] = "No course found";
// echo no users JSON
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);
}
?>
in eclipse
ViewALLCourseStudent.java
package com.ksu.sms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ViewALLCourseStudent extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> coursesList;
//url to get all products list
private static String url_all_course = "http://api.androidhive.info/SmsPhp/view_all_course.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_course = "course";
private static final String TAG_CourseID = "CourseID";
private static final String TAG_Name = "Name";
// products JSONArray
JSONArray courses = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_all_course_student);
coursesList = new ArrayList<HashMap<String, String>>();
// Loading courses in Background Thread
new LoadAllCourses().execute();
// Get list view
ListView lv = getListView();
// on seleting single course
// launching Edit course Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// getting values from selected ListItem
String CourseID = ((TextView) view.findViewById(R.id.CourseID)).getText()
.toString();
// Starting new intent
Intent ViewCourseStudent = new Intent(getApplicationContext(),
ViewCourseStudent.class);
// sending Course ID to next activity
ViewCourseStudent.putExtra(TAG_CourseID, CourseID);
// starting new activity and expecting some response back
startActivityForResult(ViewCourseStudent, 100);
}
});
}
// Response from view course Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user view course
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all course by making HTTP Request
* */
class LoadAllCourses extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewALLCourseStudent.this);
pDialog.setMessage("Loading Courses. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from u r l
* */
@Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_course, "GET", params);
// Check your log cat for JSON response
Log.d("All courses: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// course found
// Getting Array of Products
courses = json.getJSONArray(TAG_course);
// looping through All courses
for (int i = 0; i < courses.length(); i++)
{
JSONObject c = courses.getJSONObject(i); // read first
// Storing each json item in variable
String CourseID = c.getString(TAG_CourseID);
String Name = c.getString(TAG_Name);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CourseID, CourseID);
map.put(TAG_Name, Name);
// adding HashList to ArrayList
coursesList.add(map);
}
} else {
Context context = getApplicationContext();
CharSequence text = "No Course Found";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewALLCourseStudent.this, coursesList,
R.layout.list_item, new String[] { TAG_CourseID,
TAG_Name},
new int[] { R.id.CourseID, R.id.Name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
and ViewCourseStudent.java
package com.ksu.sms;
import android.app.Activity;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class ViewCourseStudent extends Activity {
TextView Name; TextView Description;
TextView OfficeHours;
TextView CreditHours;
TextView MaxAbsenceDays;
TextView ExamsDates ;
String CourseID ;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single course url
private static final String url_course_detials = "http://api.androidhive.info/SmsPhp/view_course.php";
//JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CourseID = "CourseID";
private static final String TAG_course = "course";
private static final String TAG_Name = "Name";
private static final String TAG_OfficeHours = "OfficeHours";
private static final String TAG_CreditHours = "CreditHours";
private static final String TAG_Description = "Description";
private static final String TAG_MaxAbsenceDays = "MaxAbsenceDays";
private static final String TAG_ExamsDates = "ExamsDates";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_course);
Intent i = getIntent();
CourseID = i.getStringExtra(TAG_CourseID);
// Getting complete course details in background thread
new GetCourseDetails().execute();
}
/**
* Background Async Task to Get complete course details
* */
class GetCourseDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewCourseStudent.this);
pDialog.setMessage("Loading course details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("CourseID", CourseID));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_course_detials, "GET", params);
// check your log for json response
Log.d("Single course Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray courseObj = json
.getJSONArray(TAG_course); // JSON Array
// get first course object from JSON Array
JSONObject product = courseObj.getJSONObject(0);
// course with this course_id found
// textview Text
/*TextView Name; TextView Description;
TextView OfficeHours;
TextView CreditHours;
TextView MaxAbsenceDays;
TextView ExamsDates ;*/
Name = (TextView) findViewById(R.id.C_Name);
Description = (TextView) findViewById(R.id.C_Des);
CreditHours = (TextView) findViewById(R.id.C_Hours);
OfficeHours=(TextView) findViewById(R.id.C_Ohour);
MaxAbsenceDays=(TextView) findViewById(R.id.C_absence);
ExamsDates=(TextView) findViewById(R.id.Add_C_Exam);
// display product data in EditText
Name.setText(product.getString(TAG_Name));
Description.setText(product.getString(TAG_Description));
OfficeHours.setText(product.getString(TAG_OfficeHours));
MaxAbsenceDays.setText(product.getString(TAG_MaxAbsenceDays));
ExamsDates.setText(product.getString(TAG_ExamsDates));
CreditHours.setText(product.getString(TAG_CreditHours));
}else{
// course with course id not found
}
} 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 got all details
pDialog.dismiss();
}
}
}
any question or any thing i can explained
my code i smliar of
this
http://www.androidhi...with-php-mysql/
thanks so much

New Topic/Question
Reply


MultiQuote








|