Thursday 14 March 2013

How to Read PDF files in Android?

Read PDF Files from Sdcard in Android

First Create one Android Project in Eclipse after that download PDFViewer.jar file from Internet and then add into project's build path.

After Create one Activity in this Project, Name is Second.java

Second.java

public class Second extends PdfViewerActivity {
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    }
   
    public int getPreviousPageImageResource() {
    return R.drawable.left_arrow;
    }
   
    public int getNextPageImageResource() {
    return R.drawable.right_arrow;
    }
   
    public int getZoomInImageResource() {
    return R.drawable.zoom_in;
    }
   
    public int getZoomOutImageResource() {
    return R.drawable.zoom_out;
    }
   
    public int getPdfPasswordLayoutResource() {
    return R.layout.pdf_file_password;
    }
   
    public int getPdfPageNumberResource() {
    return R.layout.dialog_pagenumber;
    }
   
    public int getPdfPasswordEditField() {
    return R.id.etPassword;
    }
   
    public int getPdfPasswordOkButton() {
    return R.id.btOK;
    }
   
    public int getPdfPasswordExitButton() {
    return R.id.btExit;
    }
   
    public int getPdfPageNumberEditField() {
    return R.id.pagenum_edit;
    }
}

After that Add below code into your project's main activity and change extends Activity to ListActivity in your java file.

First.java

public class First extends ListActivity {
   
    String[] pdflist;
    File[] imagelist;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.main);
   
    File images = Environment.getExternalStorageDirectory();
    imagelist = images.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
    return ((name.endsWith(".pdf")));
    }
    });
    pdflist = new String[imagelist.length];
    for (int i = 0; i < imagelist.length; i++) {
    pdflist[i] = imagelist[i].getName();
    }
    this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pdflist));
    }
   
    protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    String path = imagelist[(int) id].getAbsolutePath();
    openPdfIntent(path);
    }
   
    private void openPdfIntent(String path) {
    try {
    final Intent intent = new Intent(First.this, Second.class);
    intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
    startActivity(intent);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
}

And Don't Forget to Add Second Activity in Android Manifest file.

Enjoy :--)

Monday 7 January 2013

Custom Toast in Android

First Create New Android Project and after that add below xml file in res/layout folder and add below code into your MainActivity.java file.

toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:background="#ffffff" >
        
    <ImageView android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="10dp" />

    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#FFF" />
    
</LinearLayout>

Add below code into your MainActivity.java file

MainActivity.java

LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
 
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello! This is a custom toast!");
 
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

Enjoy  :-)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

How To Send Email In Android

Write below code into your activity file for send Email from Android Application.

Java Code:-


Intent mAndroidEmailIntent = new Intent (android.content.Intent.ACTION_SEND);
String aEmailList[] = { "android@gmail.com","android@yahoomail.com" };
mAndroidEmailIntent.putExtra (android.content.Intent.EXTRA_EMAIL, aEmailList);
mAndroidEmailIntent.putExtra (android.content.Intent.EXTRA_SUBJECT, "Mail Subject");
mAndroidEmailIntent.setType ("plain/text");
mAndroidEmailIntent.putExtra (android.content.Intent.EXTRA_TEXT, "Email From My Android App");
startActivity (mAndroidEmailIntent);

Enjoy :-)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Saturday 24 November 2012

Android Development – Customize Android Fonts

First Create New Android Project and after that add "DroidSansFallback.ttf" file into assets folder.

After that put below code into activity_main.xml file and MainActivity.java file

activity_main.xml


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Dipak Keshariya"
        android:id="@+id/TextView1" />

</LinearLayout>


MainActivity.java

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        // text view label
        TextView mTextView1 = (TextView) findViewById(R.id.TextView1);

        // Loading Font Face
        Typeface tf = Typeface.createFromAsset(getAssets(), "DroidSansFallback.ttf");

        // Applying font
        mTextView1.setTypeface(tf);
    }
}

Download Full Source Code from below link.

Customize Android Fonts

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Monday 27 August 2012

Multiple Android Activities in a TabActivity

Project Name:- Tab_Sample
Package Name:- com.android.tabsample
Target SDK:- Android 2.2 (API 8)

Create below 5 classes under the "com.android.tabsample" package.

ActivityStack.java


public class ActivityStackHome extends ActivityGroup {
    private Stack<String> stack;

    @Override
    public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null)
stack = new Stack<String>();
// start default activity
push("FirstStackActivity", new Intent(this, Tab_SampleActivity.class));
    }

    @Override
    public void finishFromChild(Activity child) {
pop();
    }

    @Override
    public void onBackPressed() {
pop();
    }

    public void push(String id, Intent intent) {
  Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        if (window != null) {
            stack.push(id);
setContentView(window.getDecorView());
}
    }

    public void pop() {
  if (stack.size() == 1)
            finish();
        LocalActivityManager manager = getLocalActivityManager();
  manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent();
            Window newWindow = manager.startActivity(stack.peek(), lastIntent);
            setContentView(newWindow.getDecorView());
        }
    }
}


TabActivity.java


public class TabActivity extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_screen);
TabHost tabHost = getTabHost();
Intent intent = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.home));
spec.setContent(intent);

tabHost.addTab(spec);

Intent intent1 = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec1 = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.invoice));
spec1.setContent(intent1);
tabHost.addTab(spec1);

tabHost.setCurrentTab(0);
    }
}


FirstActivity.java


public class FirstActivity extends Activity {
  @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("Tab Sample Activity ");
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), SecondActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("SecondActivity", intent);
}
});
 
        setContentView(textView);
  }
}


SecondActivity.java


public class SecondActivity extends Activity {
    @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("First Stack Activity ");
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), ThirdActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("ThirdActivity", intent);
            }
        });
 
        setContentView(textView);
    }
}


ThirdActivity.java


public class ThirdActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
    }
}


Add Below XML files into your res/layout folder.

1) tab_screen.xml


<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="3dp" >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_above="@android:id/tabs"
            android:layout_weight="1" />

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" />
    </RelativeLayout>

</TabHost>


2) main.xml


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>


AndroidManifest.xml:-


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

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".FirstActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".TabActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ActivityStack"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SecondActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ThirdActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Download Full Source Code from below link.

Android Bottom Tab Example

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Thursday 21 June 2012

Voice Recording in Android

Put below code into your main Activity.

private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonHandlers();
enableButtons(false);
setFormatButtonCaption();
}

private void setButtonHandlers() {
    ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
}

private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}

private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnFormat, !isRecording);
enableButton(R.id.btnStop, isRecording);
}

private void setFormatButtonCaption() {
((Button) findViewById(R.id.btnFormat)).setText(getString(R.string.audio_format) + " (" + file_exts[currentFormat] + ")");
}

private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}

private void startRecording() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void stopRecording() {
  if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}

private void displayFormatDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = { "MPEG 4", "3GPP" };
builder.setTitle(getString(R.string.choose_format_title)).setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
setFormatButtonCaption();
dialog.dismiss();
}
}).show();
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
  @Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(AudioRecordingActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
    }
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(AudioRecordingActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};

private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
        switch (v.getId()) {
          case R.id.btnStart: {
             Toast.makeText(AudioRecordingActivity.this, "Start Recording", Toast.LENGTH_SHORT).show();
                enableButtons(true);
             startRecording();
             break;
          }
          case R.id.btnStop: {
             Toast.makeText(AudioRecordingActivity.this, "Stop Recording", Toast.LENGTH_SHORT).show();
             enableButtons(false);
             stopRecording();
             break;
          }
          case R.id.btnFormat: {
             displayFormatDialog();
             break;
          }
       }
    }
};


Main.xml File:-


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="20dip">
 
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:scaleType="fitCenter"/>
 
        <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_info"
        android:layout_weight="1.0"
        android:textSize="20dip"/>
     
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
     
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnStart"
                android:text="@string/start_recording"
                android:layout_weight="1.0"/>
             
                <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnStop"
                android:text="@string/stop_recording"
                android:layout_weight="1.0"/>
             
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnFormat"
                android:text="Format (mp4)"
                android:layout_weight="1.0"/>
     
    </LinearLayout>
</LinearLayout>


Add Below Permissions to manifest.xml file.

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

Download Full Source Code from below link.

Voice Recording in Android

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

Play Online Video in Android Device

Put Below Code into your Application.

MainActivity.java File:-

public class MainActivity extends Activity {
public static String url = "rtsp://v3.cache8.c.youtube.com/CiILENy73wIaGQmXovF6e-Rf-BMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp";
private VideoView videoView = null;
private ProgressBar prog = null;
private Context ctx = null;
private MediaController mediaController = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.main);
ctx = this;
prog = (ProgressBar) findViewById(R.id.prog);
videoView = (VideoView) findViewById(R.id.video);
Uri video = Uri.parse(url);
mediaController = new MediaController(this);
  mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);

videoView.setOnErrorListener(new OnErrorListener() {

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Error occured", 500).show();
return false;
}
});

videoView.setOnPreparedListener(new OnPreparedListener() {

public void onPrepared(MediaPlayer arg0) {
prog.setVisibility(View.GONE);
videoView.start();
}
});
}

@Override
protected void onDestroy() {
try {
videoView.stopPlayback();
} catch (Exception e) {
//
}
super.onDestroy();
}
}


Main.xml File:-

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

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <VideoView
            android:id="@+id/video"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />

        <ProgressBar
            android:id="@+id/prog"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_gravity="center" />
    </FrameLayout>

</LinearLayout>


And Give Below Permission into your Manifest.xml file.

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

Enjoy:--)

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.