Read Contactlist

Read Contactlist

Hello guys !!

If you want to fetch contact list from your android device then you are at right place. Contact book read using ContentResolver class.

First you need to make ContentResolver Object.

ContentResolver cr = getContentResolver();

getContentResolver() return the device Resource access.

Then after make cursor for getting contacts from device resource using ContentResolver object.

Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
        null, null, null, null);

Now getting name and number from cursor object to your ArrayList<> or array[].

public ArrayList<String> nameArr = new ArrayList<String>();
public ArrayList<String> numArr = new ArrayList<String>();
if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
        String id = cur.getString(
                cur.getColumnIndex(ContactsContract.Contacts._ID));
        String name = cur.getString(cur.getColumnIndex(
                ContactsContract.Contacts.DISPLAY_NAME));
        if (cur.getInt(cur.getColumnIndex(
                ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
            Cursor pCur = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                    new String[]{id}, null);
            while (pCur.moveToNext()) {
                String phoneNo = pCur.getString(pCur.getColumnIndex(
                        ContactsContract.CommonDataKinds.Phone.NUMBER));
                numArr.add(phoneNo + "");
                nameArr.add(name + "");
            }
            pCur.close();
        }
    }
}

In previous example ChangeWallpaper programatically we discuss about permission so we need take permission in our AndroidMenifest.xml file.

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

 

 

Full Source Code :

 

activity_contact_read.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">



    <ListView
        android:id="@+id/lvContact"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
</LinearLayout>

 

ContactReadActivity.java

public class ContactReadActivity extends AppCompatActivity {
    public ListView lvContact;
    public ArrayList<String> nameArr = new ArrayList<String>();
    public ArrayList<String> numArr = new ArrayList<String>();
    public ContactAdapter cAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_read);
        lvContact = (ListView) findViewById(R.id.lvContact);
        cAdapter = new ContactAdapter(ContactReadActivity.this, nameArr, numArr);
        lvContact.setAdapter(cAdapter);

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(
                        ContactsContract.Contacts.DISPLAY_NAME));
                if (cur.getInt(cur.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));
                        numArr.add(phoneNo + "");
                        nameArr.add(name + "");
                    }
                    pCur.close();
                    cAdapter.notifyDataSetChanged();
                }
            }
        }
    }
}

 

ContactAdapter.java

 

public class ContactAdapter extends BaseAdapter {

    public Context ct;
    public ArrayList<String> nameArr = new ArrayList<String>();
    public ArrayList<String> numArr = new ArrayList<String>();

    public ContactAdapter(Context ct, ArrayList<String> nameArr, ArrayList<String> numArr) {
        this.ct = ct;
        this.nameArr = nameArr;
        this.numArr = numArr;
    }

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

    @Override
    public Object getItem(int position) {
        return nameArr.get(position);
    }

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

    Holder holder;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(ct).inflate(R.layout.cutsom_contact_row, null);
            holder = new Holder();
            holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
            holder.tvNum = (TextView) convertView.findViewById(R.id.tvNum);
            convertView.setTag(holder);
        }else{
            holder=(Holder)convertView.getTag();
        }

        holder.tvName.setText(nameArr.get(position));
        holder.tvNum.setText(numArr.get(position));
        return convertView;
    }

    class Holder {
        TextView tvName, tvNum;
    }

}

custom_contact_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        android:padding="5dp"
        android:singleLine="true"/>

    <TextView
        android:id="@+id/tvNum"
        android:textColor="@android:color/black"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        android:padding="5dp"
        android:singleLine="true"/>

</LinearLayout>

 

Thank you.  🙂

If you have any query or face any problem in your android programming feel free to write here 🙂

How to Load image From URL :

How to Load image From URL :

Hello Friends !! welcome back to https://yashajabiya.wordpress.com/ .

Today we learn about how to load image direct from URL :

Using Picasso Image Loader library , we can load our image direct url to our ImageView control. Which you can Download from here :

So download .jar file and put into your libs folder . load with your build.gradle file on dependencies part :

compile files('libs/picasso-2.5.2.jar')

now take one ImageView Control your xml file :


Cast into your .java file :

ImageView img = (ImageView) findViewById(R.id.img);

Load url image in your ImageView control using Picasso:

Picasso.with(contex)
        .load("https://yashajabiya.files.wordpress.com/2016/07/facebook_cover.jpg?")
        .placeholder(R.drawable.default_img)
        .error(R.drawable.error_img)
        .into(img);

Parameter & Description :

load : Pass url which you want to load image.

placeholder:  It will show image as a place holder untill your url image not loaded fully on control.

error: It will show when loading process over and any problem occure with url then it show error drawable image.

Thank you : 

If any query feel free to write here :

How to Check Internet Connection Available or Not

How to Check Internet Connection Available or Not

Hello Friends !!

Today, We learn about how to check internet connection is available or not.

This Function is use when you work with Rest API, or any work with internet in your application.

So, First of all we need to create Object of Connectivity Manager.

ConnectivityManager is a class of inbuilt by android platform for check the current internet connection is available or not , it also notify when change the network state.

Ex :

ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);

Context.CONNECTIVITY_SERVICE is check the current system connection either if you using mobile data/WiFi.

When you  want use it more than one time then create one method which return Boolean object for return true either connection is establish  or false when not connected.

Now Compare the ConnectivityManager class object with condition for check.

Ex:

boolean connected=false;

if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else {
connected = false;
}

so the above condition return true/false for check with connection of your mobile data and also check the WiFi connection.

Finally Your method will be :

public boolean isNetworkCheck(){

boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);

if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else {
connected = false;
}
return connected;

}

Finally when we work with any component or hardware with our device then you need to get the permission in you AndroidManifiest.xml file:

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

 

So Enjoy Coding , Any query feel free to write here .

Thank you.

🙂

How to Change Wallpaper programmatically

How to Change Wallpaper programmatically

 

Hello friends !! Welcome back to https://yashajabiya.wordpress.com/

Today we learn that how to change the device wallpaper programmatically. So let’s do it …!!

So first of all make one screen with one button and ImageView control.

activity_chngwallpaper.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <Button
        android:id="@+id/btnPick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick Image" />

    <ImageView
        android:id="@+id/imgWallpaper"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:scaleType="fitXY"
        android:src="@drawable/default_img" />

</LinearLayout>

Now Make one Activity and define two controls globally.

public Button btnPick;
public ImageView imgWallpaper;
public static final int RESULT_PRO_IMG=1;

Cast the both controll in your onCreate()

imgWallpaper = (ImageView) findViewById(R.id.imgWallpaper);
btnPick = (Button) findViewById(R.id.btnPick);

now set onClick listner on our Button Controll.

btnPick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        
    }
});

put the Implicit intent for pick image from your device gallery :

btnPick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, RESULT_PRO_IMG);
    }
});

if you aware the Implicit intent or Explicit intent then you understand easly otherwise check this out :

Now we need to set OnActivityResult() method when you reback in our app after choosen image from gallery , it take result code and data and one flag RESULT_PRO_IMG  which we pass when calling the Implicit Intent at our button Click event.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.i("Data", "Data Result Code :" + requestCode);
    switch (requestCode) {
        case RESULT_PRO_IMG:
            try {
                Log.i("Data", "Data :" + data);
                // When an Image is picked
                if (requestCode == RESULT_PRO_IMG && resultCode == RESULT_OK) {

                    try {
                        /*****************************************************************************************/
                        Uri img = data.getData();
                        String[] filepc = {MediaStore.Images.Media.DATA};
                        Cursor c = this.getContentResolver().query(img,
                                filepc, null, null, null);
                        c.moveToFirst();
                        int cIndex = c.getColumnIndex(filepc[0]);
                        String filePath = c.getString(cIndex);
                        c.close();
                        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        Matrix matrix = new Matrix();
                        matrix.postRotate(0);
                        imgWallpaper.setImageBitmap(bitmap);
                        WallpaperManager myWallpaperManager = WallpaperManager
                                .getInstance(getApplicationContext());
                        try {
                            if (bitmap != null) {
                                myWallpaperManager.setBitmap(bitmap);
                                Toast.makeText(ActivityChangeWallpaper.this, "Wallpaper set Successfully !!", Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(ActivityChangeWallpaper.this, "Your bitmap object is null !!", Toast.LENGTH_LONG).show();
                            }
                            //set wallpaper picture from resource here

                        } catch (IOException e) {
                            Toast.makeText(ActivityChangeWallpaper.this, "Something went wrong !!", Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(ActivityChangeWallpaper.this, "You haven't pick img", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                Toast.makeText(ActivityChangeWallpaper.this, "Something went wrong", Toast.LENGTH_LONG)
                        .show();
            }
            break;
    }
}

For change Wallpaper of our Device you need to make WallpaperManager object and set with your bitmap object :

   WallpaperManager myWallpaperManager = WallpaperManager
                                .getInstance(getApplicationContext());

If you are not Fresher in android then you know very well that when ever you perform any using of system resources that time you must need to take permission in our AndroidManifest.xml 

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

 

Full Code :

public class ActivityChangeWallpaper extends AppCompatActivity {

    public Button btnPick;
    public ImageView imgWallpaper;
    public final int RESULT_PRO_IMG = 1;

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

        imgWallpaper = (ImageView) findViewById(R.id.imgWallpaper);
        btnPick = (Button) findViewById(R.id.btnPick);

        btnPick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, RESULT_PRO_IMG);
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("Data", "Data Result Code :" + requestCode);
        switch (requestCode) {
            case RESULT_PRO_IMG:
                try {
                    Log.i("Data", "Data :" + data);
                    // When an Image is picked
                    if (requestCode == RESULT_PRO_IMG && resultCode == RESULT_OK) {

                        try {
                            /*****************************************************************************************/
                            Uri img = data.getData();
                            String[] filepc = {MediaStore.Images.Media.DATA};
                            Cursor c = this.getContentResolver().query(img,
                                    filepc, null, null, null);
                            c.moveToFirst();
                            int cIndex = c.getColumnIndex(filepc[0]);
                            // sDecode = cursor.getString(cIndex);
                            String filePath = c.getString(cIndex);
                            c.close();
                            Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                            int width = bitmap.getWidth();
                            int height = bitmap.getHeight();
                            Matrix matrix = new Matrix();
                            matrix.postRotate(0);
                            imgWallpaper.setImageBitmap(bitmap);

                            WallpaperManager myWallpaperManager = WallpaperManager
                                    .getInstance(getApplicationContext());
                            try {
                                if (bitmap != null) {
                                    myWallpaperManager.setBitmap(bitmap);
                                    Toast.makeText(ActivityChangeWallpaper.this, "Wallpaper set Successfully !!", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(ActivityChangeWallpaper.this, "Your bitmap object is null !!", Toast.LENGTH_LONG).show();
                                }
                                //set wallpaper picture from resource here

                            } catch (IOException e) {
                                Toast.makeText(ActivityChangeWallpaper.this, "Something went wrong !!", Toast.LENGTH_LONG).show();
                            }

                           /* Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                                    width, height, matrix, true);
                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                                    outputStream);
                            imgProduct.setImageBitmap(resizedBitmap);
                            decodeProfileImg(sDecode);*/
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(ActivityChangeWallpaper.this, "You haven't pick img", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(ActivityChangeWallpaper.this, "Something went wrong", Toast.LENGTH_LONG)
                            .show();
                }
                break;
        }
    }

}

firstsecondthirdfourth