Retrive data from mysql on my android application

I am try to retrive(read) an array of course form database (mysql) and display it as list of item in my android activity the problem is i have more than one row in my table (course) but it retrive only the first row also if the table (course) have know data insert my application step after the run even that i have case in my code that display toast message that say there is no course


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 method
    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) {
        } catch (ClientProtocolException e) {
        } catch (IOException e) {

        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");
            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;



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.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(); //class

    ArrayList<HashMap<String, String>> coursesList;

    //url to get all products list
    private static String url_all_course = "";
    // 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";

    // course JSONArray
    JSONArray courses = null;

    public void onCreate(Bundle savedInstanceState) {

        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) //one of the list
                 // getting values from selected ListItem
                 String CourseID = ((TextView) view.findViewById(
                 // Starting new intent
                 Intent ViewCourseStudent = new Intent(getApplicationContext(),
                 // 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

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

     * 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
         * */
        protected void onPreExecute() {
            pDialog = new ProgressDialog(ViewALLCourseStudent.this);
            pDialog.setMessage("Loading Courses. Please wait...");
         * getting All products from u r l
         * */
        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 course
                    courses = json.getJSONArray(TAG_course);

                    // looping through All courses
                    for (int i = 0; i < courses.length(); i++)//course JSONArray
                        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
                } else {
                    Toast.makeText(getBaseContext(),"there is no course" ,Toast.LENGTH_LONG).show();

            } catch (JSONException e) {

            return null;

         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            // 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,
                            new int[] {, });
                    // updating listview



and php for view all course


 * 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);


Any thing you want i can explain.


Look at the example given in halloandrdoid or SPTechnolab blog

There is a good example for connecting MySql using PHP and it worked for me.

Need Your Help

How to shrink hitArea of a Sprite on RollOver

actionscript-3 flex animation sprite

I have a grid of many 10x10 pixel squares separated only by a pixel line. When the user rolls over the sprite, it grows, animating to about 4 times its size--to around 40x40 pixels. The sprite stays

How I can i conditionally change the values in a numpy array taking into account nan numbers?

python open-source numpy statistics gdal

My array is a 2D matrix and it has numpy.nan values besides negative and positive values:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.