更新某个值并将其保存在脱机数据库

时间:2017-10-17 13:49:51

标签: java android listview android-sqlite

我正在开发一个小应用程序,默认情况下textview设置为150,000。每个月我都会将值重置为默认值。每次我花费一些金额,我都会打开我的应用程序并输入我花费的金额以及花费的详细信息。

我所做的是创建一个离线数据库来存储我花费一些金额的所有时间,以及它的id和细节。每按一次“花费”按钮,总金额就会减少我在EditText中输入的金额。

我还没有实现如何更新总金额,我相信我必须使用一个名为sharedpreference number的东西。

这是主要活动:

    public class MainActivity extends AppCompatActivity {

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

    Button spendMoney = (Button)this.findViewById(R.id.spendMoney);
    Button test = (Button)this.findViewById(R.id.test);
    TextView totalTxt = (TextView) this.findViewById(R.id.totalTxt);
    final EditText spendAmount = (EditText)this.findViewById(R.id.spendAmount);

    // int totalAmount = Integer.parseInt(totalTxt.getText().toString());

    final Paid_DB db = new Paid_DB(this);



    spendMoney.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {
            db.addPayment(new Payment(0, (Integer.parseInt(spendAmount.getText().toString())), "Test Details"));

        }

    });

    //totalAmount = totalAmount - Integer.parseInt(spendAmount.getText().toString());
   // totalTxt.setText(totalAmount);
    test.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {
          Intent i = new Intent(null, DetailsActivity.class);
            startActivity(i);
        }

    });

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.example.user.paid.MainActivity">

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="13dp"
    android:layout_marginStart="13dp"
    android:layout_marginTop="53dp"
    android:fontFamily="sans-serif"
    android:text="Total:"
    android:textSize="30sp"
    tools:layout_editor_absoluteX="25dp"
    tools:layout_editor_absoluteY="36dp" />

<EditText
    android:id="@+id/spendAmount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="number"
    tools:layout_editor_absoluteX="72dp"
    tools:layout_editor_absoluteY="143dp"
    android:layout_marginBottom="38dp"
    android:layout_above="@+id/spendMoney"
    android:layout_centerHorizontal="true" />

<Button
    android:id="@+id/spendMoney"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Spend Money"
    tools:layout_editor_absoluteX="115dp"
    tools:layout_editor_absoluteY="215dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

<TextView
    android:id="@+id/totalTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignEnd="@+id/spendMoney"
    android:layout_alignRight="@+id/spendMoney"
    android:fontFamily="sans-serif"
    android:text="150,000"
    android:textSize="30sp"
    tools:layout_editor_absoluteX="25dp"
    tools:layout_editor_absoluteY="36dp" />

<Button
    android:id="@+id/test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Test"
    tools:layout_editor_absoluteX="134dp"
    tools:layout_editor_absoluteY="358dp"
    android:layout_marginBottom="90dp"
    android:layout_alignParentBottom="true"
    android:layout_alignLeft="@+id/spendMoney"
    android:layout_alignStart="@+id/spendMoney" />

这是我输入离线数据库的对象,包含ID,花费的金额和付款的详细信息:

    public class Payment {


private int id;
private int amount;
private String details;


public Payment(){}

public Payment(int id, int amount, String details) {
    this.id = id;
    this.amount = amount;
    this.details = details;
}

public Payment(int id, int amount) {
    this.id = id;
    this.amount = amount;
}

public Payment(int amount, String details) {
    this.amount = amount;
    this.details = details;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getAmount() {
    return amount;
}

public void setAmount(int amount) {
    this.amount = amount;
}

public String getDetails() {
    return details;
}

public void setDetails(String details) {
    this.details = details;
}  }

这是离线数据库:

    ublic class Paid_DB extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "Payments_DB";

// Contacts table name
private static final String PAYMENT_TABLE = "PaymentTable";

// Contacts Table Columns names
private static final String PAY_ID = "id";
private static final String PAY_AMOUNT = "amount";
private static final String PAY_DETAILS = "details";

Paid_DB(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + PAYMENT_TABLE + "("
            + PAY_ID + " INTEGER PRIMARY KEY," + PAY_AMOUNT + " INTEGER,"
            + PAY_DETAILS + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + PAYMENT_TABLE);

    onCreate(db);
}

public void addPayment(Payment payment){

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(PAY_AMOUNT, payment.getAmount());
    values.put(PAY_DETAILS, payment.getDetails()); // Contact Phone Number

    // Inserting Row
    db.insert(PAYMENT_TABLE, null, values);
    db.close();
}

void addListItem(ArrayList<String> listItem) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    for (int i = 0; i < listItem.size(); i++) {

        Log.e("vlaue inserting==", "" + listItem.get(i));
        values.put(PAY_AMOUNT, listItem.get(i));
        db.insert(PAYMENT_TABLE, null, values);

    }

    db.close(); // Closing database connection
}

Cursor getListItem() {
    String selectQuery = "SELECT  * FROM " + PAYMENT_TABLE;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    return cursor;
}}

最后,这是详细信息活动,它包含一个列表视图,用于存储和显示已完成的所有付款:

    public class DetailsActivity extends AppCompatActivity {

ArrayList<String> detailsListArrayList;
private ListView lv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_details);

    lv = (ListView) findViewById(R.id.listView);
     detailsListArrayList = new ArrayList<>();

    detailsListArrayList.add("Item1");
    detailsListArrayList.add("Item2");
    detailsListArrayList.add("Item3");
    detailsListArrayList.add("Item4");
    detailsListArrayList.add("Item5");

    Paid_DB db = new Paid_DB(this);

    db.addListItem(detailsListArrayList);

    Cursor cursor = db.getListItem();

    Log.e("count", " " + cursor.getCount());
    if (cursor != null) {
        cursor.moveToNext();

        do {

            Log.e("value==", "" + cursor.getString(1));

        } while (cursor.moveToNext());
    }

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            detailsListArrayList );

    lv.setAdapter(arrayAdapter);
}
}

XML文件:

    <android.support.constraint.ConstraintLayout 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.example.user.paid.DetailsActivity">

<ListView
    android:id="@+id/listView"
    android:layout_width="368dp"
    android:layout_height="495dp"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp" />

每次点击“测试”按钮,应用程序都会崩溃。每次我尝试使用“花费”按钮添加新条目时,应用程序也会崩溃。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我从这里可以看出(没有错误日志)是:

1)您的应用在按下测试按钮时崩溃,因为您在那里开始活动而不传递public void onClick(View v) { Intent i = new Intent(getApplicationContext(), DetailsActivity.class); startActivity(i); } 对象。试试这个:

addPayment()

2)支出按钮尝试向您的数据库添加新的支付条目。但是在数据库模式中,您将PAY_ID声明为主键。在public ArrayList<Payment> getAllPayments() { ArrayList<Payment> result = new ArrayList<>(); Cursor c = db.query("PAYMENTS",new String[]{"PAY_ID","PAY_AMOUNT","PAY_DETAIL"},null,null,null,null,null); ; c.moveToFirst(); while(! c.isAfterLast()) { int s1=c.getInt(0); int s2=c.getInt(1); String s3=c.getString(2); results.add(new Payment(s1,s2,s3)); c.moveToNext(); } return results; 的后期,您只是传递了PAY_AMOUNT和PAY_DETAILS,因此您错过了PAY_ID,这似乎导致了崩溃。

编辑:这样的事情应该将所有付款作为ArrayList返回(可能包含错误,只需在此编辑器中编写)。

{{1}}

}

要更新ListView,您应该仔细查看此链接,它解释了如何使用ListViews和自定义ListView适配器Painting in AWT and Swing