Sunday, 14 February 2016

Android Programming Tutorial 66: Displaying All Messages From Mobile Inbox Example in Android Studio

Displaying All Messages From Mobile Inbox In Android:

In the below example we are discussing, how we display the total messages from the phone inbox.


Message Inbox Example in Android:

File >> New >> Android Application
Enter Project name: InboxMessageExample
Package: com.listviewwithdb
Keep other default selections, click Next until you reach Finish

                                    


Copy and Past the following code in the MainActivity.java
package com.listviewwithdb;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    ListView phoneBook;
    Context context;
    TextView txt_SMSSend;
    TextView txt_MsgBody;
    Cursor cursor;
    String[] arrayBody;
    int[] arrayID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context =this;

        phoneBook = (ListView)findViewById(R.id.listViewSMS);
        arrayBody = new String[]{"address","body"};
        arrayID = new int[]{R.id.textSMSSend,R.id.textMsgBody};

        cursor = getContentResolver().query(Uri.parse("content://sms/inbox"),null,null,null,null);
        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,R.layout.content_main,cursor,arrayBody,arrayID);
        Log.v("add","add"+simpleCursorAdapter);
        phoneBook.setAdapter(simpleCursorAdapter);
        Log.v("Phone","Phone"+phoneBook);

        phoneBook.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            txt_SMSSend = (TextView)view.findViewById(R.id.textSMSSend);
            txt_MsgBody = (TextView)view.findViewById(R.id.textMsgBody);
            String smsSend = txt_SMSSend.getText().toString();
            String msgBody = txt_MsgBody.getText().toString();

                final AlertDialog dialog = new AlertDialog.Builder(context).create();
                dialog.setTitle("SMS Form:"+smsSend);
                dialog.setIcon(android.R.drawable.ic_dialog_info);
                dialog.setMessage(msgBody);
                dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        return;
                    }
                });
                dialog.show();
            }
        });
    }
}
Copy and Past the following code in the layout file called activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D1FFFF"
    tools:context="com.listviewwithdb.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listViewSMS"
        android:dividerHeight="0.1dp"
        android:divider="#0000CC" />
</RelativeLayout>



 Copy and Past the following code in the
Manifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.listviewwithdb">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Copy and Past the following code in the layout file called item_data.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:id="@+id/textSMSSend"
        android:paddingLeft="2dp"
        android:textStyle="bold"
        android:textSize="20dp"
        android:textColor="#0000FF"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:id="@+id/textMsgBody"
        android:paddingLeft="2dp"
        android:textStyle="bold"
        android:layout_below="@+id/textSMSSend"
        android:textSize="20dp"
        android:textColor="#5C002C"/>
</RelativeLayout>


Run Your Project as the below by clicking on shift+10 or like the below-->Android Application and observe the output
 
Output:

                        
 Note:

Here iam not displaying Other screen of the out put because of security reasons, because i do not want expose my messages

This Example will works on the devices(mobiles) and if the messages are there in the emulators our application also works in emulator.
  

Please Send Your Comments To ambilpura.sunil@gmail.com


Stay Tune For Next Tutorial... In Android:

Saturday, 13 February 2016

Android Programming Tutorial 65: Custom Progress Bar and Downloading Image Example in Android Studio

Progress Bar In Android:

Has name implies Progress Bar means to progress the work done.In General if you are downloading the .jpge or .png or any video file file from the Network there you want to know the work progress like was its work is getting made.

This work can be display in terms of Bar, is Called Progress Bar, once the Progress starts our application value will get changed.

Progress Bar will show like 10,20,30,40,50,60,70,80,90,100 the default value is 100
its can not be 10,20,......100  it can be 10, 15, 21, 30, 44, 57,....81,97,100 based on the programmer choice that we will see in details with example...


Custom Progress Bar Example in Android:

File >> New >> Android Application
Enter Project name: CustomProgressBarAndDownloadImageExample
Package: com.example.customprogressbardownloadimageexample
Keep other default selections, click Next until you reach Finish

                                     


Copy and Past the following code in the MainActivity.java
package com.example.customprogressbardownloadimageexample;

import java.io.BufferedInputStream;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ProgressbarActivity extends Activity {

int nProgress;
ProgressBar progressBar;
ProgressBar progressBarone;
TextView textview;
Button btn_Show, btn_Download;
private ProgressDialog progressDialog;
ImageView iv_Image;

public static final int CUSTOM_PROGRESS_DIALOG = 0;


private static String photoURL = "http://www.gettyimages.ca/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg";


@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progressbar);
textview = (TextView) findViewById(R.id.textView);
btn_Show = (Button) findViewById(R.id.button1);
btn_Download = (Button) findViewById(R.id.button2);
iv_Image = (ImageView) findViewById(R.id.my_image);
progressBarone = (ProgressBar) findViewById(R.id.progressBar2);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);

progressBarone.setVisibility(View.INVISIBLE);

progressBar.setProgress(0);
progressBar.setSecondaryProgress(0);
}

public void button_click(View view) {

switch (view.getId()) {
case R.id.button1:
new ShowCustomProgressBarAsyncTask().execute();
progressBarone.setVisibility(View.VISIBLE);

break;

case R.id.button2:
new DownloadFileFromURL().execute(photoURL);
break;
}
}
public class ShowCustomProgressBarAsyncTask extends
AsyncTask<Void, Integer, Void> {

int nProgress;


@Override

protected void onPostExecute(Void result) {
textview.setText("Finish work with custom ProgressBar");
btn_Show.setEnabled(true);
progressBarone.setVisibility(View.INVISIBLE);
}

@Override

protected void onPreExecute() {
btn_Show.setEnabled(false);
textview.setText("Start work with custom ProgressBar");
nProgress = 0;
progressBar.setSecondaryProgress(0);
}

@Override

protected Void doInBackground(Void... params) {
while (nProgress < 100) {
nProgress++;
publishProgress(nProgress);
SystemClock.sleep(100);
}
return null;
}

@Override

protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
progressBar.setSecondaryProgress(values[0] + 5);
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CUSTOM_PROGRESS_DIALOG:
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading file. Please wait...");
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressDrawable(getResources().getDrawable(
R.drawable.custom_progress_bar_horizontal));
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
return progressDialog;
default:
return null;
}
}
              class DownloadFileFromURL extends AsyncTask<String, String, String> {
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(CUSTOM_PROGRESS_DIALOG);
}
              @Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
OutputStream output = new FileOutputStream(
"/sdcard/photo.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... value) {
progressDialog.setProgress(Integer.parseInt(value[0]));
progressDialog.setSecondaryProgress(Integer.parseInt(value[0]) + 5);
}
@SuppressWarnings("deprecation")
@Override
protected void onPostExecute(String file_url) {
dismissDialog(CUSTOM_PROGRESS_DIALOG);
String imagePath = Environment.getExternalStorageDirectory()
.toString() + "/photo.jpg";
iv_Image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}

 Copy and Past the following code in the layout file called activity_main.xml

<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" 
    android:gravity="center">

<Button
   android:id="@+id/button1"
   android:layout_width="244dp"
   android:layout_height="wrap_content"
   android:layout_margin="5dip"
   android:layout_marginBottom="2dp"
   android:background="@android:color/white"
   android:onClick="button_click"
   android:text="Start Progress"
   android:textColor="@android:color/black" />

<ProgressBar
   android:id="@+id/progressBar1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" 
style="@style/CustomProgressBar"  
android:layout_margin="5dip" />

<ProgressBar
   android:id="@+id/progressBar2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
        android:indeterminateDrawable="@drawable/my_progress_indeterminate"
android:layout_margin="5dip"/>
<TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:gravity="center"
        android:text=""
android:layout_margin="5dip"
android:textColor="#48D1CC"
android:textSize="18dp"/>

<Button
   android:id="@+id/button2"
   android:layout_width="247dp"
   android:layout_height="wrap_content"
   android:layout_margin="5dip"
   android:layout_marginBottom="20dp"
   android:background="#FFFFFF"
   android:onClick="button_click"
   android:text="Download Started"
   android:textColor="@android:color/black" />

<!-- Image view to show image after downloading -->
    <ImageView android:id="@+id/my_image"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>



 Copy and Past the following code in the style.xml  Located in values folder res>>values>>style.xml
<resources>
   <style name="CustomProgressBar"                                                                                                        parent="android:Widget.ProgressBar.Horizontal">
  <item name="android:indeterminateOnly">false</item>
  <item                                                                                                                                                                                                           
name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
 <item name="android:minHeight">10dip</item>
 <item name="android:maxHeight">20dip</item>
</style>
<style name="AppTheme" parent="android:Theme.Light" />

</resources>



Create 

custom_progressbar.xml

 file in drawable folder of res and Copy and Past the following code 








<?xml version="1.0" encoding="UTF-8"?>



<!--  @author : @alexduhem 

blog.sakaroz.com
 -->
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@android:id/background">
<shape>
<corners
android:radius="5dip" />
<gradient
android:startColor="#ffffffff"
android:centerColor="#ffdddddd"
android:centerY="0.50"
android:endColor="#ffffffff"
android:angle="270" />
</shape>
</item>
<item
android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners
android:radius="5dip" />
<gradient
android:startColor="#770e75af"
android:endColor="#771997e1"
android:angle="90" />
</shape>
</clip>
</item>
<item
android:id="@android:id/progress">
<clip>
<shape>
<corners
android:radius="5dip" />
<gradient
android:startColor="#ff0e75af"
android:endColor="#ff1997e1"
android:angle="90" />
</shape>
</clip>
</item>
</layer-list>



Create progress_indeterminate.xml  xml file Copy and Past the following code

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android" 
    android:drawable="@drawable/loading" 
    android:pivotX="50%"
android:pivotY="50%" />

 Copy and Past the following code in the Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.customprogressbardownloadimageexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" /> 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ProgressbarActivity"
            android:label="@string/title_activity_progressbar"
            android:theme="@android:style/Theme.Holo" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Note: past one images in the drawable folder of your choice i copied  images named 

Run Your Project as the below by clicking on shift+10 or like the below-->Android Application and observe the output


    
OutPut:

When you click on the Start Progress button as shown in the images custom progress bar will start and there also a text will display as start work with custom progressbar

Now if you click on the second button download started button a progress bar will display and image will downloaded and displayed down
Finally:

 

Please Send Your Comments To ambilpura.sunil@gmail.com

 
 
Stay Tune For Next Tutorial...Displaying All Messages From Mobile Inbox Example In Android:

Wednesday, 10 February 2016

Android Programming Tutorial 64: CardView Example in Android Studio

CardView In Android:

CardView as the name implies cardview a type of widget introduce for  Lollipop (Android 5.0 API Level 21), CardView  seems like a card which allow us to incript the data on to it,
Example: A marriage Wedding card, is a card where we can see the incript data on to it.

 


CardView Example in Android:

File >> New >> Android Application
Enter Project name: CardViewExample
Package: cardviewexample.kdms.com.cardviewexample
Keep other default selections, click Next until you reach Finish

                                    

  Add Following jar in build.gradle display below in the
 dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.0'
    compile 'com.android.support:cardview-v7:23.0.1' 
}

Copy and Past the following code in the MainActivity.java

package cardviewexample.kdms.com.cardviewexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private CardView cardView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cardView = (CardView)findViewById(R.id.cardView);
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Yout Clicked On CardView", Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
 Copy and Past the following code in the layout file called activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:id="@+id/cardView"
    card_view:contentPaddingTop="20dp"
    card_view:contentPaddingBottom="20dp"
    card_view:contentPaddingLeft="20dp"
    card_view:contentPaddingRight="20dp"
    card_view:cardBackgroundColor="#91B2DE"
    card_view:cardUseCompatPadding="true"
    card_view:cardCornerRadius="10dp"
    android:layout_margin="20dp"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:id="@+id/iv_cardView"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:layout_centerVertical="true"
            android:src="@mipmap/andi"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="sunil@gmail.com"
            android:layout_marginLeft="10dp"
            android:id="@+id/tv_CardView"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/iv_cardView"
            android:textColor="#222"
            android:textSize="15sp"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Sunil Kumar"
            android:layout_above="@+id/tv_CardView"
            android:layout_marginLeft="10sp"
            android:id="@+id/tvName"
            android:layout_toRightOf="@+id/iv_cardView"
            android:layout_centerVertical="true"
            android:textColor="#222"
            android:textSize="15sp" />
    </RelativeLayout>
</android.support.v7.widget.CardView>

 Copy and Past the following code in the Manifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cardviewexample.kdms.com.cardviewexample" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


Run Your Project as the below by clicking on shift+10 or like the below-->Android Application and observe the output
      
OUTPUT: 

Please Send Your Comments To ambilpura.sunil@gmail.com

 Stay Tune For Next Tutorial... Custom Progress Bar and Downloading Image Example in Android StudioIn Android: