搜索从异步任务

时间:2017-12-09 19:22:54

标签: java android android-fragments asynchronous

我一直在尝试在我的actionBar中实现一个SearchView,它过滤了一个从异步任务中获取数据的Recyclerview,现在我似乎无法让它工作。

我在这里看到的所有答案都获得了Recycler类的适配器与SearchView在同一个类中。但是在我的应用程序中,适配器位于Async类中,而Searchview位于片段中。我创建了一个Async类,因为当我的应用程序试图加载RecyclerView上的项目时,我不希望我的UI线程变慢或崩溃。贝娄是我的代码,任何帮助都很可爱。

最后,对于我的片段,我有一些代码如此生病,只是将大部分代码排除在外,并留下与问题相关的内容。感谢。

表示MyAsync.java

public class MyAsync extends AsyncTask<Void,RafTask,Void>{

private RecyclerView recyclerView;
private ProgressBar progressBar;
private Context context;
private static ClientRecycler recycler;
private SearchView searchView;
private ArrayList<RafTask> newLists = new ArrayList<>();
String am;
private static ArrayList<RafTask> raftask = new ArrayList<>();
private static final String TAG = "ListDataActivity";

public MyAsync(RecyclerView recyclerView, ProgressBar progressBar,Context context, ArrayList<RafTask> newList){

    this.recyclerView = recyclerView;
    this.progressBar = progressBar;
    this.context = context;
    this.newLists = newList;
}

@Override
protected void onPreExecute() {

    recycler = new ClientRecycler(raftask);
    recyclerView.setAdapter(recycler);
    progressBar.setVisibility(View.VISIBLE);
}


@Override
protected Void doInBackground(Void... voids) {


    MyHelper mHelper = new MyHelper(context,null,null,1);

    SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();


    String Name;
    int  count = 0;
    Cursor c = mHelper.getRafData();



    while(c.moveToNext()){

        //Database codes
        publishProgress(new RafTask(Name,"","",String.valueOf(count),"",""));

    return null;
}

@Override
protected void onProgressUpdate(RafTask... value) {
    raftask.add(value[0]);
    recycler.notifyDataSetChanged();
}

@Override
protected void onPostExecute(Void aVoid) {

    progressBar.setVisibility(View.GONE);
    Log.d(TAG, "fragment text pass: " + am);
}
public static void setFilter(ArrayList<RafTask> newList){
   // newList = newLists;
    raftask = new ArrayList<>();
    raftask.addAll(newList);
    recycler.notifyDataSetChanged();
}
}

对于Rafadapter.java

public class RafRecycler extends RecyclerView.Adapter<RafRecycler.MyViewHolder> {
private static ArrayList<RafTask> rafTasks = new ArrayList<>();



public RafRecycler(ArrayList<RafTask> rafTasks){
    this.rafasks = rafTasks;

}

@Override
public RafRecycler.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_rafs,parent,false);
    return new RafRecycler.MyViewHolder(view);

}

@Override
public void onBindViewHolder(ClientRecycler.MyViewHolder holder, int position) {

    holder.name.setText(rafTasks.get(position).get_raftaskname());
    holder.id.setText(String.valueOf(rafTasks.get(position).get_raftaskid())+".");
    // holder.id.setText(String.valueOf("->"));


    holder.m = rafTasks.get(position).get_raftaskid();

}

@Override
public int getItemCount() {
    return clientTasks.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder{

    TextView id,name;
    String m;



    public MyViewHolder(View itemView) {
        super(itemView);
        id = itemView.findViewById(R.id.txt_id);
        name = itemView.findViewById(R.id.txt_name);
        m=itemView.toString();


        final MyDatabaseHelper mDatabaseHelper = new MyDatabaseHelper(itemView.getContext(),null,null,1);





        final boolean clicked = false;

        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String names = name.getText().toString();

                Cursor c = mHelper.getClientItemID(names);
                int itemID = -1;
                String email = "";
                String address = "";
                String shipaddress = "";
                String number = "";
                while (c.moveToNext()){

                    //Chech here for the codes to edit all plus numbers
                    //
                    //
                    itemID = c.getInt(0);
                    address =c.getString(4);
                    number =c.getString(2);
                    shipaddress =c.getString(5);
                    email =c.getString(3);
                }
                if(itemID >-1){
                    Log.d(TAG, "onItemClick: The id is: " + itemID);
                    Log.d(TAG, "onItemClick: The desc is: " + address);
                    Log.d(TAG, "onItemClick: The price is: " + shipaddress);
                    Intent editScreenIntent = new Intent(v.getContext(), EditClientActivity.class);
                    editScreenIntent.putExtra("id", itemID);
                    editScreenIntent.putExtra("name", names);
                    editScreenIntent.putExtra("number", number);
                    editScreenIntent.putExtra("address", address);
                    editScreenIntent.putExtra("email", email);
                    editScreenIntent.putExtra("shipaddress", shipaddress);
                    v.getContext().startActivity(editScreenIntent);
                    ((MainActivity) v.getContext()).overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
                }else{
                    Toast.makeText(v.getContext(),"No idd clicked", Toast.LENGTH_SHORT).show();
                }

            }

        });
    }
}

public void setFilter(ArrayList<ClientTask> newList){
    clientTasks = new ArrayList<>();
    clientTasks.addAll(newList);
    notifyDataSetChanged();
}
}

最后我的fragment.java

public class ClientFragment extends Fragment implements SearchView.OnQueryTextListener {

private static final String TAG = "ListDataActivity";
MyDatabaseHelper mDatabaseHelper;
private ProgressBar progressBar;
private RecyclerView recyclerView;
public static SearchView searchView;
static String am;
private MenuItem menua;
public static ArrayList<ClientTask> newList;
RecyclerView.LayoutManager layoutManager;
public BackgroundAsync backgroundAsync;
private ArrayList<ClientTask> clienttask = new ArrayList<>();
ClientRecycler recycler;

private ListView mListView;

Button opencon;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public ClientFragment() {
    // Required empty public constructor
}
public static ClientFragment newInstance(String param1, String param2) {
    ClientFragment fragment = new ClientFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onPrepareOptionsMenu(Menu menu){


    am="asdf";
    MenuItem menuItem = menu.findItem(R.id.mysearchbtn);
    SearchView searchView = (SearchView) menuItem.getActionView();
     searchView.setOnQueryTextListener(this);
    Log.d(TAG, "onCreateFragment ");
    super.onPrepareOptionsMenu(menu);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    if (getArguments() != null) {
        setRetainInstance(true);
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

}




@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_client, container, false);

    progressBar = view.findViewById(R.id.progressbar);
    recyclerView = view.findViewById(R.id.recyclerView);
    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);


    recycler = new ClientRecycler(clienttask);

    opencon = view.findViewById(R.id.opencon);
    opencon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), AddClient.class);
            startActivity(intent);
        }
    });

    return view;
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
     //   Toast.makeText(context, " Off", Toast.LENGTH_SHORT).show();

    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    newText = newText.toLowerCase();
    newList = new ArrayList<>();
        for (ClientTask clientTask : clienttask) {
            String name = clientTask.get_clienttaskname().toLowerCase();
            if (name.contains(newText)) {
                Log.d(TAG, "u get any: "+ name);
                newList.add(clientTask);
            }else{
                Log.d(TAG, "we aint got shit: "+ name);
            }

        }

        Log.d(TAG, "the usual fail ");
    recyclerView.setAdapter(recycler);
    return true;
}

void filter(String text){
    ArrayList<ClientTask> newList = new ArrayList();

      for (ClientTask c : clienttask) {
     //   String name = clientTask.get_clienttaskname().toLowerCase();
        if (c.get_clienttaskname().contains(text)) {
            newList.add(c);
        }

          Log.d(TAG, "the usual fail ");
          BackgroundAsync.setFilter(newList);
          recyclerView.setAdapter(recycler);
    }
}


public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}
@Override
public void onResume() {
    super.onResume();
    new BackgroundAsync(recyclerView,progressBar,getActivity(),newList).execute();
}


}

我的代码的某些部分可能非常不足以解决我的问题,但我已经尝试了很多修复工作并没有工作,因此,我有一些看似奇怪的实现。请继续解决问题再次感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我设法通过将Async任务类移动到Fragment类来解决问题,因此它们共享相同的变量。我清除了构造函数中的所有输入,因此它变为新的BackgroundBsync().execute();。这解决了它,我现在能够使用我在Rafadapter类中制作的单独方法搜索所有数据。代码如下。

public void setFilter(ArrayList<ClientTask> newList){
        clientTasks = new ArrayList<>();
        clientTasks.addAll(newList);
        notifyDataSetChanged();
    }

所以我需要在onQueryTextChange添加所有内容来添加几行代码

newText = newText.toLowerCase();
        ArrayList<ClientTask> newList = new ArrayList();

        for (ClientTask c : clienttask) {
               String name = c.get_clienttaskname().toLowerCase();
            if (name.contains(newText)) {
                newList.add(c);
            }

            Log.d(TAG, "the usual fail ");
        }
        recycler.setFilter(newList);
        return true;

它解决了我的问题。请注意,RafAdapter与ClientRecycler相同。