0 Replies - 1995 Views - Last Post: 20 September 2012 - 02:45 AM

#1 maram_al  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 04-August 12

retrieve form data base problem

Posted 20 September 2012 - 02:45 AM

hey i am try to retrieve all course form database as list and if the user click in specific course it will display
there information in other activity
the problem is it retrieve only one course and i have in my database 2 course
and second when i click in spisfic course it display erro message in logcat which is
09-20 12:15:05.606: E/AndroidRuntime(3090): FATAL EXCEPTION: main
09-20 12:15:05.606: E/AndroidRuntime(3090): android.os.NetworkOnMainThreadException
my code is


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://10.0.2.2/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) //one of the list
        	 {
                 // 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 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
	                    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 in 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);
}
   
 
 


?>


could you help me how to slove it

Is This A Good Question/Topic? 0
  • +

Page 1 of 1