Thursday, January 5, 2017

Recycler View in Android

Recycler view in android is use for show data like a listview .

add build gradel : 


compile 'com.android.support:recyclerview-v7:24.1.1'

XML Define RecyclerView

<android.support.v7.widget.RecyclerView   
 android:id="@+id/recycler_view"    
android:layout_width="match_parent" 
   android:layout_height="match_parent"
    android:scrollbars="none"/>


RecyclerView mRecyclerView;
LinearLayoutManager linearLayoutManager;

ArrayList<Model> arrayList = null;

Initialize : 
arrayList = new ArrayList<>();  // array initialize

mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);


arrayList.add(new Model("Android")); // add static data to array
arrayList.add(new Model("iPhone"));
arrayList.add(new Model("Window"));
arrayList.add(new Model("Blackberry"));
arrayList.add(new Model("Symbion"));

adapter = new CustomAdapter(this, arrayList); // show data
mRecyclerView.setAdapter(adapter);  // set adapter

Now discuss about adapter :  

class CustomAdapter extends RecyclerView.Adapter<CustomAdapter .ViewHolder> {

    ArrayList<HomeModel> arrayList;

    public CustomAdapter (ArrayList<HomeModel> arrayList) {
        this.arrayList = arrayList;
    }

    @Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
       viewHolder.title.setText(arrayList.get(position).getTitle());

    }

    @Override    public int getItemCount() {
        return arrayList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;

        public ViewHolder(View convertView) {
            super(convertView);
            title = (TextView) convertView.findViewById(R.id.title);
        }
    }


Custom Model Class

lass HomeModel {

    String title;

    public HomeModel(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }


Wednesday, June 15, 2016

Get Path from Uri and get Uri from path in Android

In android taking pic from camera or pic image from sd card, we get response in OnActivityResult  in form of data (Intent) so get path from data we use this method.

Uri imageUri = data.getData();

Wednesday, May 25, 2016

Generate Local Notification in Android

Generate local notification like Remainder or other scheduling task.

Call generateNotification Method and set Title and Message.
    Generate Local Notification
private void generateNotification(Context context, String title,String message) {
int requestId = (int) System.currentTimeMillis();
try {
int icon = R.drawable.ic_launcher; // set icon
Intent intent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context);
Notification notification = mBuilder
.setSmallIcon(icon)
.setTicker(title)
.setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(
new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentIntent(resultPendingIntent)
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(
BitmapFactory.decodeResource(
context.getResources(), icon))
.setContentText(message).build();

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;

NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(requestId, notification);
} catch (Exception e) {
}

}

Show Notification
Send Notification


Thursday, December 3, 2015

Color Change On Click in Android

when click on Button or TextView or may be layout, when click then change background color. purpose of this, user can detect click or not on button.

when press button then color should be changed.

Save Value in SharedPreferences

Save Value in SharedPreferences 

In Android Save Value in key pair format we use SharedPreferences.

       SharedPreferences     myPrefs = getSharedPreferences("TAG", MODE_PRIVATE);
SharedPreferences.Editor myEditor = myPrefs.edit();

save value

      myEditor.putString("name", abc); // key pair
       myEditor.commit();


Save Boolean Value

      myEditor.putBoolean("key", abc); // key pair
       myEditor.commit();

Get Boolean Value 

boolean status= myEditor.getBoolean(key, false);

Get Save value 

     String name = myPrefs.getString("name", "");

Wednesday, December 2, 2015

JSON Parsing in Android

Parse data from server is many type like XML,DOM and JSON but JSON Parsing widely used, this topic we discuss JSON PARSING.

How to Parse JSON Object:

first we get data from server afterthat we parse, in JSON start with Object or Array.
{ }   =   Object

[ ]  = Array

so we check data is object or array.

    String result=  {"response":"100","data" : "Sucess"} 

It is start with object so first object parse then string.

try {
    JSONObject json = new JSONObject(result);
       String response= json.getString("response");                                   
       String data= json.getString("data");      
} catch (JSONException e) {
    e.printStackTrace();
}
we get response = 100;
and data= Sucess


Tuesday, December 1, 2015

Show Google Ads in Android(AdMob)

show advertising in android mobile like banner or full screen add.


Banner Ads in Android
AdMob in Android
First we need id for ads open https://apps.admob.com/ and monetise application . there are basically two type of ads .

First: Banner Ad (show banner at top or bottom)
Second Full Screen Ad(Interstitial Ads)

Banner Ad show


banner can be adjust according to app it may be top or bottom

add  Google Play Library 

        AdView mAdView = (AdView) findViewById(R.id.adViewHOME);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

AdMob XML File  :


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
     <com.google.android.gms.ads.AdView
        android:id="@+id/adMob"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="YOUR BANNER ID" >
    </com.google.android.gms.ads.AdView>

</RelativeLayout>

Manifest Permission

you must have set  internet permission.

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


Full Screen Ads : 


InterstitialAd mInterstitialAd;
AdRequest adRequestFull;

mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("YOUR ID");

adRequestFull = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .build();
mInterstitialAd.loadAd(adRequestFull);






Saturday, November 28, 2015

Open Right to Left Navigation Drawer Android

open right to left Navigation Drawer in android fragment activity. it is similar to left to right as we discuss http://invokecode.blogspot.com/2015/11/custom-navigation-drawer-in-android.html
but in this we need to change line.

?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent">
    <android.support.v4.widget.DrawerLayout 
       android:id="@+id/drawer_layout" 
       android:layout_width="fill_parent"  
       android:layout_height="match_parent">
        <FrameLayout 
           android:id="@+id/content_frame_Home"            
           android:layout_width="match_parent"      
           android:layout_height="match_parent"/>
        <RelativeLayout  
          android:id="@+id/left_relative"   
          android:layout_width="300dp"   
          android:layout_height="wrap_content" 
           android:layout_gravity="start">
            <include layout="@layout/slider" />
        </RelativeLayout>
    </android.support.v4.widget.DrawerLayout>
</RelativeLayout> 
 
android:layout_gravity="start"   change to  android:layout_gravity="end"
in Coding we need to change GRAVITY LEFT To Right..
DrawerLayout drawerLayout;
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.openDrawer(Gravity.RIGHT);

Use Weight in Linear Layout Android

use weight for equal child of layout. margin and padding unable to set equal child because when multi screen support and margin and padding set fix, but in weight they remains same in all layout.

In Linear Layout need orientation horizontal and vertical.


XML for Linear layout weight.

<LinearLayout    
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="50dp" 
     android:layout_marginLeft="20dp"
     android:layout_marginRight="20dp"
     android:orientation="horizontal">

    <TextView       
       android:layout_width="0dp" 
       android:layout_weight="1" 
       android:layout_height="wrap_content" 
       android:text="FIRST"   
       android:gravity="center"  
       android:textSize="20sp"  
       android:textColor="#000000"/>

    <TextView  
      android:layout_width="0dp"   
      android:layout_weight="1"    
      android:layout_height="wrap_content"  
      android:text="SECOND"   
      android:gravity="center"   
      android:layout_marginLeft="20dp"
      android:textSize="20sp"   
     android:textColor="#000000"/>

</LinearLayout>

Monday, November 23, 2015

View Pager in android

View Pager-scroll page (slide) call view pager.



ViewPager pager;

private ArrayList<ModelClassPager> arrayOfPager;

                  pager1 = (ViewPager)findViewById(R.id.pager);
arrayOfPager = new ArrayList<ModelClass>();

arrayOfPager.add(new ModelClass(R.drawable.first));
arrayOfPager.add(new ModelClass(R.drawable.second));
arrayOfPager.add(new ModelClass(R.drawable.third));
                arrayOfPager.add(new ModelClass(R.drawable.four));

PagerAdapter  pagerAdapter = new PagerAdapter  (MainActivity.this,arrayOfPager);

pagerAdapter .setAdapter(pagerAdapter);


Custom Adapter for View Pager:


PagerAdapter   extends PagerAdapter {

LayoutInflater inflates;
ArrayList<ModelClass> arrayOfPager;

Context context;

public PagerAdapter   (Context context,
ArrayList<ModelClass> arrayOfPager_) {
this.context = context;
this.arrayOfPager = arrayOfPager_;
inflates = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

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

public Object instantiateItem(View collection, int position) {

ViewGroup container = null;
ImageView pgrImage;
View viewPgaer = inflates.inflate(R.layout.row_pager, null);

pgrImage = (ImageView)viewPgaer
.findViewById(R.id.pagerImage);

pgrImage.setImageResource(arrayOfPager.get(position).getPagerImg());

((ViewPager) collection).addView(viewPgaer, 0);

return viewPgaer;
}

public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}

public boolean isViewFromObject(View view, Object object) {
return view == (object);
}

public void finishUpdate(View arg0) {
}

@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}

@Override
public Parcelable saveState() {
return null;
}

@Override
public void startUpdate(View arg0) {
}

}


Model Class (Gettor Settor Class):

public class ModelClassPager {

int pagerImg = 0;

public int getPagerImg() {
return pagerImg;
}

public void setPagerImg(int pagerImg) {
this.pagerImg = pagerImg;
}
public ModelClassPager( int pagerImg_) {
// TODO Auto-generated constructor stub
pagerImg = pagerImg_;
}

}

XML Design For View Pager:
   <android.support.v4.view.ViewPager
        android:id="@+id/pagesCustmLayoutMAIN"
        android:layout_width="fill_parent"
        android:layout_height="160dp" />