Saturday, 19 July 2014

how to create database sqlite on android

MainActivity.java

package com.sqlexample;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

    public static ListView listView;
    private Button btnsave, btnshow;
    DataBaseHelper myDbHelper;
    private EditText fname, lname, age;
    public static Context con;
    public static String Mfname, Mlname, Mage;
   
    public static void Insert_Success_responces(Context myContext) {
       
    }
    static ArrayList<Datalist> arr_ = new ArrayList<Datalist>();
    public static void select_responces(Context conn, ArrayList<Datalist> data) {
        con = conn;
        arr_ = data;

        info_Baseadepter adepter = new info_Baseadepter(conn, data);
        listView.setAdapter(adepter);

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

        btnsave = (Button) findViewById(R.id.button1);
        btnshow = (Button) findViewById(R.id.button2);
        listView=(ListView)findViewById(R.id.listView1);

        fname = (EditText) findViewById(R.id.editText1);
        lname = (EditText) findViewById(R.id.editText2);
        age = (EditText) findViewById(R.id.editText3);
       
        btnsave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Mfname=fname.getText().toString();
                Mlname=lname.getText().toString();
                Mage=age.getText().toString();
               
                if(!Mfname.equals("")&&!Mlname.equals("")&&!Mage.equals("")){
                   
                    myDbHelper = new DataBaseHelper(MainActivity.this);
                    try {
                        myDbHelper.createDataBase();
                    } catch (IOException ioe) {
                        throw new Error("Unable to create database");
                    }
                    try {
                        myDbHelper.openDataBase();
                    } catch (SQLException sqle) {
                        throw sqle;
                    }

                    myDbHelper.Insert_data();
                   
                }else{
                   
                    Toast.makeText(MainActivity.this,"Enter value", Toast.LENGTH_SHORT).show();
                }
               
            }
        });
        btnshow.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
               
                myDbHelper = new DataBaseHelper(MainActivity.this);
                try {
                    myDbHelper.createDataBase();
                } catch (IOException ioe) {
                    throw new Error("Unable to create database");
                }
                try {
                    myDbHelper.openDataBase();
                } catch (SQLException sqle) {
                    throw sqle;
                }

                myDbHelper.Select_Data();
            }
        });
    }

}

DataBaseHelper.java

package com.sqlexample;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.app.Activity;
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.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.sqlexample/databases/";
    private static String DB_NAME = "personalinformation.db";
    public SQLiteDatabase myDataBase;

    public ArrayList<Datalist> arr_info = null;

    private Context myContext;
    public Cursor allrow;
    Activity ll;
    int id;

    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
           
        } else {
           
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
        } catch (SQLiteException e) {
           
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    private void copyDataBase() throws IOException {
       
        InputStream myInput = myContext.getAssets().open(DB_NAME);
       
        String outFileName = DB_PATH + DB_NAME;
       
        OutputStream myOutput = new FileOutputStream(outFileName);
       
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
       
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public void openDataBase() throws SQLException {
       
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {

        if (myDataBase != null)
            myDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }

    public void Insert_data() {

        try {

            ContentValues values = new ContentValues();

            values.put("fname", MainActivity.Mfname);
            values.put("lname", MainActivity.Mlname);
            values.put("age", MainActivity.Mage);
           

            myDataBase.insert("personainfo", null, values);

            MainActivity.Insert_Success_responces(myContext);

        } catch (Exception e) {

        }
    }

    @SuppressWarnings("deprecation")
    public void Select_Data() {

        arr_info = null;

        try {

            String[] Resultcol = new String[] { "fname", "lname", "age"};
            allrow = myDataBase.query("personainfo", Resultcol, null, null,null, null, null);

            int fname = allrow.getColumnIndex("fname");
            int lname = allrow.getColumnIndex("lname");
            int age = allrow.getColumnIndex("age");

            allrow.moveToFirst();
           
            for (int i = 0; i < allrow.getCount(); i++) {

                if (arr_info == null) {
                    arr_info = new ArrayList<Datalist>();

                }

                Datalist data = new Datalist();

                data.Fname = allrow.getString(fname);
                data.Lname = allrow.getString(lname);
                data.Age = allrow.getString(age);
               
                arr_info.add(data);

                allrow.moveToNext();

                ll = new Activity();

                ll.startManagingCursor(allrow);

            }

            MainActivity.select_responces(myContext, arr_info);

        } catch (Exception e) {

           
        }

    }
}

Datalist.java

package com.sqlexample;

public class Datalist {

    String Fname,Lname,Age;
}

info_Baseadepter.java

package com.sqlexample;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class info_Baseadepter extends BaseAdapter {

    LayoutInflater mInflater;
    public Activity activity;
    ArrayList<Datalist> data;
    public Context mContext;
   
    info_Baseadepter(Context activity, ArrayList<Datalist> data) {

        mContext = activity;
        this.activity = (Activity) activity;
        this.data = data;

        mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       

    }

    public int getCount() {
        try {
            return data.size();

        } catch (Exception e) {
            // TODO: handle exception
        }
        return 0;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class getitemutils {

        public TextView tv_fnmae, tv_lname,tv_age;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        final getitemutils item = new getitemutils();
        vi = mInflater.inflate(R.layout.listitem, null);

        item.tv_fnmae = (TextView) vi.findViewById(R.id.textView1);
        item.tv_lname = (TextView) vi.findViewById(R.id.textView2);
        item.tv_age =(TextView) vi.findViewById(R.id.textView3);

       

        item.tv_fnmae.setText(data.get(position).Fname);
        item.tv_lname.setText(data.get(position).Lname);
        item.tv_age.setText(data.get(position).Age);

        return vi;
    }

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/container2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal" >

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

        <EditText
            android:id="@+id/editText1"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/container3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/container2"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Last Name:" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/container4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/container3"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Age:            " />

        <EditText
            android:id="@+id/editText3"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/container5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/container4"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save Data" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show Data" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/container6"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/container5"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp" >

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" >
        </ListView>

    </RelativeLayout>

</RelativeLayout>

listitem.xml

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

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal" >

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

        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>

</RelativeLayout>


Monday, 7 July 2014

how to create a webview in android example

MainActivity.java

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity
{
   
    private WebView webView;
     @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
       
        webView = (WebView) findViewById(R.id.webView1);
    
            startWebView("your url");       
    }
   
    private void startWebView(String url)
    {
       
        webView.setWebViewClient(new WebViewClient()
        {     
         ProgressDialog progressDialog;
         
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {             
                view.loadUrl(url);
                return true;
            }
       
            public void onLoadResource (WebView view, String url)
            {
                if (progressDialog == null)
                {
                    progressDialog = new ProgressDialog(MainActivity.this);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
            }
            public void onPageFinished(WebView view, String url)
            {
                try
                {
                if (progressDialog.isShowing())
                {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                }catch(Exception exception)
                {
                    exception.printStackTrace();
                }
            }
            
        });
       
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setWebChromeClient(new WebChromeClient());
       
        webView.loadUrl(url);
         
    }
  }

AndroidManifest.xml

   <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

activity_main.xml

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

    <RelativeLayout
        android:id="@+id/main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true" >

        <WebView
            android:id="@+id/webView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="20dp" />
    </RelativeLayout>

</RelativeLayout>

Tuesday, 1 July 2014

how to create action bar in android example

activity_main.xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ViewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

fragment_design.xml

<?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"
    android:background="#000000" >
    
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Design"
        android:textSize="20dp"
        android:layout_centerInParent="true"/>
   </RelativeLayout>

fragment_home.xml

<?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"
    android:background="#FFFFFF" >
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Home"
        android:textSize="20dp"
        android:layout_centerInParent="true"/>
</RelativeLayout>

fragment_other.xml

<?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"
    android:background="#FFFFFF">
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Other"
        android:textSize="20dp"
        android:layout_centerInParent="true"/>
</RelativeLayout>

TabsPagerAdapter.java

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

        switch (index) {
        case 0:
            return new DesignFragment();
        case 1:
            return new HomeFragment();
        case 2:
            return new OtherFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }

}

MainActivity.java

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    private String[] tabs = { "design", "home", "other" };

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

        viewPager = (ViewPager) findViewById(R.id.ViewPager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);      

        for (String tab_name : tabs)
{
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
       
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
       
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

}

fragment_design.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class fragment_design extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_design, container, false);
        
        return rootView;
    }
}

fragment_home.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class fragment_home extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        
        return rootView;
    }
}



fragment_Other.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class fragment_Other extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_Other, container, false);
        
        return rootView;
    }

}

Monday, 9 June 2014

how to create simple torch light in android

MainActivity.java

package com.simpleflashlight;

import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    public final static String TAG = "simple torch";
    Camera cam;
    ToggleButton mTorch;
    Parameters camParams;
    private Context context;
    AlertDialog.Builder builder;
    AlertDialog alertDialog;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private final int FLASH_NOT_SUPPORTED = 0;
    private final int FLASH_TORCH_NOT_SUPPORTED = 1;
   
      @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = MainActivity.this;
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)){
            mTorch = (ToggleButton) findViewById(R.id.toggleButton);
            mTorch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Log.d(TAG, "onCheckedChanged");
                    try{
                        if (cam == null){
                            cam = Camera.open();
                        }
                        camParams = cam.getParameters();
                        List<String> flashModes = camParams.getSupportedFlashModes();
                        if (isChecked){
                            if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
                                camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
                            }else{
                                showDialog(MainActivity.this, FLASH_TORCH_NOT_SUPPORTED);
                            }
                        } else {
                            camParams.setFlashMode(Parameters.FLASH_MODE_OFF);
                        }
                        cam.setParameters(camParams);
                        cam.startPreview();
                    }catch (Exception e) {
                        Log.d(TAG, "Caught " + e);
                        Toast.makeText(MainActivity.this, "Camera/Torch failure: " + e, Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                        if (cam != null) {
                            cam.stopPreview();
                            cam.release();
                        }
                    }
                }
            });
            surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
            surfaceHolder = surfaceView.getHolder();
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            surfaceHolder.addCallback(this);
        } else {
            showDialog(MainActivity.this, FLASH_NOT_SUPPORTED);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(cam == null){
            cam = Camera.open();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        cam.release();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(cam != null){
            cam.release();
        }
    }

    public void showDialog (Context context, int dialogId) {
        switch(dialogId){
        case FLASH_NOT_SUPPORTED:
            builder = new AlertDialog.Builder(context);
            builder.setMessage("Sorry, Your phone does not support Camera Flash")
            .setCancelable(false)
            .setNeutralButton("Close", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alertDialog = builder.create();
            alertDialog.show();
            break;
        case FLASH_TORCH_NOT_SUPPORTED:
            builder = new AlertDialog.Builder(context);
            builder.setMessage("Sorry, Your camera flash does not support torch feature")
            .setCancelable(false)
            .setNeutralButton("Close", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alertDialog = builder.create();
            alertDialog.show();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
     
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {

            cam.setPreviewDisplay(holder);

        } catch (IOException e) {
         

        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
     
    }   
}

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="20dip"
        android:text="@string/app_title"
        android:textSize="25sp" />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dip"
        android:text="@string/toggleButtonLabe" />

    <SurfaceView
        android:id="@+id/SurfaceView"
        android:layout_width="1dp"
        android:layout_height="1dp" />

</LinearLayout>

AndroidManifest.xml

 <uses-feature
        android:name="android.hardware.Camera"
        android:required="true" >
    </uses-feature>
    <uses-feature
        android:name="android.hardware.camera.FLASHLIGHT"
        android:required="true" >
    </uses-feature>

    <uses-permission android:name="android.permission.CAMERA" >
    </uses-permission>
   

how to use random function in android

Random function

Random rand = new Random();
int rnd = rand.nextInt(16);
System.out.println("~~~~~~"+rnd);

Wednesday, 4 June 2014

how to get gallery image in android


private void selectImage() {
        final CharSequence[] items = { "Take Photo", "Choose from gallery",
                "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Photo");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment
                            .getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else if (items[item].equals("Choose from gallery")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            SELECT_FILE);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                File f = new File(Environment.getExternalStorageDirectory()
                        .toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bm;
                    BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

                    bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            btmapOptions);

                    image.setImageBitmap(bm);

                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream fOut = null;
                    File file = new File(path, String.valueOf(System
                            .currentTimeMillis()) + ".jpg");
                    try {
                        fOut = new FileOutputStream(file);
                        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                        fOut.flush();
                        fOut.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == SELECT_FILE) {
                Uri selectedImageUri = data.getData();

                String tempPath = getPath(selectedImageUri, MainActivity.this);
                Bitmap bm;
                BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
                image.setImageBitmap(bm);
            }
        }
    }

public String getPath(Uri uri, Activity activity) {
        String[] projection = { MediaColumns.DATA };
        Cursor cursor = activity
                .managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

how to save image using preferences in android

Bitmap bitmap= BitmapFactory.decodeStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
byte[] b = baos.toByteArray();

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
textEncode.setText(encodedImage);

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();

//and then, when retrieving, convert it back into bitmap:

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");

if( !previouslyEncodedImage.equalsIgnoreCase("") ){
    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
    image.setImageBitmap(bitmap);
}