在searchfilter显示第一个项目后点击

时间:2018-03-21 04:12:05

标签: java android android-layout

我无法找到此活动中的错误。我是android的新手。请问任何人都可以更正java和xml中的错误吗?我有一个微调器,Datepicker和列表视图。微调器将显示三个项目。一切正常.Te问题是每当我搜索任何项目并点击它时,它将打开列表的第一项。请告诉我你是否还需要其他任何东西来解决这个问题。

我的活动

   public class previous extends AppCompatActivity {
    static TextView startDate,endDate;
    static int DATES=123;



    CustomAdapter adapter, Padapter, Eadapter;
    ArrayList<AsyncTask> asyncTasks = new ArrayList<>();
    ListView customersList;
    Spinner listOptions;
    final static String ALL = "All", PAYMENTS = "Payments", EXPENSES = "Expenses";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customers);
        startDate=(TextView)findViewById(R.id.start_date);
        endDate=(TextView)findViewById(R.id.end_date);
        customersList = (ListView) findViewById(R.id.customers_list);
//        getCustomers(DATES);

        //Spinner
        List<String> options = new ArrayList<String>();
        options.add(ALL);
        options.add(PAYMENTS);
        options.add(EXPENSES);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.item_spinner_white, options);
        dataAdapter.setDropDownViewResource(R.layout.item_spinner);
        listOptions = (Spinner) findViewById(R.id.spinner);
        listOptions.setAdapter(dataAdapter);
        listOptions.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (listOptions.getSelectedItem().toString()) {
                    case ALL:
                        searchView.setQuery("", true);
                        customersList.setAdapter(adapter);

                        break;
                    case PAYMENTS:
                        searchView.setQuery("", true);
                        customersList.setAdapter(Padapter);
                        break;
                    case EXPENSES:
                        searchView.setQuery("", true);
                        customersList.setAdapter(Eadapter);
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        listOptions.setVisibility(View.INVISIBLE);
    }
    public void getDates(View view){
        final TextView requiredDate=(TextView)view;
        final String oldText=requiredDate.getText().toString();
        final Calendar today = Calendar.getInstance();
        final Calendar selectedDate=Calendar.getInstance();
        DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                selectedDate.set(Calendar.YEAR, year);
                selectedDate.set(Calendar.MONTH, monthOfYear);
                selectedDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                //Setting display text-------
                SimpleDateFormat formatted = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
                requiredDate.setText(formatted.format(selectedDate.getTime()));
                //Validation--------------
                if(!startDate.getText().toString().equals(getResources().getString(R.string.start_date))
                        &&!endDate.getText().toString().equals(getResources().getString(R.string.end_date))){
                    try {
                        Date sDate=formatted.parse(startDate.getText().toString());
                        Date eDate=formatted.parse(endDate.getText().toString());
                        if(sDate.after(eDate)){
                            Common.toastMessage(previous.this,R.string.give_valid);
                            requiredDate.setText(oldText);
                            return;
                        }
                    } catch (ParseException e) {
                        requiredDate.setText(oldText);
                        return;
                    }
                    getCustomers(DATES);
                }
            }
        };
        new DatePickerDialog(previous.this, dateSetListener, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH))
                .show();
    }

    void getCustomers(int DATES) {

        final Common common = new Common();
        final String webService = "/API/Approver/GetPreviousApprovalsInfo";
        final String postData = "{\"FromDate\":\"" + startDate.getText().toString() + "\",\"ToDate\":\"" + endDate.getText().toString() + "\"}";
        final AVLoadingIndicatorView loadingIndicator = (AVLoadingIndicatorView) findViewById(R.id.loading_indicator);
        final String[] dataColumns = {};
        final Runnable postThread = new Runnable() {
            @Override
            public void run() {

                try {

                    final JSONArray invoices = new JSONArray(common.json);
                    if (invoices.length() == 0) {
                        (findViewById(R.id.no_items)).setVisibility(View.VISIBLE);
                        return;
                    }
                    final ArrayList<String[]> invoiceListData = new ArrayList<>();
                    for (int i = 0; i < invoices.length(); i++) {
                        JSONObject jsonObject1 = invoices.getJSONObject(i);
                        String[] data = new String[9];
                        data[0] = jsonObject1.getString("ID");
                        data[1] = jsonObject1.getString("EntryNo");
                        data[2] = jsonObject1.getString("Company");
                        data[3] = jsonObject1.getString("Date");
                        data[4] = jsonObject1.getString("PaymentMode");
                        data[5] = jsonObject1.getString("Amount");
                        data[6] = jsonObject1.getString("Type");
                        data[7] = jsonObject1.getString("ApprovalDate");
                        data[8] = jsonObject1.getString("GeneralNotes");
                        invoiceListData.add(data);
                    }
                    adapter = new CustomAdapter(previous.this, invoiceListData, Common.PREVIOUSPAYMENTS);
                    customersList.setAdapter(adapter);
                    listOptions.setVisibility(View.VISIBLE);


                    final ArrayList<String[]> PaymentListData = new ArrayList<>();
                    final ArrayList<String[]> ExpenseListData = new ArrayList<>();
                    for (int i = 0; i < invoiceListData.size(); i++) {
                        if (invoiceListData.get(i)[6].equals("Payment")) {

                            PaymentListData.add(invoiceListData.get(i));


                        } else if (invoiceListData.get(i)[6].equals("Expense")) {

                            ExpenseListData.add(invoiceListData.get(i));


                        }
                    }

                    Padapter = new CustomAdapter(previous.this, PaymentListData, Common.PREVIOUSPAYMENTS);//Global variable
                    customersList.setAdapter(Padapter);
                    listOptions.setVisibility(View.VISIBLE);


                    Eadapter = new CustomAdapter(previous.this, ExpenseListData, Common.PREVIOUSPAYMENTS);
                    customersList.setAdapter(adapter);
                    listOptions.setVisibility(View.VISIBLE);

                    customersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                            if (customersList.getAdapter() == adapter) {


                                switch (invoiceListData.get(position)[6]){

                                    case "Payment":
                                        Intent approvalDetailsIntent1 = new Intent(previous.this,PpaymentDetails.class);
                                        approvalDetailsIntent1.putExtra(Common.APPROVALID,invoiceListData.get(position)[0]);
                                        approvalDetailsIntent1.putExtra(Common.ENTRYNO, invoiceListData.get(position)[1]);
                                        approvalDetailsIntent1.putExtra(Common.PAYMENT_MODE, invoiceListData.get(position)[4]);
                                        approvalDetailsIntent1.putExtra(Common.PAYMENT_DATE, invoiceListData.get(position)[3]);
                                        approvalDetailsIntent1.putExtra(Common.AMOUNT, invoiceListData.get(position)[5]);
                                        approvalDetailsIntent1.putExtra(Common.COMPANY_DETAILS, invoiceListData.get(position)[2]);
                                        approvalDetailsIntent1.putExtra(Common.GENERAL_NOTES, invoiceListData.get(position)[8]);
                                        approvalDetailsIntent1.putExtra(Common.PAYMENT_TYPE, invoiceListData.get(position)[6]);
                                        startActivity(approvalDetailsIntent1);


                                        break;

                                    case "Expense":

                                        Intent approvalDetailsIntent2 = new Intent(previous.this, PexpenseDetail.class);
                                        approvalDetailsIntent2.putExtra(Common.APPROVALID, invoiceListData.get(position)[0]);
                                        approvalDetailsIntent2.putExtra(Common.REFNO, invoiceListData.get(position)[1]);
                                        startActivity(approvalDetailsIntent2);


                                        break;


                                }

//                                    Common.toastMessage(getContext(), "scene aan");
                            }

                            else if (customersList.getAdapter() == Padapter) {

                                Intent approvalDetailsIntent1 = new Intent(previous.this,PpaymentDetails.class);
                                approvalDetailsIntent1.putExtra(Common.APPROVALID, PaymentListData.get(position)[0]);
                                approvalDetailsIntent1.putExtra(Common.ENTRYNO, PaymentListData.get(position)[1]);
                                approvalDetailsIntent1.putExtra(Common.PAYMENT_MODE, PaymentListData.get(position)[4]);
                                approvalDetailsIntent1.putExtra(Common.PAYMENT_DATE, PaymentListData.get(position)[3]);
                                approvalDetailsIntent1.putExtra(Common.AMOUNT, PaymentListData.get(position)[5]);
                                approvalDetailsIntent1.putExtra(Common.COMPANY_DETAILS, PaymentListData.get(position)[2]);
                                approvalDetailsIntent1.putExtra(Common.GENERAL_NOTES, PaymentListData.get(position)[8]);
                                approvalDetailsIntent1.putExtra(Common.PAYMENT_TYPE, PaymentListData.get(position)[6]);
                                startActivity(approvalDetailsIntent1);


                            }
                            else if (customersList.getAdapter() == Eadapter) {


                                Intent approvalDetailsIntent2 = new Intent(previous.this, PexpenseDetail.class);
                                approvalDetailsIntent2.putExtra(Common.APPROVALID, ExpenseListData.get(position)[0]);
                                approvalDetailsIntent2.putExtra(Common.REFNO, ExpenseListData.get(position)[1]);
                                startActivity(approvalDetailsIntent2);
                            }


                        }
                    });




                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        };
        Runnable postThreadFailed = new Runnable() {
            @Override
            public void run() {
                Common.toastMessage(previous.this, R.string.failed_server);
            }
        };

        common.AsynchronousThread(previous.this,
                webService,
                postData,
                loadingIndicator,
                dataColumns,
                postThread,
                postThreadFailed);
        asyncTasks.add(common.asyncTask);
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    }
    SearchView searchView;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home_search, menu);
        //Searching-------------------
        searchView=(SearchView) menu.findItem(R.id.menu_search).getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                if(customersList.getAdapter()!=null){//for searching
                    ((CustomAdapter)customersList.getAdapter()).getFilter(Arrays.asList(1)).filter(searchView.getQuery().toString().trim());
                }
                return false;
            }
        });
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_home) {
            Intent intent=new Intent(this,HomeScreen.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onBackPressed() {
        for(int i=0;i<asyncTasks.size();i++){
            asyncTasks.get(i).cancel(true);
        }
        super.onBackPressed();
    }
}

我的xml

<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.tech.thrithvam.spaccounts.Customers"
    android:background="@drawable/primary_gradient">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="end"
        android:gravity="end"
        android:animateLayoutChanges="true"
        android:id="@+id/dates_layout"
        android:paddingLeft="5dp"
        android:paddingRight="5dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/start_date"
            android:textSize="14sp"
            android:padding="5dp"
            android:textColor="@color/colorAccent"
            android:onClick="getDates"
            android:id="@+id/start_date"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/to"
            android:textSize="14sp"
            android:padding="5dp"
            android:textColor="@color/primary_text"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/end_date"
            android:textSize="14sp"
            android:padding="5dp"
            android:textColor="@color/colorAccent"
            android:onClick="getDates"
            android:id="@+id/end_date"/>
    </LinearLayout>
    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_gravity="end"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/customers_list"
        android:layout_below="@id/spinner"
        android:divider="@null"
        android:paddingTop="3dp"
        android:scrollbars="none"/>
    <com.wang.avi.AVLoadingIndicatorView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:indicatorName="BallScaleMultipleIndicator"
        android:layout_gravity="center"
        app:indicatorColor="@android:color/white"
        android:id="@+id/loading_indicator"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

CUSTOM ADAPTER

    public class CustomAdapter extends BaseAdapter {
    private Context adapterContext;
    public static LayoutInflater inflater=null;
    private ArrayList<String[]> objects;
    private String calledFrom;
    private SimpleDateFormat formatted;
    private Calendar cal;
    CustomAdapter(Context context, ArrayList<String[]> objects, String calledFrom) {
        // super(context, textViewResourceId, objects);
        initialization(context, objects, calledFrom);
    }

    public CustomAdapter(ArrayList<String[]> invoiceListData, String previouspayments) {
    }

    void initialization(Context context, ArrayList<String[]> objects, String calledFrom){
        adapterContext=context;
        inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.objects=objects;
        this.filteredObjects=objects;
        this.calledFrom=calledFrom;
//    
    }
    @Override
    public int getCount() {
        return filteredObjects.size();
    }

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

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

    private class Holder {
        //Customers List-----------
        TextView customerName,phone,address,amount;
        ImageView callButton;
        //Suppliers List------------
        TextView supplierName;
        //Sales list----------------
        TextView invoiceNo,contactPerson,balAmount,paidAmount,dueDate, dueDays;
        //Approvals-----------------
        TextView entryNo,paymentMode,paymentdate;
        //ApprovalDetails-----------
        TextView invoiceAmount,currentAmount,currentAmountLabel;
        //Other expense approval
        TextView expNo,expDate,description;
        TextView entryN,compN,payD,payM,payA,payT,appD,genN;


    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        final int fPos=position;
        switch (calledFrom) {

            //--------------------------for purchase invoice list items------------------

            //--------------------------for customer list items------------------

            //--------------------------for approval list items------------------

            //--------------------------for approval details list items------------------

            //--------------------------for other expense approval list items------------------
            case Common.PREVIOUSPAYMENTS:
                if (convertView == null) {
                    holder = new Holder();
                    convertView = inflater.inflate(R.layout.item_previous_approvals, null);
                    holder.entryN = (TextView) convertView.findViewById(R.id.entry_no);
                    holder.compN=(TextView)convertView.findViewById(R.id.company_name);
                    holder.payD=(TextView)convertView.findViewById(R.id.payment_date);
                    holder.payM=(TextView)convertView.findViewById(R.id.payment_mode);
                    holder.payA=(TextView)convertView.findViewById(R.id.payment_amount);
                    holder.payT=(TextView)convertView.findViewById(R.id.payment_type);
                    holder.appD=(TextView)convertView.findViewById(R.id.approval_date);
                    holder.genN=(TextView)convertView.findViewById(R.id.general_note);
                    convertView.setTag(holder);
                } else {
                    holder = (Holder) convertView.getTag();
                }
                //Label loading--------------------
//                holder.paidAmount.setText((filteredObjects.get(position)[6].equals("null")?"-":adapterContext.getResources().getString(R.string.paid_amount,filteredObjects.get(position)[6])));
                holder.entryN.setText((filteredObjects.get(position)[1].equals("null")?"-":filteredObjects.get(position)[1]));
                holder.compN.setText((filteredObjects.get(position)[2].equals("null")?"-":filteredObjects.get(position)[2]));
                holder.payD.setText((filteredObjects.get(position)[3].equals("null")?"-":filteredObjects.get(position)[3]));
                holder.payM.setText((filteredObjects.get(position)[4].equals("null")?"-":filteredObjects.get(position)[4]));
                holder.payA.setText((filteredObjects.get(position)[5].equals("null")?"-":adapterContext.getResources().getString(R.string.paid_amount,filteredObjects.get(position)[5])));
                holder.payT.setText((filteredObjects.get(position)[6].equals("null")?"-":filteredObjects.get(position)[6]));
                holder.appD.setText((filteredObjects.get(position)[7].equals("null")?"-":adapterContext.getResources().getString(R.string.Ap_date,filteredObjects.get(position)[7])));
                holder.genN.setText((filteredObjects.get(position)[8].equals("null")?"-":filteredObjects.get(position)[8]));
                break;
     }
        return convertView;
    }

    //Filtering--------------------------------------
    private ItemFilter mFilter = new ItemFilter();
    private ArrayList<String[]> filteredObjects;
    private List<Integer> dataItemPosition;
    Filter getFilter(List<Integer> dataItem) {
        dataItemPosition=dataItem;
        return mFilter;
    }
    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            String filterString = constraint.toString().toLowerCase();
            FilterResults results = new FilterResults();
            int count = objects.size();
            final ArrayList<String[]> filteredList = new ArrayList<String[]>(count);

            for (int i = 0; i < count; i++) {
                for(int j=0;j<dataItemPosition.size();j++) {
                    if (objects.get(i)[dataItemPosition.get(j)].toLowerCase().contains(filterString)) {
                        filteredList.add(objects.get(i));
                        break;//found at least one item
                    }
                }
            }

            results.values = filteredList;
            results.count = filteredList.size();
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredObjects = (ArrayList<String[]>) results.values;
            notifyDataSetChanged();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用过滤器时,您实现的逻辑不起作用。为此,您必须使用adapterSelection.selectedItem = getAdapterPosition()。  确保自定义适配器中的parent.getAdapter().getItem(position);返回正确的数据。

更改

getItem(position)

您的CustomAdapter中的此代码

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

@Override public String[] getItem(int position) { return filteredObjects.get(position); }

中考虑setOnItemClickListner的以下代码
CustomerList