保持将游标合并在一起

时间:2017-02-16 14:57:57

标签: android android-fragments android-cursor

我从点击底部列表中的行中取出光标,并将光标合并到顶部。它适用于第一个单击的行。但是,当我单击另一行时,它只是替换另一行,而不仅仅是将它们添加到一起。我不确定你是否可以或如何迭代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方法的新游标合并。我迷失在如何将两个游标合并在一起,然后获取新游标并将其与任何传递给更新方法的游标合并。

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());
    }
}

1 个答案:

答案 0 :(得分:0)

为了达到您的要求,我做了一个非常基本的项目,请在下面找到回购链接:

https://github.com/deeps09/AdamGardner

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());
        }
    }
}