Friday, September 28, 2018

Sqlite Database insert

package net.samaysoftware.listviewdemo;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileReader;
import java.io.Reader;

public class NewExpenseActivity extends AppCompatActivity implements View.OnClickListener {

    EditText etReason, etAmount;
    Button btnAddExpense;

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

        setTitle("Add expense");
        createTable();

        etReason = (EditText) findViewById(R.id.etReason);
        etAmount = (EditText) findViewById(R.id.etAmount);
        btnAddExpense = (Button) findViewById(R.id.btnAddExpense);
        btnAddExpense.setOnClickListener(this);
    }

    private void createTable() {
        SQLiteDatabase db = null;
        try {
            db = openOrCreateDatabase("SampleDB", MODE_PRIVATE,null);
            String q = "create table if not exists Expense(expenseid integer primary key autoincrement,reason varchar(100), amount integer)";
            db.execSQL(q);
        }catch (Exception ee){
            Toast.makeText(this, "Some error while creating expense table", Toast.LENGTH_LONG).show();
        }
        finally {
            if(db!=null && db.isOpen()) {
                db.close();
            }
        }

    }

    @Override    public void onClick(View view) {

        String stramount = etAmount.getText().toString();
        String strreason = etReason.getText().toString();

        SQLiteDatabase db = null;
        try {
            db = openOrCreateDatabase("SampleDB", MODE_PRIVATE,null);
            String q = "insert into Expense(amount, reason) values("+stramount+",'"+strreason+"')";
            db.execSQL(q);
            Toast.makeText(this, "Expense added successfully !!", Toast.LENGTH_LONG).show();
            Intent i = new Intent(this, ExpenseListActivity.class);
            startActivity(i);
        }catch (Exception ee){
            Toast.makeText(this, "Some error while inserting in Expense table", Toast.LENGTH_LONG).show();
        }
        finally {
            if(db!=null && db.isOpen()) {
                db.close();
            }
        }



    }
}

No comments:

Post a Comment

Near by App

https://drive.google.com/file/d/0B2ag35s4X53Eb2pSQVI1SzNudE0/view