当前位置: 代码迷 >> Android >> 不断合并光标
  详细解决方案

不断合并光标

热度:93   发布时间:2023-08-04 11:57:43.0

我从底部列表中单击的行中获取光标,并将其与顶部的光标合并。 它对于第一行单击的行正确运行。 但是,当我单击另一行时,它将替换另一行,而不仅仅是将它们添加在一起。 我不确定是否可以或如何迭代MergeCursor以使其不断添加到游标而不是替换它。

public class TopFragment extends Fragment {
    public Cursor mTopCursor;
    EmployeeDBHandler dbHandler;
    ListView mTopListView;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top_list, container, false);
        String table = "employees";
        int mStartingEmployeeID = mStartingNumber;
        dbHandler = new EmployeeDBHandler(getContext());
        SQLiteDatabase db = dbHandler.getWritableDatabase();
        mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
        mTopListView = (ListView) view.findViewById(R.id.mTopList);
        TopListCursorAdapter topAdapter = new TopListCursorAdapter(getContext(), mTopCursor);
        mTopListView.setAdapter(topAdapter);
        return view;
    }


    public void update(Cursor cursor) {
        while (cursor.moveToNext()) {
            MergeCursor mergeCursor = new MergeCursor(new Cursor[]{cursor, mTopCursor});
            TopListCursorAdapter topAdapter = new TopListCursorAdapter(getContext(), mergeCursor);
            mTopListView.setAdapter(topAdapter);
        }
    }
}

我知道我总是将mTopCursor添加到合并中,因此它只是使用mTopCursor并与传递到update方法中的新光标进行合并。 我不知道如何将两个游标合并在一起,然后采用新的游标并将其与传递给update方法的任何游标合并。

public class TopListCursorAdapter extends CursorAdapter {

    public interface TopListClickListener {
        void onTopListClick(Cursor cursor);
    }

    private TopListClickListener mCallback;

    public TopListCursorAdapter(Context context, Cursor cursor) {
        super(context, cursor, 0);
        if(!(context instanceof TopListClickListener)) {
            throw new ClassCastException("Content must implement BottomListClickListener");
        }
        this.mCallback = (TopListClickListener) context;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.contact_cardview_top, parent, false);
    }

    @Override
    public void bindView(View view, final Context context, final Cursor cursor) {
        ViewHolder holder;
        holder = new ViewHolder();
        holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
        holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
        holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
        holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
        holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
        holder.mTopCardView = (CardView) view.findViewById(R.id.mTopHomeScreenCV);

        String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
        String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
        String mPayrollTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
        String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));

        holder.tvFirstName.setText(mFirstName);
        holder.tvLastName.setText(mLastName);
        holder.tvTitle.setText(mPayrollTitle);

        if (mThumbnail != null) {
            byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
            Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
            holder.mPeepPic.setImageBitmap(parsedImage);
        } else {
            holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
        }


        final int position = cursor.getPosition();
        holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cursor.moveToPosition(position);
                String mEmployeeNumber = cursor.getString(1);
                String mEmail = cursor.getString(8);
                String mFirstName = cursor.getString(2);
                String mLastName = cursor.getString(3);
                String mPhoneMobile = cursor.getString(4);
                String mPhoneOffice = cursor.getString(5);
                String mCostCenter = cursor.getString(10);
                String mHasDirectReports = cursor.getString(7);
                String mTitle = cursor.getString(6);
                String mPic = cursor.getString(9);
                Intent mIntent = new Intent(context, EmployeeFullInfo.class);
                mIntent.putExtra("Employee_number", mEmployeeNumber);
                mIntent.putExtra("Email", mEmail);
                mIntent.putExtra("First_name", mFirstName);
                mIntent.putExtra("Last_name", mLastName);
                mIntent.putExtra("Phone_mobile", mPhoneMobile);
                mIntent.putExtra("Phone_office", mPhoneOffice);
                mIntent.putExtra("Cost_center_id", mCostCenter);
                mIntent.putExtra("Has_direct_reports", mHasDirectReports);
                mIntent.putExtra("Payroll_title", mTitle);
                mIntent.putExtra("ThumbnailData", mPic);
                mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                v.getContext().startActivity(mIntent);
            }
        });

        holder.mTopCardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mCallback != null) {
                    mCallback.onTopListClick(cursor);
                }
            }
        });
    }

    public static class ViewHolder {
        TextView tvFirstName;
        TextView tvLastName;
        TextView tvTitle;
        ImageView mPeepPic;
        ImageButton mDetailsButton;
        CardView mTopCardView;
    }
}


public class MainActivity extends AppCompatActivity implements BottomListCursorAdapter.BottomListClickListener,
        TopListCursorAdapter.TopListClickListener {
    private ProgressBar mProgressBar;
    EmployeeDBHandler dbHandler;
    private TopListCursorAdapter topAdapter;
    private BottomListCursorAdapter bottomAdapter;
    private ArrayList<Employee> mEmployee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        dbHandler = new EmployeeDBHandler(getApplicationContext());
        mProgressBar.setVisibility(View.VISIBLE);
        getXMLData();

        //GUI for seeing android SQLite Database in Chrome Dev Tools
        Stetho.InitializerBuilder inBuilder = Stetho.newInitializerBuilder(this);
        inBuilder.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this));
        Stetho.Initializer in = inBuilder.build();
        Stetho.initialize(in);
    }

    public void getXMLData() {
        OkHttpClient client = getUnsafeOkHttpClient();
        Request request = new Request.Builder()
                .url(getString(R.string.API_FULL_URL))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String responseData = response.body().string();
                final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
                final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
                final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);

                for (Employee e : employees) {
                    dbHandler.addEmployee(e);
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressBar.setVisibility(View.GONE);
                        displayTopList();
                        displayBottomList();
                    }
                });
            }
        });
    }

    public void displayTopList() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.topFragment, new TopFragment());
        fragmentTransaction.commit();
    }

    public void displayBottomList() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.bottomFragment, new BottomFragment());
        fragmentTransaction.commit();
    }

    @Override
    public void onBottomListClick(Employee e) {
        dbHandler.addEmployee(e);
        Log.i("EMPLOYEE", e.toString());
        TopFragment topFragment = (TopFragment) getSupportFragmentManager().findFragmentById(R.id.topFragment);
        SQLiteDatabase db = dbHandler.getWritableDatabase();
        final Cursor clickedEmployee = db.rawQuery("SELECT * FROM " + "employees" + " WHERE " +
                "Employee_number" + "=" + e.getEmployee_number(), null);
        // change the adapter's Cursor
        topFragment.update(clickedEmployee);
    }

    @Override
    public void onTopListClick(Cursor cursor) {
        do{
            BottomFragment bottomFragment = (BottomFragment) getSupportFragmentManager().findFragmentById(R.id.bottomFragment);
            bottomFragment.refreshList(cursor);
        } while (cursor.moveToNext());
    }
}

为了满足您的要求,我做了一个非常基础的项目,请在下面找到repo的链接:

public class TopFragment extends Fragment {
    public Cursor mTopCursor;
    EmployeeDBHandler dbHandler;
    ListView mTopListView;
    public static MatrixCursor customCursor1;
    private int mStartingEmployeeID = mStartingNumber;
    int flag = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top_list, container, false);
        String table = "employees";

        customCursor1 = new MatrixCursor(new String[]{"_id", "Employee_number", "First_name",
                "Last_name", "Payroll_title", "ThumbnailData"});
        dbHandler = new EmployeeDBHandler(getContext());
        SQLiteDatabase db = dbHandler.getWritableDatabase();
        mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
        mTopListView = (ListView) view.findViewById(R.id.mTopList);
        TopListCursorAdapter topAdapter = new TopListCursorAdapter(getContext(), mTopCursor);
        mTopListView.setAdapter(topAdapter);
        return view;
    }

    public void update(Cursor cursor) {
        if (cursor.moveToNext() && cursor.getCount() >= 1) {
            do {
                customCursor1.addRow(new Object[]{cursor.getInt(0), cursor.getString(1), cursor.getString(2),
                        cursor.getString(3), cursor.getString(6), cursor.getString(9)});
                if (flag == 0) {
                    customCursor1.addRow(new Object[]{mTopCursor.getInt(0), mTopCursor.getString(1), mTopCursor.getString(2),
                            mTopCursor.getString(3), mTopCursor.getString(6), mTopCursor.getString(9)});
                    flag++;
                }
                TopListCursorAdapter topAdapter = new TopListCursorAdapter(getContext(), customCursor1);
                mTopListView.setAdapter(topAdapter);
            } while (cursor.moveToNext());
        }
    }
}
  相关解决方案