Skip to main content

ListView Using SqLite Database

MainActivity.Java


package com.example.nikk.nikkukaushik;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.List;


public class MainActivity extends ActionBarActivity implements View.OnClickListener,AdapterView.OnItemSelectedListener{
    MyDataHelper data1=new MyDataHelper(this);
    int pos;
    private ImageButton ib;
    private Calendar cal;
    private int day;
    private int month;
    private int year;
    private EditText et;
    Spinner spinner;
    EditText amount;
    TextView txt5;
    EditText quantity,name;
    Button b1;
SQLiteDatabase db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // loadSpinnerData();
        spinner=(Spinner)findViewById(R.id.spinner);
        amount=(EditText)findViewById(R.id.editText2);
        name=(EditText)findViewById(R.id.editText4);
       txt5=(TextView)findViewById(R.id.textView5);
        quantity=(EditText)findViewById(R.id.editText3);
        b1=(Button)findViewById(R.id.button);
        spinner.setOnItemSelectedListener(this);
        ib = (ImageButton) findViewById(R.id.imageButton1);
        cal = Calendar.getInstance();
        day = cal.get(Calendar.DAY_OF_MONTH);
        month = cal.get(Calendar.MONTH);
        year = cal.get(Calendar.YEAR);

        et = (EditText) findViewById(R.id.editText);
        ib.setOnClickListener(this);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String label4 = name.getText().toString();
                String date=et.getText().toString();
                String Quantity=quantity.getText().toString();
                Integer Quantity1=Integer.parseInt(Quantity);
                String Amount=amount.getText().toString();
                Integer Amount1=Integer.parseInt(Amount);


               Boolean b;
                b=data1.adddata(date,Amount1,Quantity1,label4);
                if(b){

                    et.setText("");
                    name.setText("");
                    quantity.setText("");
                    amount.setText("");
                    loadSpinnerData();

                    Toast.makeText(getApplicationContext(),"record saved",Toast.LENGTH_SHORT).show();

                }

            }
        });

    }




    @Override
    public void onClick(View v) {
        showDialog(0);
    }
    protected Dialog onCreateDialog(int id) {
        return new DatePickerDialog(this, datePickerListener, year, month, day);
    }
    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            et.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
                    + selectedYear);
        }
    };

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String quentity = parent.getItemAtPosition(position).toString();
pos=position;
loadSpinnerData1();


        // Showing selected spinner item
        Toast.makeText(parent.getContext(), "You selected: " + quentity,
                Toast.LENGTH_LONG).show();
      //txt5.setText(s1);

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    private void loadSpinnerData(){
        // database handler
        MyDataHelper db = new MyDataHelper(getApplicationContext());

        // Spinner Drop down elements
        List<String> lables = db.getAllLabels();

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, lables);

        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner.setAdapter(dataAdapter);
    }
    private void loadSpinnerData1(){
        // database handler
        MyDataHelper db = new MyDataHelper(getApplicationContext());

        // Spinner Drop down elements
        List<String> lables = db.getAllLabels1();

       // txt5.setText((CharSequence) lables);
        String str= lables.get(pos);
        txt5.setText(str);



    }


}



MyDataHelper.java

package com.example.nikk.nikkukaushik;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by nikk on 3/24/2015.
 */

public class MyDataHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME="My";
    public static final String TABLE_NAME="con";
    public static final String ROWID_NO="id";
    public static final String ROW_BillAmount="amount";
    public static final String ROW_BillQuentity="quantity";
    public static final String ROW_DATE="date";
    public static final Integer DATABASE_VERSION=2;
    public static final String ROW_name="name";
    public static final String []arr={"quantity"};

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table con(id integer primary key autoincrement,date text,amount integer,quantity integer,name text)");

    }

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

    }
    public Boolean adddata(String date, Integer amount1, Integer quantity1,String name1) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(ROW_DATE, date);
        cv.put(ROW_BillAmount, amount1);
        cv.put(ROW_BillQuentity, quantity1);
        cv.put(ROW_name, name1);
        db.insert(TABLE_NAME, null, cv);

        db.close();
return true;
    }


    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(4));
               // labels.add(cursor.getString(3));


            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return labels;
    }
   // public  String getdata4()
   // {
       // SQLiteDatabase db = this.getReadableDatabase();
       // Cursor cursor = db.query(TABLE_NAME,arr,"name=?",new String[]{"gff"},null,null,null);
      //  while (cursor.)
   // }
   public List<String> getAllLabels1(){
       List<String> labels = new ArrayList<String>();

       // Select All Query
       String selectQuery = "SELECT  * FROM " + TABLE_NAME;

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

       // looping through all rows and adding to list
       if (cursor.moveToFirst()) {
           do {
               labels.add(cursor.getString(3));
               // labels.add(cursor.getString(3));


           } while (cursor.moveToNext());
       }

       // closing connection
       cursor.close();
       db.close();

       // returning lables
       return labels;
   }

}


activitymain.xml



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/ww">
    <EditText
        android:id="@+id/editText"
        android:layout_width="250dp"
        android:layout_marginTop="182dp"
        android:layout_height="wrap_content"
        android:editable="false"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">
    </EditText>

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText"
        android:layout_toRightOf="@+id/editText"

        android:cropToPadding="true"
         />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Database"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_above="@+id/imageButton1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="52dp"
        android:layout_alignRight="@+id/textView"
        android:layout_alignEnd="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="bill amount"
        android:id="@+id/textView2"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/editText3"
        android:layout_alignStart="@+id/editText3"
        android:layout_alignRight="@+id/editText3"
        android:layout_alignEnd="@+id/editText3" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="quantity"
        android:id="@+id/textView3"
        android:layout_marginTop="80dp"
        android:layout_below="@+id/editText2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText3"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="save"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/editText3"
        android:layout_alignStart="@+id/editText3" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="name"
        android:id="@+id/textView4"
        android:layout_marginTop="52dp"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText4"
        android:layout_alignTop="@+id/textView4"
        android:layout_alignLeft="@+id/editText3"
        android:layout_alignStart="@+id/editText3"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView5"
        android:layout_alignTop="@+id/spinner"
        android:layout_toRightOf="@+id/editText"
        android:layout_toEndOf="@+id/editText" />

</RelativeLayout>

Comments

Popular posts from this blog

Android: Login Screen using Fragments

In this tutorial, our focus is on making a User/Member login activity using fragments. With the help of Fragments we will use the same activity to show User login area and also Members Login area. Prerequisite for this tutorial: You should be know how to make an Activity And most importantly you should have prior Knowledge of Fragments. For practising basic Fragment implementation refer to Android Simple Fragment Example      We have used only three activities for this: MainActivity(which represents the Login Screen) Fragments for Members area Fragment for New Users

Simple Login/Register Example using SQLite database

MainActivity.java(login Screen) package com.AndroidDevelopmentGuru.database_new; import java.util.List; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity {                                 EditText user, pass;                 Button login, not_reg;                 DatabaseHandler db;                 Cursor cursor;                                 @Override                 protected void onCreate(Bundle savedInstanceState) {                                 super.onCreate(savedInstanceState);                                 setContentView(R.layout.activity_main);

Android: Current Location Using Fused APi on Google Maps

This tutorial gives us the simple implementation of "Fused API" to fetch the current location on google map in android. Fused API is latest among all techniques to get the location. It provides you very precise results and also uses less battery of your device. It chooses GPS or Network provider to get to your current location. And it helps your device remember about the last saved location. Let's implement the Fused API to fetch/get the current location. Step 1: Create a new project in Android studio. and select Maps Activity.