Friday 19 August 2016

ALL TextView's typefaces, includes action bar and other standard components, but EditText's password font won't be overriden.




Reference URL : https://gist.github.com/artem-zinnatullin/7749076?signup=true



public class MyApp extends Application {
@Override
public void onCreate() {
TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); // font from assets: "assets/fonts/Roboto-Regular.ttf
}
}






<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyAppTheme" parent="@android:style/Theme.Holo.Light">
<!-- you should set typeface which you want to override with TypefaceUtil -->
<item name="android:typeface">serif</item>
</style>
</resources>




import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.lang.reflect.Field;
public class TypefaceUtil {
/**
* Using reflection to override default typeface
* NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
* @param context to work with assets
* @param defaultFontNameToOverride for example "monospace"
* @param customFontFileNameInAssets file name of the font from assets
*/
public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
try {
final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);
final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
defaultFontTypefaceField.setAccessible(true);
defaultFontTypefaceField.set(null, customFontTypeface);
} catch (Exception e) {
Log.e("Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
}
}
}

Easiest way to hide keyboard in fragment or Activity


Soluton : 1


    //hide keyboard
    public static void hideKeyboard(Context ctx) {
        InputMethodManager inputManager = (InputMethodManager) ctx
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        // check if no view has focus:
        View v = ((Activity) ctx).getCurrentFocus();
        if (v == null)
            return;

        inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }



Solution : 2


        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
   





Solution : 3 for Table layout (TAB selected based hid the keyboard)

http://stackoverflow.com/questions/10297376/how-do-i-hide-the-soft-keyboard-when-changing-tabs








Friday 12 August 2016

Take Backup Sqlite Database from device programmatically


package com.example.sample;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.truetech.nec.util.NECSharedPref;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

public class SplashScreen extends BaseActivity {


    // Splash screen timer    private static int SPLASH_TIME_OUT = 3000;

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




    
          //fucntion for taking sqlite database backup programmatically
          backupDB();

    }


 //fucntion for taking sqlite database backup programmatically
private void backupDB() {

    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "/data/data/" + getPackageName() + "/databases/database.db";
            String backupDBPath = "databasename.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {

    }
}

Monday 2 May 2016

Custom Dialog in Android Using Dialog Interface


Custom Dialog Popup Window using Android with Help of Dialog Interface


Main Activity onCreate()

To write the code inside the onclick event.


   btn_next = (Button)findViewById(R.id.btn_next);
        btn_next.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {
                CustomizeDialog customDiglog= new CustomizeDialog(context);
                customDiglog.setTitle("Hello Welocme");
                customDiglog.setMessage("Hello Welocme");
                customDiglog.show();
            }
        });
    }
 
Custome Dialog Class
 
 
 import android.app.Dialog;
import android.content.Context;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
/** Class Must extends with Dialog */
 /** 
Implement onClickListener to dismiss dialog when OK Button is pressed */
 public class CustomizeDialog extends Dialog implements OnClickListener {
    Button okButton;
    Context mContext;
    TextView mTitle = null;
    TextView mMessage = null;
    View v = null;
    public CustomizeDialog(Context context) {
        super(context);
        mContext = context;
        /** 'Window.FEATURE_NO_TITLE' - Used to hide the mTitle */         
         requestWindowFeature(Window.FEATURE_NO_TITLE);
        /** Design the dialog in main.xml file */ 
         setContentView(R.layout.dialog_msg);
        v = getWindow().getDecorView();
        v.setBackgroundResource(android.R.color.transparent);
        mTitle = (TextView) findViewById(R.id.dialogTitle);
        mMessage = (TextView) findViewById(R.id.dialogMessage);
        okButton = (Button) findViewById(R.id.OkButton);
        okButton.setOnClickListener(this);
    }
    @Override    public void onClick(View v) {
        /** When OK Button is clicked, dismiss the dialog */        if (v == okButton)
            dismiss();
    }
    @Override    public void setTitle(CharSequence title) {
        super.setTitle(title);
        mTitle.setText(title);
    }
    @Override    public void setTitle(int titleId) {
        super.setTitle(titleId);
        mTitle.setText(mContext.getResources().getString(titleId));
    }
    /**     * Set the message text for this dialog's window.     * 
 * @param message     *      - The new message to display in the title.     */ 
 public void setMessage(CharSequence message) {
        mMessage.setText(message);
        mMessage.setMovementMethod(ScrollingMovementMethod.getInstance());
    }
    /**     * Set the message text for this dialog's window. 
The text is retrieved from the resources with the supplied     * identifier. 
 *     * @param messageId     *      - the message's text resource identifier <br>
     * @see <b>Note : if resourceID wrong application may get crash.</b><br>
     *   Exception has not handle.     */    public void setMessage(int messageId) {
        mMessage.setText(mContext.getResources().getString(messageId));
        mMessage.setMovementMethod(ScrollingMovementMethod.getInstance());
    }
}
 
 
Layout xml file
 
 
dialog_msg.xml 

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout  
xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@+id/LinearLayout" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:layout_margin="0dip" 
      android:background="@drawable/alert_bg"     
      android:orientation="vertical" 
      android:paddingBottom="15dip"     
      android:paddingLeft="0dip"     
      android:paddingRight="0dip" 
      android:paddingTop="0dip" >
 
    <TextView 
           android:id="@+id/dialogTitle"         
           android:layout_width="fill_parent" 
           android:layout_height="wrap_content" 
           android:layout_marginTop="20dip" 
           android:background="#00000000"         
           android:gravity="center" 
           android:text=""         
           android:textColor="#fff" 
           android:textSize="22sp" 
           android:textStyle="bold" >
   </TextView>
    <TextView 
          android:id="@+id/dialogMessage"         
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content"         
          android:layout_below="@+id/dialogTitle"         
          android:focusable="true" 
          android:focusableInTouchMode="true"         
          android:gravity="center"         
          android:maxLines="10"         
          android:padding="10dip" 
          android:scrollbars="vertical" 
          android:text="" 
          android:textColor="#fff"         
          android:textSize="18sp" >
    </TextView>
    <Button         
          android:id="@+id/OkButton" 
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content"         
          android:layout_below="@+id/dialogMessage" 
          android:layout_centerHorizontal="true" 
          android:layout_marginLeft="10dip" 
          android:layout_marginRight="10dip" 
          android:background="@drawable/button" 
          android:text="OK"         
          android:textColor="#FFFFFF" >
    </Button>
</RelativeLayout>
 
 
Button design in drawable xml file 
 
button.xml
 
<?xml version="1.0" encoding="utf-8"?><selector xmlns: 
android="http://schemas.android.com/apk/res/android"
 
<item android:state_pressed="true" 
 android:drawable="@drawable/button_bg_pressed" /> 
<!-- pressed -->     
<item android:state_focused="true"  
android:drawable="@drawable/button_bg_pressed" />
 <!-- focused --> 
 <item android:drawable="@drawable/button_bg_normal" /> 
<!-- default --> 
</selector> 
 
 Images 
 



 


Result Activity:
 
 
 

 
 
 
 
 
 

Custom Dialog using Android Studio

Custom Dialog Showing using Button Click

To create custom dialog in android with help of android studio ide

Another Activity to Call :- 

        btn_next = (Button)findViewById(R.id.btn_next);
        btn_next.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {

                CustomDialogFragment cdf = new CustomDialogFragment();
                cdf.show(getSupportFragmentManager(),"CustomDialogFragment");

            }
        });

Custom Dialog Fragment class ===> java Class

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
public class CustomDialogFragment extends DialogFragment {
    @Override    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity());
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        dialog.setContentView(R.layout.dialog_custom);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        // OK        dialog.findViewById(R.id.positive_button).setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {
                dismiss();
            }
        });
        // Close        dialog.findViewById(R.id.close_button).setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {
                dismiss();
            }

        });
        return dialog;
    }
}
 
custom_dialog.xml file
 
dialog_custom.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:layout_width="match_parent" 
               android:layout_height="wrap_content" 
               android:layout_alignParentTop="true"         
               android:layout_marginTop="6dp"         
               android:layout_marginLeft="6dp"         
               android:layout_marginRight="6dp"         
               android:paddingBottom="20dp" 
               android:background="@drawable/bg_dialog"         
               android:gravity="center_horizontal" 
               android:orientation="vertical" >
            <TextView 
             android:id="@+id/title" 
             android:layout_width="match_parent" 
             android:layout_height="wrap_content" 
             android:background="@drawable/bg_title"             
             android:padding="10dp" 
             android:text="Title" 
             android:textSize="18sp" 
             android:textColor="@android:color/white" />
            <TextView 
                  android:id="@+id/message"             
                  android:layout_width="wrap_content"             
                  android:layout_height="wrap_content"             
                  android:layout_margin="20dp" 
                  android:lineSpacingExtra="6dp" 
                  android:text="Message Dialog Content Showing Here Internet connection" 
                  android:textSize="16sp" 
                  android:textColor="#333333" />
            <Button             
                  android:id="@+id/positive_button" 
                  android:layout_width="wrap_content" 
                  android:layout_height="wrap_content" 
                  android:layout_marginTop="6dp" 
                  android:background="@drawable/bt_dialog_positive" 
                  android:text="OK" 
                  android:textColor="@android:color/white"            />
    </LinearLayout>

           <Button 
                 android:id="@+id/close_button" 
                 android:layout_width="40dp" 
                 android:layout_height="40dp" 
                 android:layout_alignParentRight="true"         
                 android:layout_alignParentTop="true" 
                 android:background="@drawable/bt_dialog_close" 
                 android:text="×" 
                 android:textColor="#9acd32"
        />
</RelativeLayout>
 
 
 ==============drawable folder xml files ============================
 
  
bg_dialog.xml
 
 <?xml version="1.0" encoding="utf-8"?> 
 <shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners android:radius="5dp"/>
       <stroke android:width="2dp" android:color="#9acd32"/>
       <gradient android:startColor="#ffffff" android:endColor="#dcdcdc" android:angle="90"/>
 </shape>
 
 
 
 bg_title.xml
 
 <?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners android:topLeftRadius="5dp" android:topRightRadius="5dp"/>
    <solid android:color="#9acd32"/>
 </shape>
 
 
bt_dialog_close.xml
 
 <?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="oval">
    <solid android:color="@android:color/white"/>
    <stroke        android:width="3dp"        android:color="#9acd32"        />
 </shape>
 
 
bt_dialog_positive.xml
 
 <?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android" >
   <corners android:radius="5dp" />
   <solid android:color="#9acd32" />
 </shape>
 
 
 Result Image