有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在我的安卓应用程序上从mysql检索数据

我试图检索(读取)一个课程表单数据库(mysql)数组,并在我的安卓活动中将其显示为项目列表。问题是我的表(课程)中有多行,但如果表(课程)中有已知数据,则只检索第一行。在运行后插入我的应用程序步骤,即使我在显示的代码中有大小写祝酒词,说没有课程

类JSONParser。爪哇

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

    }
   }

课堂视图所有课程学生。爪哇

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 安卓.app.ListActivity;
import 安卓.app.ProgressDialog;
import 安卓.content.Intent;
import 安卓.os.AsyncTask;
import 安卓.os.Bundle;
import 安卓.util.Log;
import 安卓.view.View;
import 安卓.widget.AdapterView;
import 安卓.widget.AdapterView.OnItemClickListener;
import 安卓.widget.ListAdapter;
import 安卓.widget.ListView;
import 安卓.widget.SimpleAdapter;
import 安卓.widget.TextView;
import 安卓.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 = "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";

    // course 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 {
                    Toast.makeText(getBaseContext(),"there is no course" ,Toast.LENGTH_LONG).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);
                }
            });

        }

    }
}

和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);
}





?>

你想要什么我都能解释


共 (1) 个答案