Thursday 13 April 2017


Marshmallow Permissions 

Now we have to check marshmallow permissions in our application, I have developed one PermissionUtils class for it, 
We have just called one method and pass which permission you wants to check. You would implement in 10 mins only.

PermissionUtils : 

public class PermissionUtils implements ActivityCompat.OnRequestPermissionsResultCallback {


    public final static String PERMISSION_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private Context context;
    private PermissionGranted permissionGranted;

    public PermissionUtils(final Context context) {
        this.context = context;
    }


    /**
     * Check the permission
     * Only pass the permission which you wants to check
     *
     *
@param
permission  Permission Name
     *
@param
requestCode Call Back for permission granted or not.
     *
@return is permission granted or not.
     */
   
public boolean checkPermission(final String permission, final int requestCode) {
        final int readPermissionCheck = ContextCompat.checkSelfPermission(context, permission);
        if (readPermissionCheck != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{permission},
                        requestCode);
                return true;
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * Add Multiple Permission in list and pass in the multi check permission dialog
     *
     *
@param
permissionList list of permission
     */
   
private String[] checkPermissions(final ArrayList<String> permissionList) {
        List<String> arrPermission = new ArrayList<>();
        for (int i = 0; i < permissionList.size(); i++) {
            final String permission = permissionList.get(i);
            if (ContextCompat.checkSelfPermission(context,
                    permission) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
                arrPermission.add(permission);
            }
        }
        String[] permissions = new String[arrPermission.size()];
        permissions = arrPermission.toArray(permissions);
        return permissions;
    }


    /**
     * Call where multiple permission require and only pass arraylist of permission.
     *
     *
@param
permissionList list of permission
     *
@param
requestCode    Call Back for permission granted or not.
     *
@return is permission granted or not.
     */
   
public boolean checkMultiplePermissions(final ArrayList<String> permissionList, final int requestCode) {
        String[] arrPermission = checkPermissions(permissionList);
        if (arrPermission.length > 0) {
            ActivityCompat.requestPermissions((Activity) context,
                    arrPermission,
                    requestCode);
            return true;
        }
        return false;
    }


    @Override
   
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case Constants.REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (permissionGranted != null) {
                        permissionGranted.onPermissionGranted();
                    }
                } else {
                    DialogUtils.showSnackBar(context, "You are not able to pick photo from gallery");
                }
                break;

        }
    }


    /**
     * Set the interface where callback require.
     *
     *
@param
permissionGranted This is callback interface.
     */
   
public void setPermissionGranted(final PermissionGranted permissionGranted) {
        this.permissionGranted = permissionGranted;
    }

    /**
     * This is callback interface.
     */
   
public interface PermissionGranted {
        void onPermissionGranted();
    }

}

How to use PermissionUtils class 

public class OneFragment extends Fragment implements View.OnClickListener, PermissionUtils.PermissionGranted {

    @Nullable
    @Override
   
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_1, container, false);
    }


@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    initializeComponent(view);
}


    @Override
   
public void initializeComponent(View view) {
        imageView = (ImageView) view.findViewById(R.id.fragment_1_iv_profile);
    }

   

    @Override
   
public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
        case R.id.fragment_1_iv_profile:
final PermissionUtils permissionUtils = new PermissionUtils();
        permissionUtils.setPermissionGranted(this);
        if (!(permissionUtils.checkPermission(PermissionUtils.PERMISSION_STORAGE, Constants.REQUEST_CODE_ASK_PERMISSIONS)) {
           //Code for if already permission granted.
        }
        break;
  }
 
    
    @Override
   
public void onPermissionGranted() {
         //While we have allowed the permission this interface method will call.
    }
}

Friday 13 January 2017

Spinner in ListView : 

Adapter Class : 
/** * Created on 05/01/17. */public class WorkListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<WorkModel> workModelArrayList;

    public WorkListAdapter(final Context context, final ArrayList<WorkModel> workModelArrayList) {
        this.context = context;
        this.workModelArrayList = workModelArrayList;
    }

    @Override    public int getCount() {
        return workModelArrayList.size();
    }

    @Override    public WorkModel getItem(int i) {
        return workModelArrayList.get(i);
    }

    @Override    public long getItemId(int i) {
        return i;
    }

    @Override    public View getView(final int i, View view, ViewGroup viewGroup) {
        final ViewHolder viewHolder;
        if (view == null) {
            final LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(R.layout.row_worker, viewGroup, false);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        final WorkModel workModel = workModelArrayList.get(i);

//        removeTextChangedListener(viewHolder);//        viewHolder.edtName.setText(workModel.getWorkerName());//        addTextChangedListener(viewHolder, i);

        final ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, workModel.getTypes());
        viewHolder.edtName.setAdapter(adapter);
        viewHolder.edtName.setOnItemSelectedListener(null);
        viewHolder.edtName.setSelection(workModel.getPosition());
        viewHolder.edtName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                workModel.setPosition(i);
            }

            @Override            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        return view;
    }

    private class ViewHolder {
        private Spinner edtName;

        ViewHolder(final View view) {
            edtName = (Spinner) view.findViewById(R.id.row_worker_edit_name);
        }


    }


}
 
 
Model Class : 
 
public class WorkModel {

    private int workerId;
    private String workerName;
    private String[] types = {"Android", "iPhone", "Window"};
    private int position;

    public int getWorkerId() {
        return workerId;
    }

    public void setWorkerId(int workerId) {
        this.workerId = workerId;
    }

    public String getWorkerName() {
        return workerName;
    }

    public void setWorkerName(String workerName) {
        this.workerName = workerName;
    }

    public String[] getTypes() {
        return types;
    }

    public void setTypes(String[] types) {
        this.types = types;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }
}
 
Activity Class: 
 
public class MainActivity extends AppCompatActivity {

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

        final ListView lv = (ListView) findViewById(R.id.activity_main_lv);
        final ArrayList<WorkModel> workModelList = new ArrayList<>();

        for(int i = 0 ; i < 1000; i++){
            workModelList.add(new WorkModel());
        }

        final WorkListAdapter workListAdapter = new WorkListAdapter(this, workModelList);
        lv.setAdapter(workListAdapter);

    }
}
 
 

Thursday 12 January 2017

EditText With ListView.

When we are using EditText in ListView that time we have to implement TextWatcher because you have to add text in your Model/Pojo class after text is entered.

Adapter Class.
I have created one custom baseadapter class for it. In this adapter class i have created one class for TextWatcher because we have to update arraylist after text changed.

package mavya.edittextinlistview;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;

import java.util.ArrayList;


/** * Created on 05/01/17. */public class WorkListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<WorkModel> workModelArrayList;

    public WorkListAdapter(final Context context, final ArrayList<WorkModel> workModelArrayList) {
        this.context = context;
        this.workModelArrayList = workModelArrayList;
    }

    @Override    public int getCount() {
        return workModelArrayList.size();
    }

    @Override    public WorkModel getItem(int i) {
        return workModelArrayList.get(i);
    }

    @Override    public long getItemId(int i) {
        return i;
    }

    @Override    public View getView(final int i, View view, ViewGroup viewGroup) {
        final ViewHolder viewHolder;
        if (view == null) {
            final LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(R.layout.row_worker, viewGroup, false);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        final WorkModel workModel = workModelArrayList.get(i);

        removeTextChangedListener(viewHolder);
        viewHolder.edtName.setText(workModel.getWorkerName());
        addTextChangedListener(viewHolder, i);

        return view;
    }

    private class ViewHolder {
        private EditText edtName;
        private MyTextWatcher myTextWatcher;

        ViewHolder(final View view) {
            edtName = (EditText) view.findViewById(R.id.row_worker_edit_name);
        }

        public EditText getProductQuantity() {
            return edtName;
        }

        public MyTextWatcher getTextChangedListener() {
            return myTextWatcher;
        }

        public void setTextChangedListener(MyTextWatcher textChangedListener) {
            this.myTextWatcher = textChangedListener;
        }

    }

    private class MyTextWatcher implements TextWatcher {
        private int pos;

        public MyTextWatcher(final int pos) {
            this.pos = pos;
        }

        @Override        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override        public void afterTextChanged(Editable editable) {
            workModelArrayList.get(pos).setWorkerName(editable.toString());
        }
    }

    private void removeTextChangedListener(ViewHolder viewHolder) {
        final MyTextWatcher textChangedListener = viewHolder.getTextChangedListener();
        final EditText edtValue = viewHolder.getProductQuantity();
        edtValue.removeTextChangedListener(textChangedListener);
    }

    private void addTextChangedListener(ViewHolder viewHolder, int position) {
        final MyTextWatcher textChangedListener = new MyTextWatcher(position);
        final EditText edtValue = viewHolder.getProductQuantity();
        edtValue.addTextChangedListener(textChangedListener);
        viewHolder.setTextChangedListener(textChangedListener);
    }

}
 
Model Class : 
 
public class WorkModel {

    private int workerId;
    private String workerName;

    public int getWorkerId() {
        return workerId;
    }

    public void setWorkerId(int workerId) {
        this.workerId = workerId;
    }

    public String getWorkerName() {
        return workerName;
    }

    public void setWorkerName(String workerName) {
        this.workerName = workerName;
    }
}
 
Activity Class :  
 
public class MainActivity extends AppCompatActivity {

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

        final ListView lv = (ListView) findViewById(R.id.activity_main_lv);
        final ArrayList<WorkModel> workModelList = new ArrayList<>();

        for(int i = 0 ; i < 1000; i++){
            workModelList.add(new WorkModel());
        }

        final WorkListAdapter workListAdapter = new WorkListAdapter(this, workModelList);
        lv.setAdapter(workListAdapter);

    }
}

Thursday 23 April 2015

How to import Android Studio Project in Android Studio.

Step 1.

Step 2. In this screen shot you can see the x sign which means project is not properly imported.


Step 3. In this screen shot, "Sync Project with Gradle file" When we clicks on this button, Project will Sync with Gradle. 


Step 4. In this screen shot you can see that x sign is removed. it means , Project is properly imported in Android Studio.



How To Create New Project In Android Studio.


Step 1.
Step 2.
Step 3.

Step 4.


Step 5.
Step 6.




Sunday 29 June 2014

Custom EditText With change hint font style ,text font style and password character change.


This  is my CustomEditText Class and its attr.xml

public class CustomEditText extends EditText implements TextWatcher {
private Typeface tf = null, tfhint = null;
private String customhintfont, customFont;
boolean inputtypepassword;
private CharSequence chartype;

// private CharSequence mSource;

public CustomEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
// initViews();
}

public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
// initViews();
setCustomFontEdittext(context, attrs);

}

public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
// initViews();
setCustomFontEdittext(context, attrs);
}

private void setCustomFontEdittext(Context ctx, AttributeSet attrs) {
final TypedArray a = ctx.obtainStyledAttributes(attrs,
R.styleable.CustomEditText);
customFont = a.getString(R.styleable.CustomEditText_edittextfont);
customhintfont = a
.getString(R.styleable.CustomEditText_edittextfontHint);

// custompwd = a.getString(R.styleable.CustomEditText_edittextpwd);
inputtypepassword = a.getBoolean(
R.styleable.CustomEditText_edittextpwd, false);
setCustomFontEdittext(ctx, customFont);
setCustomFontEdittextHint(ctx, customhintfont);

chartype = (CharSequence) a
.getText(R.styleable.CustomEditText_editcharpwd);
setCustompwd(inputtypepassword);
a.recycle();
}

public boolean setCustompwd(boolean pwd) {
if (pwd) {
this.setTransformationMethod(new PasswordCharacterChange());
}
return pwd;
}

public boolean setCustomFontEdittext(Context ctx, String asset) {
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
return false;
}
setTypeface(tf);
return true;
}

public boolean setCustomFontEdittextHint(Context ctx, String asset) {
try {
tfhint = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
return false;
}
setTypeface(tfhint);

return true;
}

@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore,
int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
if (text.length() < 0) {
setCustomFontEdittextHint(getContext(), customhintfont);
} else {
setCustomFontEdittextHint(getContext(), customFont);
}
if (TextUtils.isEmpty(text)) {
setCustomFontEdittextHint(getContext(), customhintfont);
}
// this.setText("*");
}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

public class PasswordCharacterChange extends PasswordTransformationMethod {

@Override
public CharSequence getTransformation(CharSequence source, View view) {
// TODO Auto-generated method stub
return new PasswordCharSequence(source);
}

private class PasswordCharSequence implements CharSequence {
private CharSequence mSource;

public PasswordCharSequence(CharSequence source) {
mSource = source; // Store char sequence
}

public char charAt(int index) {
return chartype.charAt(0); // This is the important part
}

public int length() {
return mSource.length(); // Return default
}

public CharSequence subSequence(int start, int end) {
return mSource.subSequence(start, end); // Return default
}
}
}

}


2) attrs.xml


 <declare-styleable name="CustomEditText">
        <attr name="edittextfont" format="string" />
        <attr name="edittextfontHint" format="string" />
        <attr name="edittextpwd" format="string" />
        <attr name="editcharpwd" format="string" />
    </declare-styleable>

3) activity_main.xml




<com.customdemo.CustomEditText
        android:id="@+id/activity_main_edit_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       app:edittextfont="Calibri Bold Italic.ttf"
        app:edittextfontHint="beatmygu.ttf"/>




<com.customdemo.CustomEditText
        android:id="@+id/activity_main_edit_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:editcharpwd="$"
        app:edittextpwd="true"
       />




Wednesday 25 June 2014

Fragment Transaction above android 4.0 using ObjectAnimator




1) First create Custom Class for container.

public class SlidingRelativeLayout extends RelativeLayout {
    private float xFraction = 0;

    public SlidingRelativeLayout(Context context) {
        super(context);
    }

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

    public SlidingRelativeLayout(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    private ViewTreeObserver.OnPreDrawListener preDrawListener = null;


    public void setXFraction(float fraction) {
        this.xFraction = fraction;
        if (getWidth() == 0) {
            if (preDrawListener == null) {
                preDrawListener = new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        getViewTreeObserver().removeOnPreDrawListener(
                                preDrawListener);
                        setXFraction(xFraction);
                        return true;
                    }
                };
                getViewTreeObserver().addOnPreDrawListener(preDrawListener);
            }
            return;
        }
        float translationX = getWidth() * fraction;
        setTranslationX(translationX);
    }
}

2) Four animator files  require.

 1) animator/slide_fragment_left_in.xml

         <objectAnimator
                 xmlns:android="http://schemas.android.com/apk/res/android"
                 android:interpolator="@android:anim/accelerate_decelerate_interpolator"
                 android:propertyName="XFraction"
                 android:valueType="floatType"
                 android:valueFrom="-1"
                 android:valueTo="0"
                 android:duration="@android:integer/config_mediumAnimTime"/>

 2)animator/slide_fragment_left_out.xml
          <objectAnimator
                 xmlns:android="http://schemas.android.com/apk/res/android"
                 android:interpolator="@android:anim/accelerate_decelerate_interpolator"
                 android:propertyName="XFraction"
                 android:valueType="floatType"
                 android:valueFrom="0"
                 android:valueTo="-1"
                 android:duration="@android:integer/config_mediumAnimTime"/>

 3)animator/slide_fragment_right_in.xml
            <objectAnimator
                      xmlns:android="http://schemas.android.com/apk/res/android"
                      android:interpolator="@android:anim/accelerate_decelerate_interpolator"
                      android:propertyName="XFraction"
                      android:valueType="floatType"
                      android:valueFrom="1"
                      android:valueTo="0"
                      android:duration="@android:integer/config_mediumAnimTime"/>

 4)animator/slide_fragment_right_out.xml
              <objectAnimator
                     xmlns:android="http://schemas.android.com/apk/res/android"
                     android:interpolator="@android:anim/accelerate_decelerate_interpolator"
                     android:propertyName="XFraction"
                     android:valueType="floatType"
                     android:valueFrom="0"
                     android:valueTo="1"
                     android:duration="@android:integer/config_mediumAnimTime"/>
            

3) Container, 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=".MainActivity" >

    <com.example.slidingdemo.SlidingRelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </com.example.slidingdemo.SlidingRelativeLayout>

</RelativeLayout>

4) fragment_first.xml.


<com.example.slidingdemo.SlidingRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_next"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="NEXT" />

</com.example.slidingdemo.SlidingRelativeLayout>


5) fragment_second.xml

<com.example.slidingdemo.SlidingRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_back"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Back" />

</com.example.slidingdemo.SlidingRelativeLayout>


6) Now Only setCustomAnimation use in fragmenttransaction and set above animator xml file. 


Like:-

final FragmentManager fragmentManager = getFragmentManager();
                        final FragmentTransaction fragmentTransaction = fragmentManager
                                .beginTransaction();
                        fragmentTransaction.setCustomAnimations(
                                R.animator.slide_fragment_right_in,
                                R.animator.slide_fragment_left_out,
                                R.animator.slide_fragment_left_in,
                                R.animator.slide_fragment_right_out);
                        final SecondFragment firstFragment = new SecondFragment();
                        fragmentTransaction.replace(R.id.container,
                                firstFragment, firstFragment.getClass()
                                        .getSimpleName());
                        fragmentTransaction.addToBackStack(firstFragment
                                .getClass().getSimpleName());
                        fragmentTransaction.commit();