Saturday, 21 June 2014

[KEY : FRAGMENT, ADDING FRAGMENT, ANDROID FRAGMENT, CREATING FRAGMENT]

FRAGMENT, ANDROID

Android activity is simple and best way to provide interface to user. Fragment are very similar to activity. But it will be much better if we call it small piece of activity. So an activity can have multiple fragments

Creating fragment in android

  1. Create simple class like "MyFirstFragment.java".
  2. Extend Fragment class into "MyFirstFragment.java".
  3. Fragement is almost ready. Now add required methods into it, Specifically you require two methods onCreateView() and onAttach() as mentioned below :

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return super.onCreateView(inflater, container, savedInstanceState); }


    @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); }

  4. Inflate your own xml file and return it as view. So finally onCreateView() will look like as below:

    @Override
     public View onCreateView(LayoutInflater inflater, 
       ViewGroup container, Bundle savedInstanceState) {
      
      View localView = inflater.inflate(R.layout.your_xml.xml, 
        container, false);
      
      return localView; //super.onCreateView(inflater, container, savedInstanceState);
     }
    

  5. Create global object of your parent activity

    YourActivity yourActivityObject;

  6. Initialize yourActivityObject in onAttach method so it will look as below:

     @Override
     public void onAttach(Activity activity) {
    
      yourActivityObject = (YourActivity)activity;
    
      super.onAttach(activity);
     }
    

Start / Call new fragment from fragment

 Fragment yourSecondFragment = new YourSecondFragment();

 FragmentManager fm = yourActivityObject.getSupportFragmentManager();

 //yourSecondFragment.setArguments(Bundle) // to pass argument to next fragment.

 fm.beginTransaction().replace(R.id.parent_activity_frame_layout, 
 yourSecondFragment).addToBackStack("myfragmentstring").commit();

 // addToBackStack method before commit is used to implement back button functionality later.  

Adding back button functionality to fragment

In parent activity add onBackPressed() method and paste the following code

int f = getSupportFragmentManager().getBackStackEntryCount();
  Log.v(tag, "onBackPressed ["+f+"]");
  if (f <= 1)
   this.finish();
  else {
   getSupportFragmentManager().popBackStackImmediate();
  }


Tuesday, 14 January 2014

[KEY : SIGNED, UNSIGNED, SINGED AND UNSIGNED APK]

Why signed and unsigned apk.

First of all be clear about signed and unsigned apk. Signed apks keeps its digital signature certificate with it, while unsigned does not. The Android system requires that all installed applications be digitally signed with a certificate whose private key is held by the application's developer. The Android system uses the certificate as a means of identifying the author of an application and establishing trust relationships between applications.

As I guess unsigned apk is for facilitate another user to sign apk with its own key.
Remember the following points.

  • All applications must be signed. The system will not install an application on an emulator or a device if it is not signed.
  • To test and debug your application, the build tools sign your application with a special debug key that is created by the Android SDK build tools.
  • When you are ready to release your application for end-users, you must sign it with a suitable private key. You cannot publish an application that is signed with the debug key generated by the SDK tools.
  • You can use self-signed certificates to sign your applications. No certificate authority is needed.

More detail here

Signing the unsigned apk.
  1. Make sure you have unsigned apk or create it (Open menifest file-> click on Export on Unsigned apk).
  2. Keep your unsigned apk in separate folder.
  3. Find the path of you key.
  4. Open Command Prompt.
  5. jarsigner -verbose -keystore path/of/your/key path/of/your/unsignedApk alias_name_of_key
  6. Key will ask password
  7. Done

Wednesday, 10 July 2013

ListView inside scroll view android

  1. Create a class named "VerticalScroller.java"
  2. Copy the following code and paste into class.
    package com.example.utils;
    
    import android.content.Context;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.widget.ScrollView;
    
    public class VerticalScroller extends ScrollView{
    
        public VerticalScroller(Context context) {
            super(context);
        }
    
         public VerticalScroller(Context context, AttributeSet attrs) {
                super(context, attrs);
            }
    
            public VerticalScroller(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
            }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            final int action = ev.getAction();
            switch (action)
            {
                case MotionEvent.ACTION_DOWN:
                        Log.i("VerticalScroller", "onInterceptTouchEvent: DOWN super false" );
                        super.onTouchEvent(ev);
                        break;
    
                case MotionEvent.ACTION_MOVE:
                        return false; // redirect MotionEvents to ourself
    
                case MotionEvent.ACTION_CANCEL:
                        Log.i("VerticalScroller", "onInterceptTouchEvent: CANCEL super false" );
                        super.onTouchEvent(ev);
                        break;
    
                case MotionEvent.ACTION_UP:
                        Log.i("VerticalScroller", "onInterceptTouchEvent: UP super false" );
                        return false;
    
                default: Log.i("VerticalScroller", "onInterceptTouchEvent: " + action ); break;
            }
    
            return false;
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            super.onTouchEvent(ev);
            Log.i("VerticalScroller", "onTouchEvent. action: " + ev.getAction() );
             return true;
        }
    }
  3. Go to xml file replace your <scrollview></scrollview> with <com.example.utils.VerticalScroller></com.example.utils.VerticalScroller>
  4. Done

Thursday, 2 May 2013

How to call database onUpgrade method Android

just open your SQLiteHelper class and change the DATABASE_VERSION. (increase its value from previous one)
Run your app again.

Monday, 15 October 2012

Create your own camera app and take images android

  1. Create a SurfaceView as follow (it will interact with camera)

    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import android.content.Context;
    import android.hardware.Camera;
    import android.hardware.Camera.PreviewCallback;
    import android.util.Log;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
    
    public class CameraView extends SurfaceView implements 
    SurfaceHolder.Callback
    {
     SurfaceHolder holder;
     Camera camera;
     public CameraView(Context context) 
     {
      super(context);
      holder=getHolder();
      holder.addCallback(this);
      holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
     }
     public void surfaceChanged(SurfaceHolder holder, int format,
       int width,int height) 
     {
    
      Camera.Parameters parameters=camera.getParameters();
      parameters.set("flash-mode", "on");
      camera.setParameters(parameters);
      camera.startPreview();
     }
     public void surfaceCreated(SurfaceHolder holder) 
     {
      try 
      {
       camera=Camera.open();
       camera.setPreviewDisplay(holder);
      } catch (IOException e) 
      {
       e.printStackTrace();
      }
     }
     public void surfaceDestroyed(SurfaceHolder holder) 
     {
      camera.stopPreview();
      camera.setPreviewCallback(null);
      camera.release();
      camera=null;
     }
    }
    

  2. Now Create front interface for camera Activity

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import android.app.Activity;
    import android.content.Intent;
    import android.hardware.Camera;
    import android.hardware.Camera.PictureCallback;
    import android.hardware.Camera.ShutterCallback;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.Window;
    import android.widget.*;
    
    public class CameraFront extends Activity
    {
     CameraView camview;
     FrameLayout frame;
     Button Click,Close;
     static String filename; 
     public void onCreate(Bundle bundle)
     {
      super.onCreate(bundle);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      setContentView(R.layout.camframe);
      Click=(Button)findViewById(R.id.buttonClick); 
      Click.setOnClickListener(new Button.OnClickListener(){
    
      public void onClick(View v) {
        
       camview.camera.takePicture(shutterCallback, 
         rawCallback, jpegCallback);
    
       }});
      Close=(Button)findViewById(R.id.buttonClose);
      Close.setOnClickListener(new Button.OnClickListener(){
    
      public void onClick(View v) {
      
       CameraFront.this.finish();
    
       }});
      camview=new CameraView(this);
      frame=(FrameLayout)findViewById(R.id.preview);
      frame.addView(camview);
     }
     ShutterCallback shutterCallback = new ShutterCallback() {
      public void onShutter() {
    
      }
     };
     PictureCallback rawCallback = new PictureCallback() {
      public void onPictureTaken(byte[] data, Camera camera) {
    
      }
     };
     PictureCallback jpegCallback = new PictureCallback() {
      public void onPictureTaken(byte[] data, Camera camera) {
       FileOutputStream outStream = null;
      try {
    
       long d=System.currentTimeMillis();
       filename="/sdcard/"+d+".jpg";
    
       outStream = new FileOutputStream(
         String.format("/sdcard/%d.jpg", d));
       outStream.write(data);
       outStream.close();
    
      } catch (FileNotFoundException e) {
       e.printStackTrace();
      } catch (IOException e) {
       e.printStackTrace();
      } finally {
    
      }
      CameraFront.this.finish();
      //ImageViewer to Show Image taken from camera
      Intent intent=new Intent(CameraFront.this,ImageViewer.class);
      intent.putExtra("imagefile", filename);
      startActivity(intent);
     }
    };
    }
    
    

  3. 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" >
    
        <FrameLayout
            android:id="@+id/preview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" >
        </FrameLayout>
    
        <LinearLayout
           xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="horizontal"
            android:weightSum="1.0" >
    
            <Button
                android:id="@+id/buttonClick"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_weight="0.5"
                android:text="Click" >
            </Button>
    
            <Button
               android:id="@+id/buttonClose"
               android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_weight="0.5"
               android:text="Close" >
            </Button>
        </LinearLayout>
    
    </LinearLayout>
    
    

  4. It will store image in sdcard

Sunday, 14 October 2012

Install apk from assets android

  1. Copy/put your apk file in assets folder of your project
  2. Set onClick event of button to install apk. Copy and paste following code
  3. ===============================================
    public void loadMyApk()
    {
    copyAssets(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/" + "BS.apk")), "application/vnd.android.package-archive"); startActivityForResult(intent, 4);
    }
    ===============================================
    private void copyAssets()
    {
    AssetManager assetManager = getAssets(); String[] files = null; try { files = assetManager.list(""); } catch (IOException e) { Log.e("tag", e.getMessage()); } for(String filename : files) { InputStream in = null; OutputStream out = null; try { //fileone=filename; in = assetManager.open(filename); out = new FileOutputStream("/sdcard/" + filename); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch(Exception e) { Log.e("tag", e.getMessage()); } }
    }
    ===============================================
    private void copyFile(InputStream in, OutputStream out) throws IOException
    {
    byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); }
    }

    ===============================================
  4. Its done
In the above process I have copied apk file from assets folder to sdcard and installing from sdcard. If you want to delete from sdcard you can call delete() method for file

Wednesday, 29 August 2012

how to connect to internet on pc using android phone

[KEY : Tethering, Phone Internet, PC Internet]

Tethering mobile internet into PC / Laptop

Assuming that internet is activated on your phone
  1. Connect your android phone to pc
  2. Go to Settings
  3. Wireless and Network settings
  4. Tethering and portable hotspot
  5. USB tethering
Now at your pc
  1. Select "My Network Places"
  2. View Network Connections
here you will have your android phone as one more connection