从JSONArray android填充listview

时间:2015-11-03 02:47:13

标签: java android listview android-listview

这个问题基本上是this question

的更新

再次回放,这是country_info.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<LinearLayout
    android:id="@+id/gambar_saja"
    android:layout_width="150dp"
    android:layout_height="160dp"
    android:orientation="vertical">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/n1"/>
</LinearLayout>
<RelativeLayout
    android:id="@+id/detail_country"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:layout_toRightOf="@+id/gambar_saja"
    android:layout_toEndOf="@+id/gambar_saja"
    android:orientation="vertical"
    android:layout_marginLeft="4dp">
    <TextView
        android:id="@+id/code"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="TextView"
        android:textSize="24sp"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginBottom="4dp"/>

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/code"
        android:layout_below="@+id/code"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginBottom="4dp"/>

    <TextView
        android:id="@+id/continent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/name"
        android:text="TextView"
        android:textSize="14sp"
        android:textColor="@android:color/black"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginBottom="4dp"/>

    <TextView
        android:id="@+id/region"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/continent"
        android:layout_below="@+id/continent"
        android:text="TextView"
        android:textSize="14sp"
        android:textColor="@android:color/black"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</RelativeLayout>
</RelativeLayout>

这里是cari_studio.xml,用于将country_info填充到listview(listView1)中:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white">
<RelativeLayout
    android:id="@+id/area"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/isiArea"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:background="@drawable/text_selector"
            android:gravity="center_vertical"
            android:paddingBottom="10dp"
            android:paddingLeft="35dp"
            android:paddingRight="5dp"
            android:paddingTop="10dp"
            android:text="@string/area"
            android:textColor="@color/black"
            android:textSize="14sp"
            android:visibility="visible"/>
        <Spinner
            android:id="@+id/textArea"
            android:layout_marginRight="15dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="@string/area"
            android:textColor="@color/black"
            android:inputType="text"
            android:textSize="14sp"/>
    </LinearLayout>
</RelativeLayout>
<RelativeLayout
    android:id="@+id/list_area_studio"
    android:layout_below="@+id/area"
    android:layout_width="match_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:padding="10dp"
            android:text="@string/cari_studio" android:textSize="20sp" />

        <EditText android:id="@+id/myFilter" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:ems="10"
            android:hint="@string/studio_hint">
            <requestFocus />
        </EditText>

        <ListView android:id="@+id/listView1" android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </LinearLayout>
</RelativeLayout>
<RelativeLayout
    android:id="@+id/bottom_navigation_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:background="@drawable/navbar_background"
        >
        <RadioButton
            android:id="@+id/btnAll"
            style="@style/navbar_button"
            android:drawableTop="@drawable/navbar_allselector"
            android:text="All"
            />
        <RadioButton
            android:id="@+id/btnPicture"
            style="@style/navbar_button"
            android:drawableTop="@drawable/navbar_pictureselector"
            android:text="Pictures"
            android:layout_marginLeft="5dp"
            />
        <RadioButton
            android:id="@+id/btnVideo"
            style="@style/navbar_button"
            android:drawableTop="@drawable/navbar_videoselector"
            android:text="Videos"
            android:layout_marginLeft="5dp"
            />
        <RadioButton
            android:id="@+id/btnFile"
            style="@style/navbar_button"
            android:drawableTop="@drawable/navbar_fileselector"
            android:text="Files"
            android:layout_marginLeft="5dp"
            />
        <RadioButton
            android:id="@+id/btnMore"
            style="@style/navbar_button"
            android:drawableTop="@drawable/navbar_moreselector"
            android:text="More"
            android:layout_marginLeft="5dp"
            />
    </RadioGroup>
    <LinearLayout
        android:id="@+id/floatingmenu"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@drawable/laysemitransparentwithborders"
        android:orientation="vertical"
        android:layout_marginBottom="-4dp"
        android:visibility="gone"
        >
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:paddingTop="15dp"
            android:paddingBottom="15dp"
            android:text="Contacts"
            android:textColor="#ffffff"
            android:textSize="16dp"
            />
        <View
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:background="#ff999999"
            />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:paddingTop="15dp"
            android:paddingBottom="15dp"
            android:text="Calendar"
            android:textColor="#ffffff"
            android:textSize="16dp"
            />
    </LinearLayout>
</RelativeLayout>
</RelativeLayout>

这里是获取JSONArray结果的Cari Studio类(使用帖子),我已经成功获得结果:

public class CariStudio extends Activity{
final Context context = this;
MyCustomAdapter dataAdapter = null;
RadioButton radioButton1, radioButton2, radioButton3, radioButton4, radioButton5;
TextView flexlocationid;
Spinner flexlocation;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> provincelist;
ArrayList<ProvinceModel> province;

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

    //Generate list View from ArrayList
    new DownloadJSON().execute();
    addListenerOnButton();
}
public void addListenerOnButton() {
    Bundle extras = getIntent().getExtras();
    final String token= extras.getString("TOKEN");
    radioButton1 = (RadioButton) findViewById(R.id.btnAll);
    radioButton1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(context, home.class);
            intent.putExtra("TOKEN", token);
            startActivity(intent);
        }
    });
    radioButton2 = (RadioButton) findViewById(R.id.btnPicture);
    radioButton2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(context, CariKelas.class);
            intent.putExtra("TOKEN", token);
            startActivity(intent);
        }
    });
    radioButton3 = (RadioButton) findViewById(R.id.btnVideo);
    radioButton3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(context, CariStudio.class);
            intent.putExtra("TOKEN", token);
            startActivity(intent);
        }
    });
    radioButton4 = (RadioButton) findViewById(R.id.btnFile);
    radioButton4.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(context, HotStuff.class);
            intent.putExtra("TOKEN", token);
            startActivity(intent);
        }
    });
    radioButton5 = (RadioButton) findViewById(R.id.btnMore);
    radioButton5.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(context, MyAccount.class);
            intent.putExtra("TOKEN", token);
            startActivity(intent);
        }
    });
    flexlocation = (Spinner) findViewById(R.id.textArea);
    flexlocationid = (TextView) findViewById(R.id.isiArea);
}
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
    private static final String LOG_TAG = "CariStudio";
    ProgressDialog dialog;
    Bundle extras = getIntent().getExtras();
    final String token= extras.getString("TOKEN");
    @Override
    protected String doInBackground(String... params) {
        String areaid = params[0];
        Utils.log("params 1:"+ areaid);
        // do above Server call here
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("region_id", areaid ));

        String responseString = null;
        final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
        Utils.log("url studio:"+ url_studio);
        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url_studio);

            // no idea what this does :)
            httppost.setEntity(new UrlEncodedFormEntity(postParameters));

            // This is the line that send the request
            HttpResponse response = httpclient.execute(httppost);
            Utils.log("response:"+ response);
            HttpEntity entity = response.getEntity();
            String responseAsText = EntityUtils.toString(entity);
            Utils.log("daftar isi studio: " + responseAsText);
            JSONArray json = new JSONArray(responseAsText);
            for (int i = 0; i < json.length(); i++) {
                jsonobject = json.getJSONObject(i);
                final String studio_name = jsonobject.getString("studio_name");
                final String address = jsonobject.getString("address");
                final String website = jsonobject.getString("website");
                final String seo_url = jsonobject.getString("seo_url");
                Utils.log("studio_name: " + studio_name);
                runOnUiThread(new Runnable() {
                    public void run() {
                        ArrayList<Country> countryList = new ArrayList<Country>();
                        Country country = new Country(studio_name,address, "Website:"+ website,
                                "Fasilitas:"+ seo_url);
                        countryList.add(country);
                        //create an ArrayAdaptar from the String Array
                        dataAdapter = new MyCustomAdapter(context,
                                R.layout.country_info, countryList);
                        //enables filtering for the contents of the given ListView
                        ListView listView = (ListView) findViewById(R.id.listView1);
                        // Assign adapter to ListView
                        listView.setAdapter(dataAdapter);
                        listView.setTextFilterEnabled(true);

                        listView.setOnItemClickListener(new OnItemClickListener() {
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                // When clicked, show a toast with the TextView text
                                Country country = (Country) parent.getItemAtPosition(position);
                                Toast.makeText(getApplicationContext(),
                                        country.getCode(), Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(context, checkin.class);
                                startActivity(intent);
                            }
                        });
                        EditText myFilter = (EditText) findViewById(R.id.myFilter);
                        myFilter.addTextChangedListener(new TextWatcher() {

                            public void afterTextChanged(Editable s) {
                            }

                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                            }

                            public void onTextChanged(CharSequence s, int start, int before, int count) {
                                dataAdapter.getFilter().filter(s.toString());
                            }
                        });
                    }
                });
            }
        }
        catch (Exception e)
        {
            /*Toast.makeText(context,
                    "user not registered", Toast.LENGTH_SHORT).show();*/
            Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
        }
        return "processing";
    }

    protected void onPostExecute(Boolean result) {
        //dialog.cancel();
    }
}
// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        // Locate the CariStudio Class
        province = new ArrayList<ProvinceModel>();
        // Create an array to populate the spinner
        provincelist = new ArrayList<String>();
        // JSON file URL address
        final String url_flexlocation = Constant.URI_BASE_FLEXLOCATION;
        Utils.log("url_flexlocation: " + url_flexlocation);

        try {
            // Locate the NodeList name
            HttpGet httppost = new HttpGet(url_flexlocation);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity);
            Utils.log("data: " + data);
            JSONArray json = new JSONArray(data);
            for (int i = 0; i < json.length(); i++) {
                jsonobject = json.getJSONObject(i);

                ProvinceModel worldpop = new ProvinceModel();

                worldpop.setId(jsonobject.optString("flex_id"));
                worldpop.setProvince(jsonobject.optString("name"));
                province.add(worldpop);

                // Populate spinner with province names
                provincelist.add(jsonobject.optString("name"));

            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in cari_studio.xml
        Spinner mySpinner = (Spinner) findViewById(R.id.textArea);

        // Spinner adapter
        mySpinner
                .setAdapter(new ArrayAdapter<String>(CariStudio.this,
                        R.layout.spinner_white,
                        provincelist));
        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                                               View arg1, int position, long arg3) {
                        // TODO Auto-generated method stub
                        // Locate the textviews in cari_studio.xml
                        TextView flexlocationid = (TextView) findViewById(R.id.isiArea);

                        // Set the text followed by the position
                        flexlocationid.setText(province.get(position).getId());
                        String areaid = flexlocationid.getText().toString();
                        Utils.log("area id:" + areaid);
                        SendfeedbackJob job = new SendfeedbackJob();
                        job.execute(areaid);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
private class MyCustomAdapter extends ArrayAdapter<Country> {

    private ArrayList<Country> originalList;
    private ArrayList<Country> countryList;
    private CountryFilter filter;

    public MyCustomAdapter(Context context, int textViewResourceId,
                           ArrayList<Country> countryList) {
        super(context, textViewResourceId, countryList);
        this.countryList = new ArrayList<Country>();
        this.countryList.addAll(countryList);
        this.originalList = new ArrayList<Country>();
        this.originalList.addAll(countryList);
    }

    @Override
    public Filter getFilter() {
        if (filter == null){
            filter  = new CountryFilter();
        }
        return filter;
    }


    private class ViewHolder {
        TextView code;
        TextView name;
        TextView continent;
        TextView region;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        Log.v("ConvertView", String.valueOf(position));
        if (convertView == null) {

            LayoutInflater vi = (LayoutInflater)getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.country_info, null);

            holder = new ViewHolder();
            holder.code = (TextView) convertView.findViewById(R.id.code);
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.continent = (TextView) convertView.findViewById(R.id.continent);
            holder.region = (TextView) convertView.findViewById(R.id.region);

            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Country country = countryList.get(position);
        holder.code.setText(country.getCode());
        holder.name.setText(country.getName());
        holder.continent.setText(country.getContinent());
        holder.region.setText(country.getRegion());

        return convertView;

    }

    private class CountryFilter extends Filter
    {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            constraint = constraint.toString().toLowerCase();
            FilterResults result = new FilterResults();
            if(constraint != null && constraint.toString().length() > 0)
            {
                ArrayList<Country> filteredItems = new ArrayList<Country>();

                for(int i = 0, l = originalList.size(); i < l; i++)
                {
                    Country country = originalList.get(i);
                    if(country.toString().toLowerCase().contains(constraint))
                        filteredItems.add(country);
                }
                result.count = filteredItems.size();
                result.values = filteredItems;
            }
            else
            {
                synchronized(this)
                {
                    result.values = originalList;
                    result.count = originalList.size();
                }
            }
            return result;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {

            countryList = (ArrayList<Country>)results.values;
            notifyDataSetChanged();
            clear();
            for(int i = 0, l = countryList.size(); i < l; i++)
                add(countryList.get(i));
            notifyDataSetInvalidated();
        }
    }
}
}

我从Utils.log获得的结果(&#34; daftar isi studio:&#34; + responseAsText):

[{"id":"8","studio_name":"Dodi fit","seo_url":"dodi-fit","address":"Komp. Pertanian Blok 5 No 3","postcode":"87473","area_phone":"","phone":"+62876543","area_phone_second":"","phone_second":"+62","website":"sucifir.com","region_id":"12","lokasi_id":"138","booking_window":"7","facebook":"dodifitfb","twitter":"dodifittw","how_to_get_there":"over there, by trun left and right","priority":"5"},{"id":"11","studio_name":"inu fit","seo_url":"inu-fit","address":"","postcode":"","area_phone":"","phone":"+6221324234","area_phone_second":"","phone_second":"","website":"","region_id":"11","lokasi_id":"137","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"5","studio_name":"Vstudio","seo_url":"vstudio","address":"Plaza Indonesia Ground Floor #541","postcode":"","area_phone":"","phone":"+6221453787","area_phone_second":"","phone_second":"","website":"www.jkiij.com","region_id":"12","lokasi_id":"137","booking_window":"0","facebook":"face","twitter":"twy","how_to_get_there":"","priority":"5"},{"id":"7","studio_name":"Infovendor","seo_url":"infovendor","address":"","postcode":"","area_phone":"","phone":"+6221123452","area_phone_second":"","phone_second":"","website":"www.kidsdngf.com","region_id":"12","lokasi_id":"135","booking_window":"1","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"12","studio_name":"Seleb Fitnes One","seo_url":"selebfitnesone-57","address":"Kelapa gading timur no 17","postcode":"","area_phone":"","phone":"+6221453777","area_phone_second":"","phone_second":"","website":"selebfirnes.com","region_id":"12","lokasi_id":"138","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"14","studio_name":"Riri Studio","seo_url":"riristudio-57","address":"Mall Kelapa Gading, Lt 5","postcode":"","area_phone":"","phone":"+6221459325","area_phone_second":"","phone_second":"","website":"riri-riri.com","region_id":"12","lokasi_id":"135","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"19","studio_name":"NF Studio","seo_url":"nf-studio","address":"Ruko Mediterania Blok A4 No 79Jalan Ahmad Yani Kav A5, Kota Bekasi","postcode":"13536","area_phone":"","phone":"+62265111222","area_phone_second":"","phone_second":"","website":"nfstudio.com","region_id":"11","lokasi_id":"137","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"}]

我从循环Utils.log(&#34; studio_name:&#34; + studio_name)得到的结果是:

studio_name: Dodi fit
studio_name: inu fit
studio_name: Vstudio
studio_name: Infovendor
studio_name: Seleb Fitnes One
studio_name: Riri Studio
studio_name: NF Studio

这意味着我已经全部使用了循环。 但问题是结果没有填充到listview中(它显示为NF Studio的最后一个结果,另一个没有出现)。

我需要的是将其填充到country_info的4 texview中(我禁用imageview):

String studio_name, address, website, seo_url

在listview中显示/填充的正确代码是什么?

2 个答案:

答案 0 :(得分:0)

将值添加到List并将其传递到AdapterListView的{​​{1}}类

答案 1 :(得分:0)

  • 你不需要一个线程,这就是异步的全部意义。
  • 列表视图代码位于for循环中
  • UI代码属于PostExecute()而不是doInBackground()
  • 您重新初始化了循环内的列表

试试这样:

private class SendfeedbackJob extends AsyncTask<String, Void, String> {
    private static final String LOG_TAG = "CariStudio";
    private ArrayList<Country> countryList = new ArrayList<Country>();
    ProgressDialog dialog;
    Bundle extras = getIntent().getExtras();
    final String token= extras.getString("TOKEN");
    @Override
    protected String doInBackground(String... params) {
        String areaid = params[0];
        Utils.log("params 1:"+ areaid);
        // do above Server call here
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("region_id", areaid ));

        String responseString = null;
        final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
        Utils.log("url studio:"+ url_studio);
        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url_studio);

            // no idea what this does :)
            httppost.setEntity(new UrlEncodedFormEntity(postParameters));

            // This is the line that send the request
            HttpResponse response = httpclient.execute(httppost);
            Utils.log("response:"+ response);
            HttpEntity entity = response.getEntity();
            String responseAsText = EntityUtils.toString(entity);
            Utils.log("daftar isi studio: " + responseAsText);
            JSONArray json = new JSONArray(responseAsText);

            for (int i = 0; i < json.length(); i++) {
                jsonobject = json.getJSONObject(i);
                final String studio_name = jsonobject.getString("studio_name");
                final String address = jsonobject.getString("address");
                final String website = jsonobject.getString("website");
                final String seo_url = jsonobject.getString("seo_url");
                Utils.log("studio_name: " + studio_name);
                Country country = new Country(studio_name,address, "Website:"+ website,"Fasilitas:"+ seo_url);
                countryList.add(country);
            }
        }
        catch (Exception e)
        {
            /*Toast.makeText(context,
                    "user not registered", Toast.LENGTH_SHORT).show();*/
            Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
        }
        return "processing";
    }

    protected void onPostExecute(Boolean result) {
        //dialog.cancel();
        //create an ArrayAdaptar from the String Array
        dataAdapter = new MyCustomAdapter(context,
                R.layout.country_info, countryList);
        //enables filtering for the contents of the given ListView
        ListView listView = (ListView) findViewById(R.id.listView1);
        // Assign adapter to ListView
        listView.setAdapter(dataAdapter);
        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // When clicked, show a toast with the TextView text
                Country country = (Country) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(),
                        country.getCode(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(context, checkin.class);
                startActivity(intent);
            }
        });
        EditText myFilter = (EditText) findViewById(R.id.myFilter);
        myFilter.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                dataAdapter.getFilter().filter(s.toString());
            }
        });

    }
}
相关问题