繁体   English   中英

Android Listview无法正常工作?

[英]Android Listview not working properly?

我最近一直在使用教程来为我的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上对其进行了测试,并且显示了我想要的内容。

logcat的:

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

我的列表视图文件没有错误。 add_profile具有ID / list的列表视图,list_item具有ID / pid和ID / name的两个文本视图。 有什么想法吗?

您没有正确解析JSON。

"UserProfile" != "userprofile"

要从JSON获取值,必须使用适当的键。 因为您使用了不正确的键, org.json.JSONException会抛出org.json.JSONException ,并且在大多数情况下,您应该注意抛出的异常。 :)

您需要更改此:

private static final String TAG_USERPROFILE = "userprofile";

private static final String TAG_USERPROFILE = "UserProfile";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM