MySQL table 值到 Android 中的 ListView
MySQL table values to ListView in Android
我是 Android 开发新手。
我想要 table 值的完整列表 [来自 Select * 来自产品] 显示在 Android 的 'ListView' 中。
所以,我遵循了几个教程并编写了自己的项目,但是,在启动和应用程序时我仍然遇到异常 'unexpectedly closes'。有人请告诉我代码有什么问题。
我的数据库是在网络服务器上创建的。所以,我将把所有 PHP 文件也放在一起。
get_all_products.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_access.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT * FROM products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["products"], $product);
}
// 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);
}
?>
db_access.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "something"); // database name
define('DB_SERVER', "myhost"); // db server
?>
MySQL 条目
CREATE TABLE products(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
);
INSERT INTO `products` (
`pid` ,
`name` ,
`price` ,
`description` ,
`created_at` ,
`updated_at`
)
VALUES (
NULL , 'iPhone', '678', 'Awesome Phone', '2015-02-01 03:13:31', '2015-02-02 09:27:35'
);
MainActivity.java
public class MainActivity extends ListActivity {
ListView lv;
JSONArray products = null;
ArrayList<HashMap<String, String>> productsList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
productsList = new ArrayList<HashMap<String, String>>();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
lv = (ListView)findViewById(R.id.list);
lv = getListView();
LoadAllProducts();
}
public void LoadAllProducts() {
Thread th = new Thread(new Runnable() {
@Override
public void run() {
JSONObject json = getUserObject("http://myweb.com/get_all_products.php");
Log.i("My json",json.toString());
try {
int success = json.getInt("success");
if (success == 1) {
products = json.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String id = c.getString("pid");
String name = c.getString("name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("pid", id);
map.put("name", name);
productsList.add(map);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, productsList,
R.layout.list_item, new String[] { "pid",
"name"},
new int[] { R.id.pid, R.id.name });
// updating list view
setListAdapter(adapter);
}
});
}
});
th.start();
}
public static JSONObject getUserObject(String url){
JSONObject jObj = null;
String json = null;
try
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
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();
InputStream is = httpEntity.getContent();
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
catch(Exception e)
{
Log.i("NetworkTest", "Network Error: " + e);
}
return jObj;
}
}
all_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/pid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
抱歉,如果问题很长,因为我还是新手。但是,有人可以帮忙吗?谢谢!
错误日志cat
02-01 12:34:16.256: E/cutils(31230): to chown(/mnt/shell/emulated/0, 0, 0)
02-01 12:34:16.256: E/cutils(31230): to chown(/mnt/shell/emulated/obb, 0, 0)
02-01 12:34:16.257: E/cutils(31230): to chown(/storage/emulated/0/Android, 0, 0)
02-01 12:34:16.257: E/cutils(31230): to chown(/storage/emulated/0/Android/obb, 0, 0)
02-01 12:34:16.438: E/AndroidRuntime(31230): FATAL EXCEPTION: main
02-01 12:34:16.438: E/AndroidRuntime(31230): java.lang.RuntimeException: Unable to start activity ComponentInfo{harsha.dbconnection/harsha.dbconnection.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.access0(ActivityThread.java:169)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.os.Handler.dispatchMessage(Handler.java:107)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.os.Looper.loop(Looper.java:194)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.main(ActivityThread.java:5433)
02-01 12:34:16.438: E/AndroidRuntime(31230): at java.lang.reflect.Method.invokeNative(Native Method)
02-01 12:34:16.438: E/AndroidRuntime(31230): at java.lang.reflect.Method.invoke(Method.java:525)
02-01 12:34:16.438: E/AndroidRuntime(31230): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
02-01 12:34:16.438: E/AndroidRuntime(31230): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
02-01 12:34:16.438: E/AndroidRuntime(31230): at dalvik.system.NativeStart.main(Native Method)
02-01 12:34:16.438: E/AndroidRuntime(31230): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ListActivity.onContentChanged(ListActivity.java:243)
02-01 12:34:16.438: E/AndroidRuntime(31230): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:277)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.Activity.setContentView(Activity.java:1895)
02-01 12:34:16.438: E/AndroidRuntime(31230): at harsha.dbconnection.MainActivity.onCreate(MainActivity.java:37)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.Activity.performCreate(Activity.java:5179)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
02-01 12:34:16.438: E/AndroidRuntime(31230): ... 11 more
尝试在 xml 文件中将列表视图的 ID 更改为 android:id="@android:id/list",因为您扩展了 ListActivity 所以它会尝试查找默认 ID。如果扩展 ListActivity,则无需在 Activity 中声明 ListView
试试这个 link 了解更多信息:http://developer.android.com/reference/android/app/ListActivity.html
我是 Android 开发新手。
我想要 table 值的完整列表 [来自 Select * 来自产品] 显示在 Android 的 'ListView' 中。
所以,我遵循了几个教程并编写了自己的项目,但是,在启动和应用程序时我仍然遇到异常 'unexpectedly closes'。有人请告诉我代码有什么问题。
我的数据库是在网络服务器上创建的。所以,我将把所有 PHP 文件也放在一起。
get_all_products.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_access.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT * FROM products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["products"], $product);
}
// 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);
}
?>
db_access.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "something"); // database name
define('DB_SERVER', "myhost"); // db server
?>
MySQL 条目
CREATE TABLE products(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
);
INSERT INTO `products` (
`pid` ,
`name` ,
`price` ,
`description` ,
`created_at` ,
`updated_at`
)
VALUES (
NULL , 'iPhone', '678', 'Awesome Phone', '2015-02-01 03:13:31', '2015-02-02 09:27:35'
);
MainActivity.java
public class MainActivity extends ListActivity {
ListView lv;
JSONArray products = null;
ArrayList<HashMap<String, String>> productsList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
productsList = new ArrayList<HashMap<String, String>>();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
lv = (ListView)findViewById(R.id.list);
lv = getListView();
LoadAllProducts();
}
public void LoadAllProducts() {
Thread th = new Thread(new Runnable() {
@Override
public void run() {
JSONObject json = getUserObject("http://myweb.com/get_all_products.php");
Log.i("My json",json.toString());
try {
int success = json.getInt("success");
if (success == 1) {
products = json.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String id = c.getString("pid");
String name = c.getString("name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("pid", id);
map.put("name", name);
productsList.add(map);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, productsList,
R.layout.list_item, new String[] { "pid",
"name"},
new int[] { R.id.pid, R.id.name });
// updating list view
setListAdapter(adapter);
}
});
}
});
th.start();
}
public static JSONObject getUserObject(String url){
JSONObject jObj = null;
String json = null;
try
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
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();
InputStream is = httpEntity.getContent();
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
catch(Exception e)
{
Log.i("NetworkTest", "Network Error: " + e);
}
return jObj;
}
}
all_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/pid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
抱歉,如果问题很长,因为我还是新手。但是,有人可以帮忙吗?谢谢!
错误日志cat
02-01 12:34:16.256: E/cutils(31230): to chown(/mnt/shell/emulated/0, 0, 0)
02-01 12:34:16.256: E/cutils(31230): to chown(/mnt/shell/emulated/obb, 0, 0)
02-01 12:34:16.257: E/cutils(31230): to chown(/storage/emulated/0/Android, 0, 0)
02-01 12:34:16.257: E/cutils(31230): to chown(/storage/emulated/0/Android/obb, 0, 0)
02-01 12:34:16.438: E/AndroidRuntime(31230): FATAL EXCEPTION: main
02-01 12:34:16.438: E/AndroidRuntime(31230): java.lang.RuntimeException: Unable to start activity ComponentInfo{harsha.dbconnection/harsha.dbconnection.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.access0(ActivityThread.java:169)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.os.Handler.dispatchMessage(Handler.java:107)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.os.Looper.loop(Looper.java:194)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.main(ActivityThread.java:5433)
02-01 12:34:16.438: E/AndroidRuntime(31230): at java.lang.reflect.Method.invokeNative(Native Method)
02-01 12:34:16.438: E/AndroidRuntime(31230): at java.lang.reflect.Method.invoke(Method.java:525)
02-01 12:34:16.438: E/AndroidRuntime(31230): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
02-01 12:34:16.438: E/AndroidRuntime(31230): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
02-01 12:34:16.438: E/AndroidRuntime(31230): at dalvik.system.NativeStart.main(Native Method)
02-01 12:34:16.438: E/AndroidRuntime(31230): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ListActivity.onContentChanged(ListActivity.java:243)
02-01 12:34:16.438: E/AndroidRuntime(31230): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:277)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.Activity.setContentView(Activity.java:1895)
02-01 12:34:16.438: E/AndroidRuntime(31230): at harsha.dbconnection.MainActivity.onCreate(MainActivity.java:37)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.Activity.performCreate(Activity.java:5179)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
02-01 12:34:16.438: E/AndroidRuntime(31230): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
02-01 12:34:16.438: E/AndroidRuntime(31230): ... 11 more
尝试在 xml 文件中将列表视图的 ID 更改为 android:id="@android:id/list",因为您扩展了 ListActivity 所以它会尝试查找默认 ID。如果扩展 ListActivity,则无需在 Activity 中声明 ListView 试试这个 link 了解更多信息:http://developer.android.com/reference/android/app/ListActivity.html