php - ListView 与 android mysql 数据库使用 php

标签 php android mysql listview

我正在制作一个连接到外部 mysql 数据库 的 android 应用程序,并且我有一个loginregistration 功能在上面工作。

我的数据库中有一个名为 lessons 的表,其中包含列名称和时间。我一直在寻找一种方法来读取数据库并在 ListView 中显示该表的内容,但我找不到任何适合我的方法。

我意识到有很多类似的问题,但我没有发现任何有用的问题,我真的开始挣扎了。

这是我的 Activity 页面:

package com.example.studentregister;

//imports

import com.example.studentregister.library.JSONParser;
import com.example.studentregister.R;

public class ProfilePage extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> lessonList;

// url to get all products list
private static String url_all_lessons = "http://192.168.0.6/android_login_api/get_all_lessons.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_LESSONS = "lessons";
private static final String TAG_PID = "uid";
private static final String TAG_NAME = "name";

// products JSONArray
JSONArray lessons = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.profilepage);

    // Hashmap for ListView
    lessonList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();



}

// Response from Edit Product 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 edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ProfilePage.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_lessons, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                lessons = json.getJSONArray(TAG_LESSONS);

                // looping through All Products
                for (int i = 0; i < lessons.length(); i++) {
                    JSONObject c = lessons.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    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_PID, id);
                    map.put(TAG_NAME, name);

                    // adding HashList to ArrayList
                    lessonList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } 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(
                        ProfilePage.this, lessonList,
                        R.layout.eachlesson, new String[] { TAG_PID,
                                TAG_NAME},
                        new int[] { R.id.uid, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
} 

这是我的两个 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView
         Always give id value as list(@android:id/list)
    -->
<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <!-- Name Label -->
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="6dip"
        android:textSize="17dip"
        android:textStyle="bold" />

</LinearLayout>

atm 的问题是列表适配器中的 uid

new int[] { R.id.uid, R.id.name });

无法解析或不是字段。但是我在另一个项目中有这个例子没有那个错误,但是页面上没有任何显示。

最佳答案

我不是很肯定(在 Android 上使用 MySql 时),但是在使用 sqlite 时,您必须有一个名为 _id 的文件,否则它将不起作用。我会从你的 mysql 数据库开始。您还必须在显示数据时选择该字段,否则它将不起作用。我花了几个小时来处理这个具体问题。

关于php - ListView 与 android mysql 数据库使用 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15754397/

相关文章:

数据库;使用位置的时区选择昨天(午夜到午夜)的所有记录

php $_POST 变量作为 mysql 查询中的列名

php - 数据库中的口音

php - 在正常价格之前显示销售价格 (WooCommerce)

android - 如果我在Android中使用Telegram api,是否需要服务器?

mysql - 表达式引擎 : git : local development : remote database

php - 使用 array_diff 比较关联数组和数值数组

javascript - 使用 JavascriptInterface 时未捕获的类型错误

将手势与模式相匹配的 Android 库?

php - 查询两个表,选择两个字段匹配的数据