简体   繁体   English

ListView不显示JSON数据

[英]ListView not displaying the JSON data

I am creating a android app using web services, In which giving the place name will search the postal code and display in ListView. 我正在使用Web服务创建一个android应用,在其中提供地名将搜索邮政编码并显示在ListView中。 But my ListView is not displaying the JSON data from the server. 但是我的ListView没有显示来自服务器的JSON数据。 Please advice.. 请指教..

MainActivity.java ` 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();
            }

        }
    }

}
`

This is the UI part. 这是UI部分。 Activity.xml 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 data Its for Bangalore as an example. JSON数据以班加罗尔为例。 For eg 例如

{  
   "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
      }
   ]
}

It should display this JSON data in the ListView. 它应该在ListView中显示此JSON数据。 The program is running fine without any errors. 该程序运行正常,没有任何错误。 The JSON data is displayed in the logcat but not the ListView. JSON数据显示在日志猫中,而不显示在ListView中。 I searched all the stackoverflow solution but nothing worked for me. 我搜索了所有的stackoverflow解决方案,但没有任何帮助。

Your logic is wrong, you are checking if your data is empty. 您的逻辑错误,正在检查数据是否为空。 Change your code like this: 像这样更改代码:

if(!searchResult.isEmpty()){

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

Use the "!" 使用 ”!” to change the boolean value 更改布尔值

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

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