Monday, 8 April 2013

 

Date Picker - Anroid Example

Project Structure :

date picker project sketch
 


 

File : res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
   <Buttonh
       android:id="@+id/changeDate"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Click To Change Date" />
   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Current/Selected Date (M-D-YYYY): "
       android:textAppearance="?android:attr/textAppearanceLarge" />
  
   <TextView
       android:id="@+id/Output"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text=""
       android:textAppearance="?android:attr/textAppearanceLarge" />
 </LinearLayout>  

File : res/layout/main.xml

 
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
   <Buttonh
       android:id="@+id/changeDate"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Click To Change Date" />
   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Current/Selected Date (M-D-YYYY): "
       android:textAppearance="?android:attr/textAppearanceLarge" />
  
   <TextView
       android:id="@+id/Output"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text=""
       android:textAppearance="?android:attr/textAppearanceLarge" />
 </LinearLayout

File : src/DatePickerExample.java

 
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerExample extends Activity {
    private TextView Output;
    private Button changeDate;
    private int year;
    private int month;
    private int day;
    static final int DATE_PICKER_ID = 1111;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Output = (TextView) findViewById(R.id.Output);
        changeDate = (Button) findViewById(R.id.changeDate);
        // Get current date by calender
         
        final Calendar c = Calendar.getInstance();
        year  = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day   = c.get(Calendar.DAY_OF_MONTH);
        // Show current date
         
        Output.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(month + 1).append("-").append(day).append("-")
                .append(year).append(" "));
  
        // Button listener to show date picker dialog
         
        changeDate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // On button click show datepicker dialog
                showDialog(DATE_PICKER_ID);
            }
        });
   }
     
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_PICKER_ID:
             
            // open datepicker dialog.
            // set date picker for current date
            // add pickerListener listner to date picker
            return new DatePickerDialog(this, pickerListener, year, month,day);
        }
        return null;
    }
    private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
        // when dialog box is closed, below method will be called.
        @Override
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
             
            year  = selectedYear;
            month = selectedMonth;
            day   = selectedDay;
            // Show selected date
            Output.setText(new StringBuilder().append(month + 1)
                    .append("-").append(day).append("-").append(year)
                    .append(" "));
     
           }
        };
}

Thursday, 13 September 2012

Expendable list view in android

Expentable list view in android:

Layout:

Main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <ExpandableListView android:layout_height="wrap_content"
    android:layout_weight="1"
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:groupIndicator="@drawable/icon"
    android:divider="@null"></ExpandableListView> 
</LinearLayout>

child.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent" android:layout_height="wrap_content">
    <ImageView android:layout_width="wrap_content" android:id="@+id/imageView1" android:src="@drawable/icon2" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"></ImageView>
    <TextView android:text="TextView" android:layout_width="wrap_content"  android:id="@+id/textView1" android:layout_gravity="center_horizontal" android:layout_height="fill_parent" android:gravity="center_vertical"></TextView>
  </LinearLayout>

ExpandableListExample.java

package com.android.valllllll2000;

import android.os.Bundle;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;

import android.app.ExpandableListActivity;
import android.graphics.Typeface;
import android.widget.TextView;

public class ExpandableListExample extends ExpandableListActivity {

    private MyExpandableListAdapter mAdapter;
    private String[] preguntas;
    private String[][] respuestas;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        // getting the arrays from the ressources

        // group array
        preguntas = getResources().getStringArray(R.array.countries);

        // children array
        String[] respuestas1 = getResources().getStringArray(R.array.capitals);
        respuestas = new String[respuestas1.length][1];
        for (int i = 0; i < respuestas1.length; i++) {
            respuestas[i][0] = respuestas1[i];
        }

        // Set up our adapter
        mAdapter = new MyExpandableListAdapter();
        setListAdapter(mAdapter);
    }

    public class MyExpandableListAdapter extends BaseExpandableListAdapter {

        public Object getChild(int groupPosition, int childPosition) {
            return respuestas[groupPosition][childPosition];
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        public int getChildrenCount(int groupPosition) {
            return respuestas[groupPosition].length;
        }

        public TextView getGenericView() {
            // Layout parameters for the ExpandableListView
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
           
            TextView textView = new TextView(ExpandableListExample.this);
           
            textView.setLayoutParams(lp);

            textView.setPadding(60, 5, 0, 5);
            textView.setTextAppearance(getBaseContext(), R.style.TitleText);
            return textView;
        }

        public View getChildView(int groupPosition, int childPosition,
                boolean isLastChild, View convertView, ViewGroup parent) {
           
            //Including a custom view for the child image and text
            View inflatedView = View.inflate(getApplicationContext(),
                    R.layout.child, null);
            inflatedView.setPadding(50, 0, 0, 0);
            TextView textView =(TextView)inflatedView.findViewById(R.id.textView1);
           
            //lets set up a custom font
            Typeface font = Typeface.createFromAsset(getAssets(),"BLOODY.ttf");
            textView.setTypeface(font);
            textView.setTextSize(17);
            textView.setText(getChild(groupPosition, childPosition).toString());
            return inflatedView;
        }

        public Object getGroup(int groupPosition) {
            return preguntas[groupPosition];
        }

        public int getGroupCount() {
            return preguntas.length;
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded,
                View convertView, ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getGroup(groupPosition).toString());
            return textView;
        }

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public boolean hasStableIds() {
            return true;
        }

    }
}

Android spinner from sqllite.

Android spinner from sqllite.

Layout: Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add New Label"
        android:padding="8dip" />
   
    <!-- Input Text -->
    <EditText android:id="@+id/input_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"/>
   
    <!-- Add Button -->
    <Button android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Label"
        android:layout_marginLeft="8dip"
        android:layout_marginTop="8dip"/>
   
    <!-- Select Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Label"
        android:padding="8dip" />
   
    <!-- Spinner Dropdown -->
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/spinner_title"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
    />"

</LinearLayout>

java code:
AndroidSpinnerFromSQLiteActivity:

package com.example.androidhive;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AndroidSpinnerFromSQLiteActivity extends Activity implements
        OnItemSelectedListener {

    // Spinner element
    Spinner spinner;

    // Add button
    Button btnAdd;

    // Input text
    EditText inputLabel;

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

        // Spinner element
        spinner = (Spinner) findViewById(R.id.spinner);

        // add button
        btnAdd = (Button) findViewById(R.id.btn_add);

        // new label input field
        inputLabel = (EditText) findViewById(R.id.input_label);

        // Spinner click listener
        spinner.setOnItemSelectedListener(this);

        // Loading spinner data from database
        loadSpinnerData();

        /**
         * Add new label button click listener
         * */
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler
                    DatabaseHandler db = new DatabaseHandler(
                            getApplicationContext());

                    // inserting new label into database
                    db.insertLabel(label);

                    // making input filed text to blank
                    inputLabel.setText("");

                    // Hiding the keyboard
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);

                    // loading spinner with newly added data
                    loadSpinnerData();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    /**
     * Function to load the spinner data from SQLite database
     * */
    private void loadSpinnerData() {
        // database handler
        DatabaseHandler db = new DatabaseHandler(getApplicationContext());

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

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.select_dialog_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);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
        // On selecting a spinner item
        String label = parent.getItemAtPosition(position).toString();

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

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }
}

2.DatabaseHandler.java:

package com.example.androidhive;

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

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

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

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

    // Labels table name
    private static final String TABLE_LABELS = "labels";

    // Labels Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

        // Create tables again
        onCreate(db);
    }
   
    /**
     * Inserting new lable into lables table
     * */
    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();
       
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, label);
       
        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }
   
    /**
     * Getting all labels
     * returns list of labels
     * */
    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();
       
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_LABELS;
    
        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(1));
            } while (cursor.moveToNext());
        }
       
        // closing connection
        cursor.close();
        db.close();
       
        // returning lables
        return labels;
    }
}