Listview的搜索视图 - 以json格式从服务器获取数据

时间:2016-08-10 03:48:45

标签: android json listview adapter searchview

嗨开发者:)我是一名学生,我开始在Android中实施搜索视图。 我有实现搜索视图的问题。我已完成代码,并且已成功查看来自服务器的数据,

  

但是当我开始输入一些时,我得到一个错误(不幸停止)   EditText中的文本(seacrh视图)。有人会帮助我吗?给一些   建议,请..

谢谢..

  

记录错误:
      进程:com.rumahkasihindonesia.kasihgroup.posrki,PID:9842 java.lang.NullPointerException:尝试调用虚方法   ' java.util.Iterator java.util.ArrayList.iterator()'在null对象上   参考   com.rumahkasihindonesia.kasihgroup.posrki.adapter.ItemAdapter.filter(ItemAdapter.java:116)

这是我的代码:

ItemAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.rumahkasihindonesia.kasihgroup.posrki.activity.ItemsActivity;
import com.rumahkasihindonesia.kasihgroup.posrki.model.ModelItems;
import com.rumahkasihindonesia.kasihgroup.posrki.R;

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

/**
 * Created by putri-pc on 6/29/2016.
 */
    public class ItemAdapter extends BaseAdapter {

    private List<ModelItems> modelItemList;
    ArrayList<HashMap<String, String>> data;
    private Context context;

    private ArrayList<ModelItems> arraylistitem;
    LayoutInflater inflater;
    ItemsActivity main;

    public ItemAdapter(ItemsActivity main)
    {
        this.main = main;
    }


    public ItemAdapter(Context context,
                        ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        this.arraylistitem = new ArrayList<ModelItems>();
        this.arraylistitem.addAll(modelItemList);
    }


    @Override
    public int getCount() {
        return  main.itemsModel.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }



    static class ViewHolderItem {
        TextView nameItem;
        TextView priceItem;
        ImageView imageItem;
    }

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

        ViewHolderItem holder = new ViewHolderItem();
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_item, null);

            holder.nameItem = (TextView) convertView.findViewById(R.id.item_name);
            holder.priceItem = (TextView) convertView.findViewById(R.id.item_price);
            holder.imageItem = (ImageView) convertView.findViewById(R.id.imgItem);

            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolderItem) convertView.getTag();
        }

        holder.priceItem.setText(this.main.itemsModel.get(position).getPrice());
        holder.nameItem.setText(this.main.itemsModel.get(position).getName());
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        this.main.itemsModel.clear();
        if (charText.length() == 0) {
            this.main.itemsModel.addAll(arraylistitem);
        }
        else
        {
            for (ModelItems wp : arraylistitem)
            {
                if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText))
                {
                    this.main.itemsModel.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

}

  

package com.rumahkasihindonesia.kasihgroup.posrki.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.rumahkasihindonesia.kasihgroup.posrki.R;
import com.rumahkasihindonesia.kasihgroup.posrki.adapter.ItemAdapter;
import com.rumahkasihindonesia.kasihgroup.posrki.model.ModelItems;
import com.rumahkasihindonesia.kasihgroup.posrki.service.ServiceHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Locale;

public class ItemsActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    SwipeRefreshLayout swLayout;
    LinearLayout llayout;
    // URL to get contacts JSON
    private static String url = "http://10.160.1.35:84/posrkidev/web/index.php/api/inventory";

    public String idcategory;
    public String namecategory;
    public String id_mom,idItem,idCategory,idMom,name,price,active,userinsert,dateinsert,userupdate,dateupdate, pic1,pic2,categoryitem;

    final Context _context = this;
    public TextView output;

    final Context context = this;
    public ListView list;
    public ArrayList<ModelItems> itemsModel = new ArrayList<ModelItems>();
    public ItemAdapter adapter;

    private ModelItems itemModel;
    ProgressDialog pDialog;
    EditText inputSearch;

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

        //JSON
        if(android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        //LISTVIEW
        list = (ListView) findViewById(R.id.listItems);
        adapter = new ItemAdapter(this);
        list.setAdapter(adapter);

        //
        inputSearch = (EditText) findViewById(R.id.inputSearch);

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONArray jsonarray = new JSONArray(jsonStr);
                for (int i = 0; i < jsonarray.length(); i++) {
                    final JSONObject jsonobject = jsonarray.getJSONObject(i);

                    idItem = jsonobject.getString("ID_Item");
                    idCategory = jsonobject.getString("Item_Name");
                    idMom = jsonobject.getString("ID_Mom");
                    name = jsonobject.getString("Item_Price");
                    categoryitem = jsonobject.getString("ID_Inv_Category");
                    pic1 = jsonobject.getString("Item_PIC1");
                    pic2 = jsonobject.getString("Item_PIC2");
                    price = jsonobject.getString("Item_active");
                    userinsert = jsonobject.getString("insert_user");
                    dateinsert = jsonobject.getString("insert_date");
                    userupdate = jsonobject.getString("update_user");
                    dateupdate = jsonobject.getString("update_date");

                    ModelItems add=new ModelItems();
                    add.setId(jsonobject.getString("ID_Item"));
                    add.setName(jsonobject.getString("Item_Name"));
                    add.setIdMom(jsonobject.getString("ID_Mom"));
                    add.setPrice(jsonobject.getString("Item_Price"));
                    add.setActive(jsonobject.getString("Item_active"));
                    add.setPic1(jsonobject.getString("Item_PIC1"));
                    add.setPic2(jsonobject.getString("Item_PIC2"));
                    add.setIdCategory(jsonobject.getString("ID_Inv_Category"));
                    add.setInsert_user(jsonobject.getString("insert_user"));
                    add.setInsert_date(jsonobject.getString("insert_date"));
                    add.setUpdate_user(jsonobject.getString("update_user"));
                    add.setUpdate_date(jsonobject.getString("update_date"));

                    itemsModel.add(add);
                }
                adapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
                String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
                adapter.filter(text);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                // TODO Auto-generated method stub
            }
        });

        // Inisialisasi SwipeRefreshLayout
        swLayout = (SwipeRefreshLayout) findViewById(R.id.swlayout);

        llayout = (LinearLayout) findViewById(R.id.ll_swiperefresh);
        swLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary);
        swLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                // Handler untuk menjalankan jeda selama 5 detik
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Berhenti berputar/refreshing
                        swLayout.setRefreshing(false);
                        Intent intent = new Intent(ItemsActivity.this, ItemsActivity.class);
                        startActivity(intent);
                    }
                }, 1000);
            }
        });

    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(ItemsActivity.this, MasterDataActivity.class);
        startActivity(intent);
    }

}

2 个答案:

答案 0 :(得分:0)

此适配器有2个公共构造函数。您正在使用第adapter = new ItemAdapter(this);行上的ItemsActivity中的第一个。此构造函数不会初始化ItemAdapter中的字段arraylistitem,这就是您的应用在尝试访问arraylistitem时崩溃的原因。您可以在第一个构造函数中重复行this.arraylistitem = new ArrayList<ModelItems>();来解决这个问题,或者使用第二个构造函数。

答案 1 :(得分:0)

我认为您必须在onTextChanged中编写代码,如下所示:

String text = arg0;
            adapter.filter(text);