java - Android Listview 无法正常工作?

标签 java android listview debugging logcat

我最近一直在使用教程为我的 Android 应用程序开发 CRUD 操作。这些类不包含任何错误,应用程序与我的本地主机同步。但是,当我想单击一个按钮来查看我的所有用户配置文件时,我得到一个空白屏幕,但我的 logCat 显示一条成功消息?

请帮忙!

控制查看的类:

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 org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AllProfile extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

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

    ArrayList<HashMap<String, String>> profileList;

    // url to get all products list
    private static String url_all_profile = "http://MYIPADDRESS:8888/android_connect/get_all_profiles.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_USERPROFILE = "userprofile";
    private static final String TAG_PID = "pid";
    private static final String TAG_FIRSTNAME = "firstname";

    // products JSONArray
    JSONArray userprofile = null;

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

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

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

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditProfile.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }


    // 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 LoadAllProfile extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProfile.this);
            pDialog.setMessage("Loading profiles. 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_profile, "GET", params);

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

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

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

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

                        // Storing each json item in variable
                        String pid = c.getString(TAG_PID);
                        String firstname = c.getString(TAG_FIRSTNAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, pid);
                        map.put(TAG_FIRSTNAME, firstname);

                        // adding HashList to ArrayList
                        profileList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            AddProfile.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(
                            AllProfile.this, profileList,
                            R.layout.list_item, new String[] { TAG_PID,
                            TAG_FIRSTNAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

我的 php 正在运行,因为我已经调试它并在 HTML 上对其进行了测试,它显示了我想要的内容。

日志:

02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme D/All Profiles:﹕ {"success":1,"UserProfile":[{"updated_at":"0000-00-00 00:00:00","address":"Tottenham Hale","age":"21","created_at":"2015-02-04 21:22:09","gender":"Male","lastname":"Sharma","pid":"4","firstname":"Ankhit","comments":"Help Me"}]}
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ org.json.JSONException: No value for userprofile
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:544)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at com.example.ankhit.saveme.AllProfile$LoadAllProfile.doInBackground(AllProfile.java:144)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at com.example.ankhit.saveme.AllProfile$LoadAllProfile.doInBackground(AllProfile.java:110)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-04 22:11:59.189  20039-20371/com.example.ankhit.saveme W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
02-04 22:11:59.199  20039-20039/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
02-04 22:11:59.199  20039-20039/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
02-04 22:11:59.209  20039-20039/com.example.ankhit.saveme E/ViewRootImpl﹕ sendUserActionEvent() mView == null

我的 ListView 文件没有错误。 add_profile 有一个带有 id/list 的 ListView ,而 list_item 有两个分别带有 id/pid 和 id/name 的 TextView 。有什么想法吗?

最佳答案

您没有正确解析 JSON。

"UserProfile" != "userprofile"

要从 JSON 中获取值,您必须使用适当的键。因为您使用了不正确的键,org.json.JSONException 被抛出,大多数时候,您应该处理抛出的异常。 :)

关于java - Android Listview 无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28332627/

相关文章:

java - Java 的 FileChannel 的内存版本

java - 如何从句子数组列表中获取包含特定单词的句子?

android - 如何让谷歌地图上的标记标题自动同时显示?

java - TableView和ListView的删除是如何工作的?

Android Listview OnItemClickListener 有时无法正常工作

java - 从java代码访问Apache的unique_id

java - 无法连接到 Remedy AR 系统服务器

java - 使用自定义主题的 actionbar 时如何更改 actionbarsherlock 菜单项字体?

java - Java中如何将字符串从一个方法传递到另一个方法

android - 删除项目后 ListView 不更新