如何通过匹配id获得SQLite列的总和

时间:2017-01-29 15:06:15

标签: java android sqlite android-sqlite

该应用:我有一个可以创建多台计算机的应用:

  • ID,姓名和位置

这些机器的每个我必须让用户分别输入收入。

问题:我需要 SUM 从每台机器输入的所有收入( money,date,note,machines_id AND 在另一个Activity中的TextView中显示它。

我的问题:如何将getIncomeOfMachine方法的rawQuery中的数据传输到另一个Activity?

我尝试了什么:使用DBHelper类中的Bundles,Intents和SharedPreferences。

DBHelper

public class DBHelpter extends SQLiteOpenHelper {

    private static final String DB_NAME = "machines.db";
    private static final int DB_VERSION = 1;

    public static final String TABLE_MACHINES = "machines";
    public static final String MACHINES_COLUMN_NAME = "name";
    public static final String MACHINES_COLUMN_LOCATION = "location";
    public static final String MACHINES_ID = "id";

    public static final String TABLE_INCOME = "income";
    public static final String INCOME_COLUMN_MONEY = "money";
    public static final String INCOME_COLUMN_DATE = "date";
    public static final String INCOME_COLUMN_NOTE = "note";
    public static final String INCOME_ID = "id";
    public static final String INCOME_COLUMN_MACHINES_ID = "machines_id";

    private Context mContext;

public DBHelpter(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

@Override
public void onCreate(SQLiteDatabase db) {
    String query1 = String.format("CREATE TABLE " + TABLE_MACHINES + "("
        + MACHINES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + MACHINES_COLUMN_NAME + " TEXT NOT NULL, "
        + MACHINES_COLUMN_LOCATION + " TEXT NOT NULL)",
            TABLE_MACHINES, MACHINES_COLUMN_NAME, MACHINES_COLUMN_LOCATION, MACHINES_ID);

    String query2 = String.format("CREATE TABLE " + TABLE_INCOME + "("
        + INCOME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + INCOME_COLUMN_MONEY + " REAL NOT NULL, "
        + INCOME_COLUMN_DATE + " DATE NOT NULL, "
        + INCOME_COLUMN_NOTE + " TEXT NOT NULL, "
        + INCOME_COLUMN_MACHINES_ID + " INTEGER NOT NULL)",
            TABLE_INCOME, INCOME_ID, INCOME_COLUMN_MONEY, INCOME_COLUMN_DATE, INCOME_COLUMN_NOTE, INCOME_COLUMN_MACHINES_ID);
    db.execSQL(query1);
    db.execSQL(query2);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String query1 = String.format("DROP TABLE IF EXISTS " + TABLE_MACHINES);
    String query2 = String.format("DROP TABLE IF EXISTS " + TABLE_INCOME);
    db.execSQL(query1);
    db.execSQL(query2);
    onCreate(db);

}
public void insertNewMachine(String name, String location){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(MACHINES_COLUMN_NAME, name);
        values.put(MACHINES_COLUMN_LOCATION, location);
        db.insertWithOnConflict(TABLE_MACHINES, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
    }
public void insertNewIncome(Double money, String date, String note, long machines_id){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(INCOME_COLUMN_MONEY, money);
        values.put(INCOME_COLUMN_DATE, date);
        values.put(INCOME_COLUMN_NOTE, note);
        values.put(INCOME_COLUMN_MACHINES_ID, machines_id);
        db.insertWithOnConflict(TABLE_INCOME, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
    }
public void getIncomeOfMachine(long machinesId){
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT machines_id, SUM(money) AS total FROM income WHERE machines_id = "+machinesId+"", null);
        while (cursor.moveToFirst()){
            String totalAmount = String.valueOf(cursor.getInt(0));
            SharedPreferences mSharedPreferences = mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor mEditor = mSharedPreferences.edit();
            mEditor.putString("total_amount", totalAmount);
            mEditor.commit();
        }
        cursor.close();
        db.close();
    }
public ArrayList<MachinesClass> getAllMachines(){
        ArrayList<MachinesClass> machinesList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_MACHINES, null);
        while (cursor.moveToNext()){
            final long id = cursor.getLong(cursor.getColumnIndex(MACHINES_ID));
            final String name = cursor.getString(cursor.getColumnIndex(MACHINES_COLUMN_NAME));
            final String location = cursor.getString(cursor.getColumnIndex(MACHINES_COLUMN_LOCATION));
            machinesList.add(new MachinesClass(id, name, location));
        }
        cursor.close();
        db.close();
        return machinesList;
    }

RecyclerViewAdapter

public class MachinesAdapter extends RecyclerView.Adapter<MachinesAdapter.ViewHolder>  {

private ArrayList<MachinesClass> machinesList;
private LayoutInflater mInflater;
private DBHelpter mDBHelpter;
private Context mContext;
public static final String PREFS_NAME = "MyPrefsFile";


public MachinesAdapter(Context mContext, ArrayList<MachinesClass> machinesList){
    this.mContext = mContext;
    this.machinesList = machinesList;
}

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

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    holder.mLocation.setText(machinesList.get(position).getLocation());
    holder.v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            SharedPreferences mSharedPreferences = mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor mEditor = mSharedPreferences.edit();
            mEditor.putString("location", machinesList.get(position).getLocation());
            mEditor.putLong("machines_id", machinesList.get(position).getId());
            mEditor.commit();

            Bundle bundle = new Bundle();
            bundle.putString("location", machinesList.get(position).getLocation());
            Intent intent = new Intent(v.getContext(), MachineInfo.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return machinesList != null ? machinesList.size() : 0;
}


public class ViewHolder extends RecyclerView.ViewHolder {

    public TextView mLocation, mMoney;
    public LinearLayout mLinearLayout;
    public View v;

    public ViewHolder(View v) {
        super(v);
        mLinearLayout = (LinearLayout) v.findViewById(R.id.linearLayout);
        mLocation = (TextView) v.findViewById(R.id.tvLocation);
        mMoney = (TextView) v.findViewById(R.id.tvMoney);

        this.v = v;
    }
}
}

MachineInfo

public class MachineInfo extends AppCompatActivity {

private TextView mLocation, mMoney, mNotes;
private DBHelpter mDBHelpter;
private FloatingActionButton mFAB;

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

    mDBHelpter = new DBHelpter(getApplicationContext());

    mLocation = (TextView) findViewById(R.id.tvLocation);
    mMoney = (TextView) findViewById(R.id.tvMoney);
    mNotes = (TextView) findViewById(R.id.tvNotes);
    mFAB = (FloatingActionButton) findViewById(R.id.fabAddIncome);

    SharedPreferences mSharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

    String total_amount = mSharedPreferences.getString("total_amount", null);
    mMoney.setText(total_amount);

    String location = mSharedPreferences.getString("location", null);
    mLocation.setText(location);

    mFAB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), IncomeCreation.class);
            startActivity(i);
        }
    });
}
}

如果您需要任何其他活动或布局,请告诉我们!

1 个答案:

答案 0 :(得分:1)

首先,我建议更改为getIncomeOfMachine()。由于此方法位于DBHelper中,因此它应仅负责与数据库交互。它应该了解有关SharedPreferencesActivity的任何信息。相反,它应该返回从数据库中检索的值,并让调用者决定如何处理该值。由于您知道生成的Cursor中只有一行,因此您不需要循环。只需移动到第一行,获取总数,然后返回。

其次,由于您只是将一个值传递给某个活动,并且您可能不需要将其永久存储以供以后使用,因此您应该使用Intent而不是SharedPreferencesStarting Another Activity有一个向另一个活动发送值的明显示例。如果您在应用中使用此示例时遇到问题,请随时发布一个新问题,说明您的操作并解释您遇到的问题。