-1

I'm developing a tiny app that has a value in a textview set to 150,000 by default. Each month I reset the value back to the default. Every time I spend some of that amount, I open my app and enter the amount I spent and the details of what it was spent on.

What I did was create an offline database to store all the times I spent some of that amount, along with it's id and details. Each time I press the "spend" button, the total amount is reduced by the amount I have entered in the EditText.

I haven't implemented how I'll update the total amount yet, I believe I have to use something called sharedpreference number.

This is the main activity:

    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 file:

    <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" />

This is the object I enter into the offline database, containing the id, the amount spent, and details of the payment:

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

This is the offline database:

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

And finally, this is the details activity, it contains a list view that stores and displays all the payments that have been made:

    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 file:

    <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" />

Every time I click on the "test" button, the app crashes. And every time I try to add a new entry using the "spend" button, the app also crashes. What did I do wrong?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Kirito
  • 1
  • 1
  • 4

1 Answers1

0

What I can tell from here (without the error log) is:

1) your app crashes when pressing the test-button because you are starting an activity there without passing a contextobject. Try this:

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

2) The spend button tries to add a new payment entry to your database. But in your database schema , you declare the PAY_ID as a primary key. Later in your addPayment() you are just passing the PAY_AMOUNT and PAY_DETAILS, so you are missing the PAY_ID which seems to lead to a crash.

EDIT: something like this should return all the payments as an ArrayList (may Contain bugs, just wrote it in this editor).

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;

}

To update your ListView, you should have a closer look a this link, that explains how to work with ListViews and a custom ListView adapter Custom Adapter for List View

Pynnie
  • 136
  • 12
  • Well, I did what you suggested and both worked out fine. Right now, I can click on the spend button and it doesn't crash (as long as there is a value in the edit text, since I didn't catch that exception obviously). I can also click the test button to view the listview without issues. Now, I need to know how to update the total amount in the textView, as the guy above suggested but I'm not sure how to implement it. Also, how am I supposed to fill the list view every time I enter new values? because right now it only shows "List item 1", "List item 2" etc. – Kirito Oct 17 '17 at 15:10
  • I'm sorry, I don't get how and where I'm supposed to apply your method? – Kirito Oct 17 '17 at 16:24
  • the edited code you go into your `Paid_DB` class. You have to feed your adapter for the ListView with this method. Just read through the post i linked above – Pynnie Oct 18 '17 at 07:20