Thursday 10 March 2016

Android coding guidelines

Ever confused about the naming conventions to be followed in android?? Ever wondered about the guidelines to be followed while doing an android project??

Well,then have a look at this

https://github.com/ribot/android-guidelines/blob/master/project_and_code_guidelines.md

Happy Coding,
-Rajeev

Resolve "set ANDROID_DAILY_OVERRIDE environment variable" error

Ever come across "set ANDROID_DAILY_OVERRIDE environment variable" error while building
your android project in studio??

This is how it can be solved:

1.In your terminal, run this
      launchctl setenv ANDROID_DAILY_OVERRIDE <your-value-on-error-message>

   <your-value-on-error-messag> is the value that you get in the error message

2.Restart Android studio


Tuesday 21 April 2015

Creating Custom Text View to apply Custom Font


Creating custom text view in android is a breeze.You just have to follow few very simple steps.


Step 1:Create a attributes  file (say attrs.xml) in res/values folder.This is how android lets you define attributes for your custom view

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomFont">
        <attr name="font_name" format="string"/>
    </declare-styleable>
</resources>

Step 2: Create a class by extending the TextView.Fetch the custom font name & set the typeface.

public class CustomFont extends TextView {
    public CustomFont(Context context) {
        super(context);
    }

    public CustomFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public CustomFont(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    private void init(Context context,AttributeSet attrs){
       TypedArray attributes=context.obtainStyledAttributes(attrs,R.styleable.CustomFont);
       if(attributes!=null){
           String fontName=attributes.getString(R.styleable.CustomFont_font_name);
           if(fontName!=null){
               Typeface tf=Typeface.createFromAsset(context.getAssets(),fontName);
               setTypeface(tf);
           }
       }
        attributes.recycle();
    }

}

Step 3:Add your custom text view in the layout.Specify the font name (.ttf file).In my case ,font is placed in assets folder.Hence,the path would be:"YOUR_FONTNAME.ttf"

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@android:color/holo_blue_dark"
    tools:context=".MainActivity">

    <escape.rajeevkr.studio.com.lollypoptest.CustomFont
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom Font"
        android:layout_centerInParent="true"
        android:textSize="25sp"
        android:textColor="@android:color/white"
        custom:font_name="customfont.ttf"
        />

</RelativeLayout>


And That's it.You are done creating your Custom Text View.It would look something like this.



Happy Coding,
-Rajeev

Sunday 19 August 2012

Creating Fragments in the simplest possible way-1


What are fragments?


Fragments in Android are like modular sections of a single activity having their own life-cycle.Umm..sort of sub-activity.

Fragments life cycle methods are affected by its host(Parent) life cycle.For ex:When parent activity is paused,so are all the fragments.When parent activity is destroyed,so are all the Fragment.When an activity is running,each of the fragments can be manipulated(Well i haven't tried it yet..:P)independently.

You can read more about fragments in 

http://developer.android.com/guide/components/fragments.html


Creating fragments

Like Activities,fragments also have their Life cycle callback methods.


To create a fragment you need to override at least its "onCreateView(Bundle)".This method has to return a view and that view is the root of your fragments layout.

Steps to create fragments

Step1:Create a layout XML file(simple_text_fragment.xml)
---------------------------------------------------------------------------------------------

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

    <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

    <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>
---------------------------------------------------------------------------------------------

Step 2:Create a class that extends Fragment and Override its onCreateView method
---------------------------------------------------------------------------------------------
public  class Example_fragment extends Fragment {
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.v("Fragments","onAttach");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("Fragments","onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.v("Fragments","onCreateView");
                //1st Arg:Fragments Layout
               //2nd Arg:container(parent)
               //3rd Arg:Boolean arg indicating whether the fragment layout should be attached to       the viewGroup(2nd Arg).In our case,it is no as the system itself is doing it.

return inflater.inflate(R.layout.simple_text_fragment,container,false);
}
@Override
public void onStart() {

super.onStart();
Log.v("Fragments","onStart");

}
@Override
public void onResume() {

super.onResume();
Log.v("Fragments","onResume");
}
@Override
public void onPause() {
super.onPause();
Log.v("Fragments","onResume");
}
@Override
public void onStop() {
super.onStop();
Log.v("Fragments","onResume");
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onDetach() {
super.onDetach();
}
}
---------------------------------------------------------------------------------------------
Step 3:
In you parent layout's XML file include the below snippet 
---------------------------------------------------------------------------------------------

    <fragment 
    android:name="com.example.apidemo.Example_fragment"
    android:id="@+id/myfragment"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
    />

---------------------------------------------------------------------------------------------



Step 4:

Create Root Activity that inflates parents layout XML.

That's it.Your activity should  look something similar like this


Happy Coding,
-Rajeev










Sunday 12 August 2012

How to Extend Array Adapters to Create customized listView ?


The answer i got in the web to the above question is "SCRATCH YOUR OWN ITCH".Hence,am putting on this post so that people who are struggling to get this thing right,need not have to spend lot of time scratching their own itch..:p.

You can use the below code to use ListViews along with other views in the layout or ListView alone.
Lets get Started??.. Yeah.
There are three simple steps in creating a customized List View

  • Get the ListView in your layout by specifying its resource ID
  • Get the instance of your own ArrayAdapter class
  • Bind ListView to the adapter



Get the ListView in your layout by specifying its resource ID

Get the ListView instance in layout by its ID.

// Get the list View
mCustomListView = (ListView) findViewById(R.id.db_menu);

Get the instance of your own ArrayAdapter class and Bind ListView to the adapter

We can  combine steps 2 and 3 and implement it as below

// set the Adapter
mCustomListView.setAdapter(new DashBoardListAdapter(
getApplicationContext(), R.layout.dashboard_custom_list));

the argument R.layout.dashboard_custom_list is the resource ID of your customized view which has to created separately to achieve customization, not your ListView ID in the main layout.

Your Array adapter class should override getView method and getCount method of the parent.
Here's the implementation,
-------------------------------------------------------------------------------------------------
class DashBoardListAdapter extends ArrayAdapter<String> {
private Context mContext;
private String[] mTitle_content, mDesc_content;
private TextView mTitle, mDescription;

public DashBoardListAdapter(Context context, int layout) {
super(context, layout);
this.mContext = context;
setContentValues();
}

@Override
public int getCount() {
return mTitle_content.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (null == convertView) {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflator.inflate(R.layout.dashboard_custom_list, null);
} else {
v = convertView;
}
mTitle = (TextView) v.findViewById(R.id.db_topic);
mTitle.setText(mTitle_content[position]);
mDescription = (TextView) v.findViewById(R.id.db_description);
mDescription.setText(mDesc_content[position]);
return v;
}

private void setContentValues() {
mTitle_content = mContext.getResources().getStringArray(
R.array.bashboard_menu);
mDesc_content = mContext.getResources().getStringArray(
R.array.db_list_desc);
-------------------------------------------------------------------------------------------------------

Thats it,your listView is ready to use.In the listView by taking a seperate layout,i have changed the textView appearance in the listView and it looks lyk,



Happy Coding,
-Rajeev


Saturday 11 August 2012

Messing with Scroll Views in android

The post is regarding the usage of scroll views in android.The layout for the same is 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" >

    <ScrollView
        android:id="@+id/tc_termsConditions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tc_buttoncontainer" >

        <RelativeLayout
            android:id="@+id/tc_textHolder"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/tc_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="@string/tc_title"
                android:textSize="20sp"
                android:textStyle="bold"
                android:typeface="serif" >
            </TextView>

            <TextView
                android:id="@+id/tc_description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/tc_title"
                android:fitsSystemWindows="false"
                android:singleLine="false"
                android:text="@string/tc_content_description" />
        </RelativeLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/tc_buttoncontainer"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/tc_btn_decline"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/btn_decline"
            android:textSize="15dip"
            android:typeface="monospace" />

        <Button
            android:id="@+id/tc_btn_accept"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/btn_accept"
            android:textSize="15dip"
            android:typeface="monospace" />
    </LinearLayout>

</RelativeLayout>
----------------------------------------------------------------------------------------------------------

Sunday 22 July 2012

Creating a Custom cursor Adapter and Binding it to a List View in Android

This Post is about creating a Custom Cursor Adapter,which comes handy when fetching the data from the SQLite DB/Content Provider and Binding the same to a View,a ListView to be precise.

I am taking this as my first post as i spent almost half-a-day to get it right.

The following example demonstrates on how to Fetch the contacts and display it in your own way using a List View.Each row in the custom list has an Image,The name fetched from contacts DB and chat availabilty of the contact(hardcoded offcourse.. :P).You can consider this a stub code and make improvisations on it.



/**
 * Activity that displays Custom List View
 * @author rajeev ranganathan
 *
 */
public class MainActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor>{

private listBuilder mListBuilder;
private LayoutInflater mInflator;
private int LOADER_ID=1000;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
               //Using Cursor Loader for better Performance.
              //Refer Cursor Loader to get more understanding.

getLoaderManager().initLoader(LOADER_ID, null,this);
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//Create the Cursor that will take care of the data being displayed
Log.d("TAG","onCreateLoader...");
return new CursorLoader(getApplicationContext(),
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
//Now Bind the data to the View
Log.d("TAG","onLoadFinished...ARG1= "+cursor);
mListBuilder=new listBuilder(getApplicationContext(), cursor);
setListAdapter(mListBuilder);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
//NO OP

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

class listBuilder extends CursorAdapter{
public listBuilder(Context context, Cursor c) {
super(context, c);
Log.d("TAG","CursorAdapter Constr..");
mInflator=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public void bindView(View arg0, Context arg1, Cursor cursor) {
String name = null;
Log.d("TAG","CursorAdapter BindView");
if(null!=cursor){
Log.d("TAG","CursorAdapter BindView:Cursor not null");
name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY   _NAME));
}
//Set the Menu Image
ImageView menuImage=(ImageView)arg0.findViewById(R.id.iv_ContactImg);
menuImage.setImageResource(R.drawable.ic_launcher);

//Set the Name
TextView heading=(TextView)arg0.findViewById(R.id.tv_ContactName);
heading.setText(name);
//Set Availability
TextView randomText=(TextView)arg0.findViewById(R.id.tv_ContactNumber);
randomText.setText("Not Available");

}

@Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
Log.d("TAG","CursorAdapter newView");
final View customListView=mInflator.inflate(R.layout.activity_listrow,null);
return customListView;
}

}
}
The XML design for the layout is as 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" >

    <ImageView
        android:id="@+id/iv_ContactImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher" />


    <TextView
        android:id="@+id/tv_ContactName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/iv_ContactImg"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000000" />


    <TextView
        android:id="@+id/tv_ContactNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tv_ContactName"
        android:layout_below="@+id/tv_ContactName"
        android:layout_marginLeft="18dp"
        android:text="TextView"
        android:textColor="#000000" />

</RelativeLayout>


The final result would look something like this,

Happy Coding,
-Rajeev