Thursday, March 14, 2013

ANDROID SPINNERS

                                      ANDROID SPINNERS

Android has spinner structure like comboboxes in html.

I will explain to create default spinner in 2 ways.
First one is declaring resources as static in xml
Second one is declaring resources as programmatically in Java

First
You should declare your spinner resource in xml layout file such as

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

    <Spinner
        android:id="@+id/declaredSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="133dp"
        android:entries="@array/resources" />

</RelativeLayout>


And then you should create a resources in strings.xml file
<string-array name="country_arrays">
        <item>Malaysia</item>
        <item>India</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
</string-array>

And then you should handle your spinner functions in you activity

Spinner declaredSpinner= (Spinner) findViewById(R.id.declaredSpinner);
declaredSpinner.setOnItemSelectedListener(new yourListener());

you should create your own class as inner in your activity

class YourListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Selected", Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Not Selected", Toast.LENGTH_LONG).show();
}

}

If you do not want to write inner class you can use class in function
declaredSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}

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

Second one needs to use adapter because you are creating your resources programmatically and you should
bind them through the spinner resources

So firstly you will declare your layout file such as below
<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">

    <Spinner
        android:id="@+id/declaredSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="133dp"
/>

</RelativeLayout>

If you notice it is different according to the first.
Secondly you will open your activity class

1 ) Create your string arrays
String[] ustspinner = new String[5];
for(int i = 0 ; i < 5 ; i++){
ustspinner = ""+i;
}
2 ) create your arrayadapter with your string arrays
ArrayAdapter<String> defaultAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, ustsolspiner);
defaultAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
3 ) then set to your spinner
spinnerReference.setAdapter(defaultAdapter);
4 ) You can define your functions as the previous one.

The best one is creating your own customized spinner.
For example i want an image and then a text in my spinner how can we do?
We must create CustomizedAdapter.
Steps :
1 ) Create your own layout file in layout folder. Such as customizedspinner.xml
2 ) Get a reference to spinner
3 ) Create your own Customized spinners adapter that is extended from ArrayAdapter
4 ) set your adapter object to your spinner reference


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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="0.74" 
        android:background="@drawable/textdrawable">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent" >

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ido"
                android:contentDescription="@string/img" />
        </LinearLayout>

        <TextView
            android:id="@+id/spinerdatetext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/blankForDate"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

</LinearLayout>


 class SpAD extends ArrayAdapter<String>{

@Override
public int getPosition(String item) {
// TODO Auto-generated method stub
return 4;
}
public SpAD(Context context, int textViewResourceId,   String[] objects) {
            super(context, textViewResourceId, objects);
        }
@Override
        public View getDropDownView(int position, View convertView,ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
   LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.spinerdate, parent, false);
            TextView label=(TextView)row.findViewById(R.id.spinerdatetext);
            label.setText(tenDays[position]);
            ImageView icon=(ImageView)row.findViewById(R.id.imageView1);
            icon.setImageResource(R.drawable.ido);
            return row;        
}
}
//Come to your own activity file
String[] days = tenDays();
       SpAD dataAdapter1 = new SpAD(this,R.layout.customizedspinner, days);
spinerdate.setAdapter(dataAdapter1);



Tuesday, March 12, 2013

SQLiteDatabase

                           SQLITE DATABASE



If you want to save your data to your storage of your device it is one of the easiest way to use SQLite
Basically we will use context to open or create a database and then we will use the SQLiteDatabase class to provide table or data to database also query the database
tables at last we will focus on to Cursor to trace the records on tables

context.openOrCreateDatabase("tablename",/*mode of table*/,null);
mode of table is related the permission of the table
as you know databases for the each program is different in device you can look your DDMS data/data/yourpackagename/databases
so if another program wants to reach to another programs database there should be permission for the table defined when it is created
1 ) If you want another program to reach your database your mode should be MODE_WORLD_READABLE or MODE_WORLD_WRITABLE
2 ) If you want another program not to reach your database your mode should be MODE_PRIVATE
now lets move on.

SQLiteDatabase sqlite = this.openOrCreateDatabase("abctable",MODE_PRIVATE,null);
sqlite.execSQL("CREATE TABLE ABC (F1 VARCHAR);");
sqlite.execSQL("INSERT INTO CAN (F1) values ('ABC') ");

--> Now second important class we will look at. That is Cursor which is associated with pointer structure. It enables you to trace your table rows.
Cursor cursor = sqlite.rawQuery("SELECT * FROM ABC");
Then if you use the code below you can be sure the cursor is on the first row
cursor.moveToFirst();
String str = cursor.getString(0);

now you handled the data from database of your device.


package com.example.myxdb;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
SQLiteDatabase mydb = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mydb = this.openOrCreateDatabase("tablename", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE ABC  (F1 VARCHAR);");
mydb.execSQL("INSERT INTO ABC (F1) VALUES ('DATABC')");
Cursor cursor = mydb.rawQuery("SELECT * FROM ABC", null);
cursor.moveToFirst();
String str = cursor.getString(0);
} catch (Exception e) {
Log.e("Error In Database Operations ", null);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}





Monday, March 4, 2013

Android Customized Toast

                                                ANDROID CUSTOMIZED TOAST

If you want to warn the user or give an information briefly to the user we use toast most of time. Default toast is not enough for some of the situations so you can make your own toast such as showing images in toast or through styled writings. For example lets create a customized toast :

1 ) Create an xml file into the res-->layout folder of your android project give name as customized.xml

!! You can define relativelayout, linearlayout, tablelayout... whatever you want... And drag an imageview into the folder and choose your image from the menu lastly your xml should look like below.

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/sdcard" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:text="@string/pleaseinsertyoursdcard"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
@drawable/sdcard you can open a folder as drawable into the res folder and put a picture named as sdcard into that folder.
Then come to your own activity class file that you want to show toast in it.

If you are in class that is extended from Activity you can code such below


 Toast toast = new Toast(getApplicationContext());
                  toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                  toast.setDuration(Toast.LENGTH_LONG);
                  LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                  toast.setView(inflater.inflate(R.layout.plugsdcard,null));
                  toast.show();

Now your own toast file will be shown. You can change your layout xml according to your needs.

!!!! If you want to show your toast in a class file that is extended from BroadcastReceiver you can code such as below in onReceive(Context context, Intent intent) function:

Toast toast = new Toast(context);
//context is your app act. context equals to getApplicationContext in class that is extended from Activity class
                   toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                   toast.setDuration(Toast.LENGTH_LONG);
                   LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                   toast.setView(inflater.inflate(R.layout.plugsdcard,null));
                   toast.show();


This small example can help your program being a little customized...

Saturday, March 2, 2013

Android Button Click

                                           ANDROID BUTTON CLICK

If you are developing android you always have to give response to button clicks. As there are lots of handling types of button clicks i would choose the type for the usage in code. For example you can define your Button in layout file xml as well as programmatic way in java. If you do not want to create new class and you do not want to deal with overriding functions you can write your function name into the xml file such as
In Layout Xml File

<Button
        android:id="@+id/writeToFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onclick = "writetofile"
        android:text="@string/writeTo" />

In Activity File
public void writetofile(View view){
 // View will be the clicked button
view.getVisibility();
}

I would choose this if i do not want to comply with complex code.

If i do not want to write into the xml file so i will write into the java file there are again 2 types.
Individual one is

Button button = (Button) findViewById(R.id.writeToFile);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//Handle your code
                        }
}

If you do not want to open unique function for each type of button click you will register for a handler which is the second type in java.

While in activity
button.setOnClickListener(this);
//inside activity you will create the function below
public void onClick(View view)
{  
switch (view.getId()){
                        case R.id.writeToTextFile:
Toast.makeText(view.getContext(), "You pressed to Write To File", Toast.LENGTH_SHORT).show();
break;
                }
         }

So third one is beneficial for the usage of code(less code and more efficient function)