MySQL表中的MySQL表值到Android中

时间:2021-09-05 13:02:54

I'm New to Android Development.

我是Android开发的新手。

I wanted a complete list of table values [By Select * from products] to be displayed in the 'ListView' in Android.

我想要一个完整的表值列表[By Select * from products]显示在Android的'ListView'中。

So, I followed several tutorials and coded my own project but, I still get an exception at the launch and application 'unexpectedly closes'. Somebody please tell me what's wrong with the code.

所以,我遵循了几个教程并编写了我自己的项目,但是,我仍然在启动和应用程序'意外关闭'时遇到异常。有人请告诉我代码有什么问题。

My database is created in a web server. So, I'll put all the PHP Files also.

我的数据库是在Web服务器中创建的。所以,我也会把所有的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 Entries

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>

Sorry, If question was long as I'm still new. But, Can Somebody please help ? Thank You!

对不起,如果问题很长,我还是新人。但是,有人可以帮忙吗?谢谢!

Error Log 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.access$600(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

1 个解决方案

#1


1  

try change id of your listview as android:id="@android:id/list" in xml file, as you extends ListActivity so it try to find default id. no need to declare ListView in Activity if you extends ListActivity try this link for more info: http://developer.android.com/reference/android/app/ListActivity.html

在xml文件中尝试将listview的id更改为android:id =“@ android:id / list”,因为您扩展了ListActivity,因此它尝试查找默认ID。如果扩展ListActivity,则无需在Activity中声明ListView请尝试此链接以获取更多信息:http://developer.android.com/reference/android/app/ListActivity.html

#1


1  

try change id of your listview as android:id="@android:id/list" in xml file, as you extends ListActivity so it try to find default id. no need to declare ListView in Activity if you extends ListActivity try this link for more info: http://developer.android.com/reference/android/app/ListActivity.html

在xml文件中尝试将listview的id更改为android:id =“@ android:id / list”,因为您扩展了ListActivity,因此它尝试查找默认ID。如果扩展ListActivity,则无需在Activity中声明ListView请尝试此链接以获取更多信息:http://developer.android.com/reference/android/app/ListActivity.html