ListView不显示JSON数据

时间:2017-03-22 13:12:05

标签: android json listview

我正在使用网络服务创建一个Android应用程序,其中给出地名将搜索邮政编码并显示在ListView中。但是我的ListView没有显示来自服务器的JSON数据。请指教..

MainActivity.java     `

public class MainActivity extends AppCompatActivity {
    private EditText etSearch;
    private ListView lv;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etSearch = (EditText) findViewById(R.id.editText);
        lv = (ListView) findViewById(R.id.listView);
    }

    public void onClick(View view){
        String place = etSearch.getText().toString();
        if(place.length()>0){
            progressDialog = ProgressDialog.show(MainActivity.this,"Postal Code Search","Please Wait");
            SearchTask task = new SearchTask();
            task.execute(place);
        }else {
            Toast.makeText(this,"Please enter place Name",Toast.LENGTH_LONG).show();
        }
    }
    private ArrayList<String> searchResult = new ArrayList<>();

    private class SearchTask extends AsyncTask<String,Void,JSONObject>{

        @Override
        protected JSONObject doInBackground(String... params) {
            JSONObject result = null;
            String placeName = params[0];

            try {
                String urlS = "http://api.geonames.org/postalCodeSearchJSON?placename="
                        + URLEncoder.encode(placeName, "UTF-8")
                        + "&maxRows=10&username=USERNAME";

                URL url = new URL(urlS);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(15000);
                connection.setConnectTimeout(15000);
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String resp = reader.readLine();
                Log.d("result",resp);
                result = new JSONObject(resp);
            } catch (Exception e){
                Log.e("SearchTask", "Error:"+e.getMessage());
            }
            return result;
        }

        @Override
        protected void onPostExecute(JSONObject response) {
            progressDialog.cancel();
            searchResult.clear();
            if(response != null){
                try{
                    JSONArray postalCodes = response.getJSONArray("postalCodes");
                    for (int i=0;i<postalCodes.length();i++){
                        JSONObject obj = postalCodes.getJSONObject(i);
                        String postalCode = obj.getString("postalCode");
                        String placeName = obj.getString("placeName");
                        searchResult.add("PlaceName: "+placeName+"\nPostalCode: "+postalCode);
                    }
                    if(searchResult.isEmpty()){
                        searchResult.add("No postal code Found");
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,searchResult);
                        lv.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    }
                } catch (JSONException je){
                    Toast.makeText(MainActivity.this,"Parsing Error:"+je.getMessage(),Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(MainActivity.this,"Couldn't Find",Toast.LENGTH_LONG).show();
            }

        }
    }

}
`

这是UI部分。   的 Activity.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.priya.geocodeapp.MainActivity"

    android:weightSum="1">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.25"
        android:text="Search Postal Code "
        android:textAlignment="center"
        android:textColor="@android:color/holo_blue_bright"
        android:textSize="14sp"
        android:textStyle="bold"
        android:typeface="sans" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.07"
        android:ems="10"
        android:hint="Enter Place Name"
        android:inputType="textPersonName"
        android:textSize="14sp"
        android:layout_marginTop="29dp"
        android:layout_below="@+id/textView"
        android:layout_alignParentEnd="true" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0.05"
        android:gravity="center"
        android:onClick="onClick"
        android:text="Search"
        android:layout_marginTop="18dp"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="333dp"

        android:layout_marginTop="34dp"
        android:layout_below="@+id/button"
        android:layout_alignParentStart="true" />


</RelativeLayout>`

JSON数据以班加罗尔为例。 例如,

{  
   "postalCodes":[  
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore North",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.59443998336792,
         "countryCode":"IN",
         "postalCode":"560001",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Bangalore G.P.O.",
         "lat":12.991448503615459
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore North",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.59443998336792,
         "countryCode":"IN",
         "postalCode":"560001",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Bangalore Bazaar",
         "lat":12.991448503615459
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore North",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.59443998336792,
         "countryCode":"IN",
         "postalCode":"560001",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Rajbhavan (Bangalore)",
         "lat":12.991448503615459
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore South",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.59368896484375,
         "countryCode":"IN",
         "postalCode":"560002",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Bangalore Corporation Building",
         "lat":12.97194016928975
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore North",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.12604139137574,
         "countryCode":"IN",
         "postalCode":"560009",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Bangalore Dist Offices Bldg",
         "lat":13.0642536587272
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore North",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.54905700683594,
         "countryCode":"IN",
         "postalCode":"560010",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Industrial Estate (Bangalore)",
         "lat":12.984736805762962
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore South",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.5673389434814,
         "countryCode":"IN",
         "postalCode":"560018",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Chamrajpet (Bangalore)",
         "lat":12.9603975402696
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore North",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.54813032113138,
         "countryCode":"IN",
         "postalCode":"560024",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Anandnagar (Bangalore)",
         "lat":12.971373314490803
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore North",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.640380859375,
         "countryCode":"IN",
         "postalCode":"560038",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Indiranagar (Bangalore)",
         "lat":12.974282086640057
      },
      {  
         "adminCode2":"572",
         "adminName3":"Bangalore North",
         "adminCode1":"19",
         "adminName2":"Bangalore",
         "lng":77.32035308234025,
         "countryCode":"IN",
         "postalCode":"560040",
         "adminName1":"Karnataka",
         "ISO3166-2":"KA",
         "placeName":"Vijayanagar (Bangalore)",
         "lat":13.00637724835858
      }
   ]
}

它应该在ListView中显示此JSON数据。该程序运行正常,没有任何错误。 JSON数据显示在logcat中,但不显示在ListView中。我搜索了所有的stackoverflow解决方案,但没有任何对我有用。

1 个答案:

答案 0 :(得分:1)

您的逻辑错误,您正在检查数据是否为空。像这样更改你的代码:

if(!searchResult.isEmpty()){

                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,searchResult);
                        lv.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    }

使用&#34;!&#34;更改布尔值