Top Menu

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday, 18 September 2014

How to set textView at bottom in Linear layout


Create xml:

activity.main.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:background="@drawable/cover"  

    android:orientation="vertical" >

 

    <TextView

        android:id="@+id/textView1"

        android:layout_width="match_parent"

        android:layout_height=0dp

        android:gravity="center|bottom"

        android:layout_weight="1"

        android:text="Large Text"

        android:textAppearance="?android:attr/textAppearanceLarge" />

 

</LinearLayout>
Read more...

Wednesday, 10 September 2014

Page Curl effect with Image and Text in Android

1. Create a new project with package name - com.example.curlpagetutorial
2. Edit the 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" >

    <minh.app.mbook.MyLayout
        android:id="@+id/mainpage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:background="#FFf3c5d6"
        android:orientation="vertical" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="9"
        android:gravity="bottom"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_pre"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="Back" />

        <Button
            android:id="@+id/btn_next"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="Next" />
    </LinearLayout>
</LinearLayout>

3. Create page1.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:background="#ff660000"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/home"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/cloud" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="9"
        android:gravity="bottom"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_pre"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:text="Back" />

        <Button
            android:id="@+id/btn_next"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:text="Next" />
    </LinearLayout>

</LinearLayout>

4. Create another page2.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/text"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_margin="10dp"
        android:text="@string/text"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>

5. Now create a new package with name com.example.curlpagetutorial.layout
6. Create a new class in com.example.curlpagetutorial.layout named CustomLayout.java

package com.example.curlpagetutorial.layout;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

public abstract class CustomLayout extends RelativeLayout {
   
    public CustomLayout(Context context) {
        super(context);
       
    }

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

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        try {
            // Init game
            getPageContent();           
        } catch (Exception e) {
            // bug
            e.printStackTrace();
        }
    }

    //
    abstract protected void getPageContent();
}


7. Now create a class for example, TestLayout.java under package name com.example.curlpagetutorial
and import the CustomLayout.java class

package com.example.curlpagetutorial;

import com.example.curlpagetutorial.layout.CustomLayout;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

public class MyLayout extends CustomLayout{
    // Game name
    public static final String NAME = "SpaceBlaster";

    private Context mContext;
    //
    private int screenWidth;
    private int screenHeight;
    private int totalPages;
    //
    private MyBookView mBookView;


    public MyLayout(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public MyLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();

    }
    private ScrollView scrollView;
    //
    private void init() {

        totalPages = 2;
        Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();       
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();
        //
        mBookView = new MyBookView(mContext, screenWidth, screenHeight);
        // prepare view to take all screenshoot
        LinearLayout ll = new LinearLayout(mContext);
        ll.setOrientation(LinearLayout.VERTICAL);
       
        LayoutInflater factory = LayoutInflater.from(mContext);
       
        View view = factory.inflate(R.layout.page1, null);       
       
        ll.addView(view, screenWidth,screenHeight);
       
        View view2 = factory.inflate(R.layout.page2, null);       
        ll.addView(view2, screenWidth,screenHeight);
       
        // hide scrollview's component to have clear bitmap
        scrollView = new ScrollView(mContext);
        scrollView.addView(ll);
        scrollView.setVerticalScrollBarEnabled(false);
        scrollView.setHorizontalScrollBarEnabled(false);       
        scrollView.setFadingEdgeLength(0);
        addView(scrollView);
       
        // add true view and some actions
        View view3 = factory.inflate(R.layout.page1, null);       
        addView(view3, screenWidth, screenHeight);
       
        View view4 = factory.inflate(R.layout.page2, null);       
        addView(view4, screenWidth, screenHeight);

        addView(mPoemView);       
        mPoemView.setView(view3, view4);
               
    }
    //
    public void next(){
        mPoemView.next();
    }
    //
    public void pre(){
        mPoemView.pre();
    }
    //

    private Bitmap mBitmap;
    private Bitmap page1, page2;

    public void getPageContent() {
        if(mBitmap==null){
            setBitmap();
        }
    }

    private void setBitmap() {       
        mBitmap = Bitmap.createBitmap(screenWidth, screenHeight*totalPages, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(mBitmap);
        scrollView.draw(canvas);

        page1 = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas1 = new Canvas(page1);
        canvas1.drawBitmap(mBitmap, 0, 0, new Paint());
        page2 = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas2 = new Canvas(page2);
        canvas2.drawBitmap(mBitmap, 0, -screenHeight, new Paint());
        //removeAllViews();
        scrollView.setVisibility(View.GONE);
        //
        mPoemView.init(page1, page2);
        //
    }   
}

8. Now create a class MyBookView.java

package com.example.curlpagetutorial;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class MyBookView extends View{
    // MyHandler myHandler = new MyHandler();
    private static int DEFAULT_FLIP_VALUE = 20;
    private static int FLIP_SPEED = 30;

    private long mMoveDelay = 1000 / 30;

    float xTouchValue = DEFAULT_FLIP_VALUE, yTouchValue = DEFAULT_FLIP_VALUE;;

    // String result = "";

    //
    class FlippingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            Log.i("Thong bao: ", "Clock Handler is still running");
            MyPoemView.this.flip();

        }

        public void sleep(long delayMillis) {

            this.removeMessages(0);

            sendMessageDelayed(obtainMessage(0), delayMillis);

        }
    }

    //

    //
    FlippingHandler flippingHandler;
    //
    int width;
    int height;

    float oldTouchX, oldTouchY;
    boolean flipping = false;
    boolean next;

    Point A, B, C, D, E, F;

    Bitmap visiblePage;
    Bitmap invisiblePage;
    Paint flipPagePaint;

    boolean flip = false;

    Context context;
    //
    int loadedPages = 0;
    long timeToLoad = 0;
    //

    // boolean loadingDone = false;

    boolean onloading = true;

    boolean onMoving = false;



    public MyBookView(Context context, int width, int height) {
        super(context);
        this.context = context;
        this.width = width;
        this.height = height;
        }

    public void init(Bitmap page1, Bitmap page2) {

        //
        flippingHandler = new FlippingHandler();
        //
        flipPagePaint = new Paint();
        flipPagePaint.setColor(Color.GRAY);
        flipPagePaint.setShadowLayer(5, -5, 5, 0x99000000);
        A = new Point(10, 0);
        B = new Point(width, height);
        C = new Point(width, 0);
        D = new Point(0, 0);
        E = new Point(0, 0);
        F = new Point(0, 0);

        xTouchValue = yTouchValue = DEFAULT_FLIP_VALUE;
        visiblePage = page1;
        invisiblePage = page2;
        onMoving = false;
        flipping = false;

        loadData();

    }

    //
    private void loadData() {
        // listOfPages.add("this is my text");
        onloading = false;

    }
    //
    private View visibleView, invisibleView;
    //
    public void setView(View view1, View view2){
        visibleView = view1;
        invisibleView = view2;
        visibleView.setVisibility(VISIBLE);
        invisibleView.setVisibility(GONE);
        this.setVisibility(GONE);
    }

    //
    public void next(){
        visibleView.setVisibility(GONE);
        this.setVisibility(VISIBLE);
        flipping = true;
        next = true;       
        flip();
    }
    //
    public void pre(){
        swap2Page();
        visibleView.setVisibility(GONE);
        this.setVisibility(VISIBLE);
        flipping = true;
        next = false;
        xTouchValue = width-30;
        flip();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
      
        if (!onloading) {
            //
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                oldTouchX = event.getX();
                oldTouchY = event.getY();
                flip = true;
                if (oldTouchX > (width >> 1)) {
                    xTouchValue = DEFAULT_FLIP_VALUE;
                    yTouchValue = DEFAULT_FLIP_VALUE;
                    // set invisible page's content
                    next = true;
                } else {
                    // set invisible page's content
                    // invisiblePage.setContent(index-1, null);
                    //
                    next = false;
                    //
                    swap2Page();
                    xTouchValue = width;
                    yTouchValue = DEFAULT_FLIP_VALUE;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (onMoving) {
                    xTouchValue = width - A.x;
                    onMoving = false;
                }
                flipping = true;
                flip();
                break;
            case MotionEvent.ACTION_MOVE:
                // Log.i("Thong bao: ","x="+x+" y="+y);
                onMoving = true;
                //
                float xMouse = event.getX();
                float yMouse = event.getY();
                //
                xTouchValue -= (xMouse - oldTouchX) / 1;
                //
                yTouchValue -= yMouse - oldTouchY;
                //
                if (xMouse < oldTouchX) {
                    if (!next) {
                        flip = false;
                    }
                    next = true;

                } else {
                    if (next) {
                        flip = false;
                    }
                    next = false;
                }
                //
                oldTouchX = event.getX();
                oldTouchY = event.getY();

                this.invalidate();

                break;
            }

        }

        return true;
    }

    public void flip() {
       //
        if (flipping) {

           if (xTouchValue > width || xTouchValue < DEFAULT_FLIP_VALUE) {
                flipping = false;
                if (!flipping) {
                    //
                    if (next) {

                        swap2Page();

                    }
                    flip = false;
                    xTouchValue = DEFAULT_FLIP_VALUE;
                    yTouchValue = DEFAULT_FLIP_VALUE;
                    swap2View();

                }
                return;
            }
            if (next) {
                xTouchValue += FLIP_SPEED;
            } else {
                xTouchValue -= FLIP_SPEED;

            }
            this.invalidate();
            flippingHandler.sleep(mMoveDelay);
        }
    }

@Override
    protected void onDraw(Canvas canvas) {

        width = getWidth();
        height = getHeight();

        //
        if (flipping) {
            pointGenerate(xTouchValue, width, height);
        } else {
            // pointGenerateII(xTouchValue, yTouchValue, width, height);
            pointGenerate(xTouchValue, width, height);
        }
        // First Page render
        Paint paint = new Paint();
        canvas.drawColor(Color.GRAY);
        canvas.drawBitmap(visiblePage, 0, 0, paint);

        // Second Page Render
        Path pathX = pathOfTheMask();
        canvas.clipPath(pathX);
        canvas.drawBitmap(invisiblePage, 0, 0, paint);
        canvas.restore();
        // Flip Page render

        Path pathX2 = pathOfFlippedPaper();
        canvas.drawPath(pathX2, flipPagePaint);
        //
        pathX = null;
        pathX2 = null;
        paint = null;
    }

    //
    private Path pathOfTheMask() {
        Path path = new Path();
        path.moveTo(A.x, A.y);
        path.lineTo(B.x, B.y);
        path.lineTo(C.x, C.y);
        path.lineTo(D.x, D.y);
        path.lineTo(A.x, A.y);
        //
        return path;
    }
    //
    private Path pathOfFlippedPaper() {
        Path path = new Path();
        path.moveTo(A.x, A.y);
        path.lineTo(D.x, D.y);
        path.lineTo(E.x, E.y);
        path.lineTo(F.x, F.y);
        path.lineTo(A.x, A.y);
        return path;
    }
    //
    private void pointGenerate(float distance, int width, int height) {
        float xA = width - distance;
        float yA = height;
       
        float xD = 0;
        float yD = 0;
        //
        if (xA > width / 2) {
            xD = width;
            yD = height - (width - xA) * height / xA;
        } else {
            xD = 2 * xA;
            yD = 0;
        }       

        //
        double a = (height - yD) / (xD + distance - width);
        double alpha = Math.atan(a);
        double _cos = Math.cos(2 * alpha), _sin = Math.sin(2 * alpha);
        // E
        float xE = (float) (xD + _cos * (width - xD));
        float yE = (float) -(_sin * (width - xD));
        // F
        float xF = (float) (width - distance + _cos * distance);
        float yF = (float) (height - _sin * distance);
        //
        if (xA > width / 2) {
            xE = xD;
            yE = yD;
        }
        //
        A.x = xA;
        A.y = yA;
        D.x = xD;
        D.y = yD;
        E.x = xE;
        E.y = yE;
        F.x = xF;
        F.y = yF;
    }

    //
    float oldxF = 0, oldyF = 0;

    private void pointGenerateII(float xTouch, float yTouch, int width, int height) {
        //
        float yA = height;
        float xD = width;
        //

        //
        float xF = width - xTouch + 0.1f;
        float yF = height - yTouch + 0.1f;
        //
        if (A.x == 0) {
            xF = Math.min(xF, oldxF);
            yF = Math.max(yF, oldyF);
        }
        //
        float deltaX = width - xF;
        float deltaY = height - yF;
        //
        float BH = (float) (Math.sqrt(deltaX * deltaX + deltaY * deltaY) / 2);
        double tangAlpha = deltaY / deltaX;
        double alpha = Math.atan(tangAlpha);
        double _cos = Math.cos(alpha), _sin = Math.sin(alpha);
        //
        float xA = (float) (width - (BH / _cos));
        float yD = (float) (height - (BH / _sin));
        //

        xA = Math.max(0, xA);
        if (xA == 0) {
            oldxF = xF;
            oldyF = yF;
        }
        //
        float xE = xD;
        float yE = yD;
        if (yD < 0) {
            xD = width + (float) (tangAlpha * yD);
            yE = 0;
            xE = width + (float) (Math.tan(2 * alpha) * yD);

        }       

        //
        A.x = xA;
        A.y = yA;
        D.x = xD;
        D.y = Math.max(0, yD);
        E.x = xE;
        E.y = yE;
        F.x = xF;
        F.y = yF;
    }

    //
    private void swap2Page() {
        Bitmap temp = visiblePage;
        visiblePage = invisiblePage;
        invisiblePage = temp;
        temp = null;
    }
    private void swap2View(){
        View t = visibleView;
        visibleView = invisibleView;
        invisibleView = t;
        t=null;
        //
        visibleView.setVisibility(VISIBLE);
        this.setVisibility(GONE);
    }
}

9. Create the MainBook.java class

package com.example.curlpagetutorial;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainBook extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final MyLayout page = (MyLayout) findViewById(R.id.mainpage);
        View pre = findViewById(R.id.btn_pre);
        pre.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                page.pre();
               
            }
        });
        View next = findViewById(R.id.btn_next);
        next.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                page.next();
               
            }
        });
    }      
   
    @Override
    protected void onPause() {
        super.onPause();
        onStop();
    }
  
}

10. Create Point.java class

package com.example.curlpagetutorial;

public class Point {
    float x;
    float y;
    //
    public Point(float x, float y){
        this.x = x;
        this.y = y;
    }
   
}

11. Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.curlpagetutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="4" />

    <application
        android:configChanges="keyboardHidden|orientation"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <activity
            android:name=".MainBook"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Read more...

Friday, 5 September 2014

parseSdkContent failed Could not initialize class android.graphics.Typeface

Problem:
When open layout editor, eclipse is giving this error:
parseSdkContent failed
Could not initialize class android.graphics.Typeface
And when try to run project, it is giving this error :
An internal error occurred during: "Launching myapp".
java.lang.NullPointerException

Solution:
Delete the home/.android folder and everything is normal now.
In Windows you can find this folder in C:/Users/User/
Read more...

Tuesday, 2 September 2014

COCOS2D-X



How to setup Cocos2d-X on Windows-7


1.       Download all these files and save it either C:\ or D:\ drive on your system.

a)      Download the Cocos2d-X http://www.cocos2d-x.org/filedown/cocos2d-x-3.2.zip
b)      Download the updated ADT  http://developer.android.com/sdk/index.html#win-bundle
c)       Download the updated NDK for 32-bit or 64-bit http://dl.google.com/android/ndk/android-ndk32-r10-windows-x86.zip
d)      Download the Apache ANT  http://apache.claz.org//ant/binaries/apache-ant-1.9.4-bin.zip
e)      Download the updated Python https://www.python.org/ftp/python/2.7.8/python-2.7.8.msi

2.       Extract all the zip files in the same drive.
3.       Now install the “python-2.7.8.msi”
4.       Now open the command prompt and run these commands:
a)      C:\Users\d>cd C:\Developer\cocos2d-x-3.2_4
b)      C:\Developer\cocos2d-x-3.2_4\setup.py
(It create the setup for the cocos2d-x and asked to setup for the NDK_ROOT, SDK_ROOT, ANT_ROOT)
c)       C:\Developer\android-ndk-r10
d)      C:\Developer\adt-bundle-windows-x86-20140702\sdk
e)      C:\Developer\apache-ant-1.9.4\bin

5.       Now restart the computer or command prompt
6.       Open the command prompt and again run C:\Developer\cocos2d-x-3.2_4\setup.py to check all the Path has been set
7.       Now create the project with command
cocos.py new PROJECT_NAME –p PACKAGE_NAME –l Language (example: cocos.py new MyApp –p com.example.MyApp –l cpp)
8.       Now open the project from where is it saved (my case: it is saved in C:\Developer\cocos2d-x-3.2_4\cocos2d-x-3.2\MyApp) and drag-n-drop it to the command prompt
9.       Now open the proj.android from created project C:\Developer\cocos2d-x-3.2_4\cocos2d-x-3.2\MyApp\proj.android
10.   Now run the project with the command build_native.py
(This will compile the cocos2d-x and our project)
11.   Now open the eclipse.exe
12.   Import the project from Android Existing Projects proj.android and libcocos2dx  (my case: it is saved in C:\Developer\cocos2d-x-3.2_4\cocos2d-x-3.2\MyApp)
13.   Now RUN the project


You may get the Error:
make.exe: [obj/local/armeabi/objs-debug/cocos2dx_static/3d/CCBundleReader.o] Error 1
make.exe:
Waiting for unfinished jobs....
make.exe: Leaving directory `D:/cocos2d-x-3.2/tests/cpp-tests/proj.android'
Build dynamic library for project [ D:\cocos2d-x-3.2\build..\tests/cpp-tests/proj.android ] fails!

Solution:
The cause is that it's declared as "long int" in the header and "ssize_t" in the definition. I'm sure it will be patched soon officially, but locally you can just change "ssize_t BundleReader::tell()" to "long int BundleReader::tell()" and it should compile and link fine.
Read more...

Friday, 8 August 2014

ListViewDemo with image

Here we are going to create ListView with Images.
First we have to create Project named as ListViewDemo
1. Create a new Project, ListViewDemo
2. Open the activity_main.xml
3. We have add the ListView in it.
activity.main.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.listviewdemo.MainActivity" >

    <TextView
        android:id="@+id/textYear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/my_car"
        android:textSize="20sp"
        android:textStyle="bold" />

    <ListView
        android:id="@+id/carsListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textYear"
        android:layout_below="@+id/textYear" >

    </ListView>

</RelativeLayout>

4. We have to create a class where we want the objects to be displayed. Here I'm taking an example to show the Cars with details making, year, icon and condition
5. Create a class Car.java
package com.example.listviewdemo;

public class Car {
    private String make;
    private int year;
    private int iconId;
    private String condition;   
   
    public Car(String make, int year, int iconId, String condition) {
        super();
        this.make = make;
        this.year = year;
        this.iconId = iconId;
        this.condition = condition;
    }
    public String getMake() {
        return make;
    }
    public int getYear() {
        return year;
    }
    public int getIconId() {
        return iconId;
    }
    public String getCondition() {
        return condition;
    }
   
}
6. Now we have to create a view to display the list item
7. Create a xml item_view.xml
<ImageView
        android:id="@+id/item_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:maxHeight="80dp"
        android:maxWidth="80dp"
        android:src="@drawable/audi" />
<TextView
        android:id="@+id/item_textMake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/item_textYear"
        android:layout_alignParentTop="true"
        android:text="Make Shown Here"
        android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
        android:id="@+id/item_textYear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/item_icon"
        android:layout_toRightOf="@+id/item_icon"
        android:text="2000"
        android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
        android:id="@+id/item_textCondition"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/item_icon"
        android:layout_alignParentRight="true"
        android:text="Condition Shown Here"
        android:textAppearance="?android:attr/textAppearanceMedium" />

8. Now we have to create a list in MainActivity.java class and call all the list item to show the cars
9. MainActivity.java
package com.example.listviewdemo;

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

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    private List<Car> myCars = new ArrayList<Car>();

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

        populateCarList();
        populateListView();
        registerClickCallBack();
    }
    private void populateCarList() {
        // TODO Auto-generated method stub
        myCars.add(new Car("Audi", 1950, R.drawable.audi, "needing work"));
        myCars.add(new Car("Farari", 2005, R.drawable.black_farari, "nice color"));
        myCars.add(new Car("BMW", 2010, R.drawable.bmw, "latest BMW"));
        myCars.add(new Car("Chervolet", 2012, R.drawable.chervolet, "my favorite"));
        myCars.add(new Car("Italia", 2014, R.drawable.italia, "latest car"));   
    }
    private void populateListView() {
        ArrayAdapter<Car> adapter = new MyListAdapter();
        ListView list = (ListView) findViewById(R.id.carsListView);
        list.setAdapter(adapter);           
    }

    private void registerClickCallBack() {
        ListView list = (ListView)findViewById(R.id.carsListView);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View viewClicked,
                    int position, long id) {

                Car clickedCar = myCars.get(position);
                String message = "You clicked position " + position
                        + " which is car make " + clickedCar.getMake();
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
            }

        });

    }
    private class MyListAdapter extends ArrayAdapter<Car> {

        public MyListAdapter() {
            super(getApplicationContext(), R.layout.item_view, myCars);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Make sure we have the View to work with (may have been given null)
            View itemView = convertView;
            if(itemView == null){
                itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
            }
            //Find the car to work with
            Car currentCar = myCars.get(position);

            //Fill the View
            ImageView imageVeiw = (ImageView)itemView.findViewById(R.id.item_icon);
            imageVeiw.setImageResource(currentCar.getIconId());

            //Make:
            TextView makeText = (TextView)itemView.findViewById(R.id.item_textMake);
            makeText.setText(currentCar.getMake());

            //Year:
            TextView yearText = (TextView)itemView.findViewById(R.id.item_textYear);
            yearText.setText(" " + currentCar.getYear());

            //Condition:
            TextView conditionText = (TextView)itemView.findViewById(R.id.item_textCondition);
            conditionText.setText(currentCar.getCondition());

            return itemView;
        }

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
Read more...

Tuesday, 29 July 2014

DatabaseDemo - Example

1. Create a project : DatabaseDemo
2. Do some changes in activity_main.xml
3. Create EditText and Button
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.databasedemo.MainActivity" >

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="Enter Name" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="126dp"
        android:layout_marginRight="34dp"
        android:text="Load Data" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/load"
        android:layout_alignBottom="@+id/load"
        android:layout_alignLeft="@+id/email"
        android:text="Save Data" />

    <EditText
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/load"
        android:layout_below="@+id/name"
        android:layout_marginTop="44dp"
        android:ems="10"
        android:hint="Enter email id" />

</RelativeLayout>

4. Add these EditText and Button description in MainActivity.java class
package com.example.databasedemo;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
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 ActionBarActivity {
   
    EditText name, email;
    Button save, load;
    DataHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        name = (EditText) findViewById(R.id.name);
        email = (EditText) findViewById(R.id.email);
        save = (Button) findViewById(R.id.save);
        load = (Button) findViewById(R.id.load);
       
        save.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                String getName = name.getText().toString();
                String getEmail = email.getText().toString();
               
                handler = new DataHandler(getBaseContext());
                handler.open();
                long id = handler.insertData(getName, getEmail);
                Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show();
                handler.close();
            }
        });
       
        load.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                String getName, getEmail;
                getName = "";
                getEmail = "";
               
                handler = new DataHandler(getBaseContext());
                handler.open();
                Cursor C = handler.returnData();
                if(C.moveToFirst()){
                    do{
                        getName = C.getString(0);
                        getEmail = C.getString(1);
                   
                    } while(C.moveToNext());
                }
                handler.close();
                Toast.makeText(getBaseContext(), "Name: " + getName + " and Email: " + getEmail, Toast.LENGTH_LONG).show();
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

5. Create another java class DataHandler.java as required to handle the data
package com.example.databasedemo;

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

public class DataHandler {
    public static final String NAME = "name";
    public static final String EMAIL = "email";
    public static final String TABLE_NAME = "mytable";
    public static final String DATA_BASE_NAME = "mydatabase";
    public static final int DATABASE_VERSION = 1;
    public static final String CREATE_TABLE = "create table mytable (name text not null, email text not null)";
   
    DataBaseHelper dbhelper;
    Context context;
    SQLiteDatabase db;
   
    public DataHandler (Context context){
        this.context = context;
        dbhelper = new DataBaseHelper(context);
    }
    private static class DataBaseHelper extends SQLiteOpenHelper{

        public DataBaseHelper(Context context) {
            super(context, DATA_BASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(CREATE_TABLE);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
       
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS mytable");
            onCreate(db);
           
        }
       
    }
   
    public DataHandler open(){
        db = dbhelper.getWritableDatabase();
        return this;
    }
    public void close(){
        dbhelper.close();
    }
   
    public long insertData(String name, String email){
        ContentValues content = new ContentValues();
        content.put(NAME, name);
        content.put(EMAIL, email);
        return db.insertOrThrow(TABLE_NAME, null, content);
    }
   
    public Cursor returnData(){
        return db.query(TABLE_NAME, new String[] {NAME, EMAIL}, null, null, null, null, null);
    }
   
}
Read more...

Wednesday, 23 July 2014

Android: SeekBar Example

1. Create Project named SeekBarExample
2. Create main.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" >

    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_margin="10dp"
        android:progressDrawable="@drawable/styled_progress"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:thumb="@drawable/thumbler_small"
         android:indeterminate="false" />

</RelativeLayout>

3. Create drawable folder in res
4. Create styled_progress in drawable folder
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+android:id/SecondaryProgress"
        android:drawable="@drawable/progress_cyan"/>
    <item
        android:id="@+android:id/progress"
        android:drawable="@drawable/progress_red"/>

</layer-list>

5. Create MainActivity.java
package com.example.seekbarexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity {
    SeekBar mybar;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mybar = (SeekBar) findViewById(R.id.seekBar1);
       
        mybar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
           
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
               
                //add here your implementation
            }
           
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

                //add here your implementation
            }
           
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {

                //add here your implementation
            }
        });
    }


}
Read more...