Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/220.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android从listview填充listview_Java_Android_Json_Android Listview_Android Asynctask - Fatal编程技术网

Java Android从listview填充listview

Java Android从listview填充listview,java,android,json,android-listview,android-asynctask,Java,Android,Json,Android Listview,Android Asynctask,用户导航到此页面后发生的第一件事是应用程序使用远程数据库中的状态列表填充listview。然后用户选择一个州,应用程序返回数据库,获取该州的县的列表。 各州加载良好,问题是各州不加载。在日志中,它显示页面正在返回一个空数组。如果我去那一页 它很好用。我不确定问题是不是因为没有抛出错误,而且它在第一次获取状态时运行良好 这是我的密码: package com.example.hospitals; import java.util.ArrayList; import java.util.HashM

用户导航到此页面后发生的第一件事是应用程序使用远程数据库中的状态列表填充listview。然后用户选择一个州,应用程序返回数据库,获取该州的县的列表。 各州加载良好,问题是各州不加载。在日志中,它显示页面正在返回一个空数组。如果我去那一页 它很好用。我不确定问题是不是因为没有抛出错误,而且它在第一次获取状态时运行良好

这是我的密码:

package com.example.hospitals;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
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;


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

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

    ArrayList<HashMap<String, String>> statesList;
    ArrayList<HashMap<String, String>> countyList;


    // urls 
    private static String url_states = "http://photosbychristian.com/ems/get_states.php";
    String url_countys;

    // JSON Node names for states
    private static final String TAG_STATES = "states";
    private static final String TAG_TB_NAME = "tbname";
    private static final String TAG_NAME = "name";
    private static final String TAG_ABBR = "Abbr";

    //JSON Node names for countys
    private static final String TAG_COUNTYS = "countys";
    private static final String TAG_NAME_COUNTY = "name";



    // JSONArrays
    JSONArray states = null;
    JSONArray countys = null;

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

        //path.setText("");
        // Hashmap for ListView
        statesList = new ArrayList<HashMap<String, String>>();
        countyList = new ArrayList<HashMap<String, String>>();

        // Loading states in Background Thread
        new LoadAllStates().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 abbr = ((TextView) view.findViewById(R.id.abbr)).getText().toString();
                String cf = ((TextView) view.findViewById(R.id.comingFrom)).getText().toString();
                TextView path = (TextView)findViewById(R.id.path); 
                Log.d("Coming From",cf);

                if (cf == "1"){//countys
                    path.append(abbr + " > ");
                    url_countys = "http://photosbychristian.com/ems/get_countys.php?state="+abbr;
                    Log.d("url", url_countys);
                    new LoadAllCountys().execute(); 

                }else if(cf == "2"){//citys
                    path.append(abbr + " > ");

                }else if (cf == "3"){//hospitals
                    path.append(abbr);


                }


            }
        });

    }

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

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

        /**
         * getting all staets 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_states, "GET", params);

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

            try {
                    // products found
                    // Getting Array of Products
                    states = json.getJSONArray(TAG_STATES);

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

                        // Storing each json item in variable
                        String table = c.getString(TAG_TB_NAME);
                        String name = c.getString(TAG_NAME);
                        String abbr = c.getString(TAG_ABBR);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_TB_NAME, table);
                        map.put(TAG_NAME, name);
                        map.put(TAG_ABBR, abbr);
                        map.put("ComingFrom", "1");

                        // adding HashList to ArrayList
                        statesList.add(map);
                    }

            } 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(
                            Add.this, 
                            statesList, 
                            R.layout.hospital_items, 
                            new String[] { TAG_TB_NAME, TAG_ABBR, TAG_NAME, "ComingFrom"},  
                            new int[] { R.id.id, R.id.abbr, R.id.name, R.id.comingFrom }
                     );
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }

    class LoadAllCountys extends AsyncTask<String, String, String> {

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

        /**
         * getting all staets from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject jsonCo = jParserCo.makeHttpRequest(url_countys, "GET", params);

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

            try {
                    // products found
                    // Getting Array of Products
                    countys = jsonCo.getJSONArray(TAG_COUNTYS);

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

                        // Storing each json item in variable
                        String name = c.getString(TAG_NAME_COUNTY);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_NAME_COUNTY, name);
                        map.put("ComingFrom", "2");

                        // adding HashList to ArrayList
                        countyList.add(map);
                    }

            } 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
            cDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            Add.this, 
                            countyList, 
                            R.layout.hospital_items, 
                            new String[] {TAG_NAME, "ComingFrom"},  
                            new int[] { R.id.name, R.id.comingFrom }
                     );
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }

}
package.com.example.hospitals;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入org.apache.http.NameValuePair;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
公共类添加扩展ListActivity{
//进度对话框
私人对话;
私有进程对话;
//创建JSON解析器对象
JSONParser jParser=新的JSONParser();
JSONParser jParserCo=新的JSONParser();
ArrayList statesList;
ArrayList countyList;
//网址
私有静态字符串url_states=”http://photosbychristian.com/ems/get_states.php";
字符串url_countys;
//状态的JSON节点名称
私有静态最终字符串标记_STATES=“STATES”;
私有静态最终字符串标记\u TB\u NAME=“tbname”;
私有静态最终字符串标记_NAME=“NAME”;
私有静态最终字符串标记_ABBR=“ABBR”;
//countys的JSON节点名称
私有静态最终字符串标记_COUNTYS=“COUNTYS”;
私有静态最终字符串标记\u NAME\u COUNTY=“NAME”;
//JSONArrays
JSONArray状态=null;
JSONArray countys=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
//path.setText(“”);
//ListView的Hashmap
statesList=newarraylist();
countyList=新的ArrayList();
//后台线程中的加载状态
新建LoadAllState().execute();
//获取列表视图
ListView lv=getListView();
//论单产品的选择
//启动编辑产品屏幕
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
//从选定的ListItem获取值
字符串abbr=((TextView)view.findviewbyd(R.id.abbr)).getText().toString();
字符串cf=((TextView)view.findViewById(R.id.comingFrom)).getText().toString();
TextView路径=(TextView)findViewById(R.id.path);
Log.d(“来自”,cf);
如果(cf==“1”){//countys
path.append(缩写+“>”);
url_countys=”http://photosbychristian.com/ems/get_countys.php?state=“+abbr;
Log.d(“url”,url\u countys);
新建LoadAllCountys().execute();
}如果(cf==“2”){//citys
path.append(缩写+“>”);
}else if(cf==“3”){//
追加路径(缩写);
}
}
});
}
/**
*通过发出HTTP请求加载所有产品的后台异步任务
* */
类LoadAllState扩展了AsyncTask{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(Add.this);
setMessage(“正在加载状态,请稍候”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
/**
*从url获取所有状态
* */
受保护的字符串doInBackground(字符串…args){
//建筑参数
List params=new ArrayList();
//从URL获取JSON字符串
JSONObject json=jParser.makeHttpRequest(url_表示“GET”,参数);
//检查日志cat中的JSON响应
Log.d(“所有状态:,json.toString());
试一试{
//发现的产品
//获取一系列产品
states=json.getJSONArray(TAG_states);
//在所有产品中循环
对于(int i=0;ivalue
map.put(TAG_TB_NAME,table);
地图放置(标签名称、名称);
地图放置(TAG_ABBR,ABBR);
地图放置(“来自”、“1”);
//将哈希列表添加到ArrayList
statesList.add(地图);
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
/**
*完成背景助教后
mAdapter.setListData(mSubMenu);

mAdapter.notifyDataSetChanged();
mJsonString = downloadFileFromInternet(urls[0]);

if(mJsonString == null)
    return false;

JSONObject jObject = null;
jObject = new JSONObject(mJsonString);

----

    private String downloadFileFromInternet(String url)
        {
            if(url == null /*|| url.isEmpty() == true*/)
                new IllegalArgumentException("url is empty/null");
            StringBuilder sb = new StringBuilder();
            InputStream inStream = null;
            try
            {
                url = urlEncode(url);
                URL link = new URL(url);
                inStream = link.openStream();
                int i;
                int total = 0;
                byte[] buffer = new byte[8 * 1024];
                while((i=inStream.read(buffer)) != -1)
                {
                    if(total >= (1024 * 1024))
                    {
                        return "";
                    }
                    total += i;
                    sb.append(new String(buffer,0,i));
                }
            }catch(Exception e )
            {
                e.printStackTrace();
                return null;
            }catch(OutOfMemoryError e)
            {
                e.printStackTrace();
                return null;
            }
            return sb.toString();
        }

        private String urlEncode(String url)
        {
            if(url == null /*|| url.isEmpty() == true*/)
                return null;
            url = url.replace("[","");
            url = url.replace("]","");
            url = url.replaceAll(" ","%20");
            return url;
        }