gpt4 book ai didi

java - 在我的 android 应用程序上从 mysql 检索数据

转载 作者:行者123 更新时间:2023-11-30 23:27:27 25 4
gpt4 key购买 nike

我正在尝试检索(读取)一组类(class)表单数据库(mysql)并将其显示为我的 android Activity 中的项目列表问题是我的表(类(class))中有不止一行但它只检索如果表(类(class))知道数据,第一行也会在运行后插入我的应用程序步骤,即使我的代码中有案例显示 toast 消息说没有类(class)

类 JSONParser.java

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;

}
}

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.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 = "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);
}
});

}

}
}

和用于查看所有类(class)的 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);
}





?>

任何你想要的我都可以解释。

最佳答案

halloandrdoid中给出的例子或 SPTechnolab blog

有一个使用 PHP 连接 MySql 的好例子,它对我有用。

关于java - 在我的 android 应用程序上从 mysql 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com