Thursday, November 28, 2013

Button click play sound in android

Layout:

<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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="106dp"
        android:layout_marginTop="86dp"
        android:text="Button" />

</RelativeLayout>

MainActivity:-


import com.example.abc.R;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    MediaPlayer mp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   
       
       
        Button one=(Button)findViewById(R.id.button1);
         mp=MediaPlayer.create(this,R.raw.whoseur);
         one.setOnClickListener(new OnClickListener() {
           
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mp.start();
               
            }
        });
       
       
       
    }

   

}

sending mail in android phone to any type of mail account code:-

Layout:-
<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" >

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

MainActivity are:-


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         Intent emailIntent=new Intent(Intent.ACTION_SEND);

            String subject = "Hi!";
            String body = "hello from android....";

            String[] extra = new String[]{"aaa@bbb.com"};
            emailIntent.putExtra(Intent.EXTRA_EMAIL, extra);

            emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
            emailIntent.putExtra(Intent.EXTRA_TEXT, body);
            emailIntent.setType("message/rfc822");

            startActivity(emailIntent);}

   

}





Thank u Friends For seeing code....

Wednesday, November 13, 2013

Playing video from url to android cellphone simplest example

Code:-

package com.example.videoplaying;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = " httpxyz.mp4";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str)));

}
});


}
}


XML file:-

<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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="77dp"
        android:layout_marginTop="58dp"
        android:text="Button" />

</RelativeLayout>

Capture an image using camera in android

code :-
main activity:-

package com.example;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;

public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

preview = new Preview(this);
((FrameLayout) findViewById(R.id.preview)).addView(preview);

buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});

Log.d(TAG, "onCreate'd");
}


ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};

/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};

/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
outStream = new FileOutputStream(String.format("/sdcard/amit/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};

}
class:- preview:-

package com.example;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";

    SurfaceHolder mHolder;
    public Camera camera;
   
    Preview(Context context) {
        super(context);
       
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
        camera = Camera.open();
        try {
camera.setPreviewDisplay(holder);


camera.setPreviewCallback(new PreviewCallback() {

public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        // Because the CameraDevice object is not a shared resource, it's very
        // important to release it when the activity is paused.
        camera.stopPreview();
        camera = null;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // Now that the size is known, set up the camera parameters and begin
        // the preview.
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(w, h);
        camera.setParameters(parameters);
        camera.startPreview();
    }

    @Override
    public void draw(Canvas canvas) {
    super.draw(canvas);
    Paint p= new Paint(Color.RED);
    Log.d(TAG,"draw");
    canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2, p );
    }
}


XML:-
<?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:id="@+id/layout">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Camera Demo"
android:textSize="24sp" />

<FrameLayout android:id="@+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</FrameLayout>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/buttonClick"
android:text="Click" android:layout_gravity="center"></Button>

</LinearLayout>
manifest:-

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








What, Where and Why?


what is android
Android is a software package and linux based operating system for mobile devices such as tablet computers and smartphones.

It is developed by Google and later the OHA (Open Handset Alliance). Java language is mainly used to write the android code even though other languages can be used.

The goal of android project is to create a successful real-world product that improves the mobile experience for end users.

What is Open Handset Alliance (OHA) ?

oha
It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI, Garmin, Teleca, Ebay, Intel etc.

It was established on 5th November, 2007, led by Google. It is commited to advance open standards, provide services and deploy handsets using the Android Plateform.

Features of Android

There are many advantages of android. They are as follows:

It is open-source.
Anyone can customize the Android Platform.
There are a lot of mobile applications that can be choosen by the consumer.
It provides many interesting features like weather details, opening screen, live RSS (Really Simple Syndication) feeds etc.
It provides support for messaging services(SMS and MMS), web browser, storage (SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.
Categories of Android applications

what is android
There are many android applications in the market. The top categories are:

Entertainment
Tools
Communication
Productivity
Personalization
Music and Audio
Social
Media and Video
Travel and Local etc.








Tuesday, November 12, 2013

java security Threats :-


Warning to anyone still using Java 6: Upgrade now to Java 7 to avoid being compromised by active attacks.
That alert came via F-Secure anti-malware analyst Timo Hirvonen, who reported finding an in-the-wild exploit actively targeting an unpatched vulnerability in Java 6 following the recent publication of related proof-of-concept (POC) attack code. The Java run time environment (JRE).


Pointer in java:-


Questen is that .in java there is pointer?
many ways and many peoples are says that in java there is not pointer but i m saying that there is a pointer :-because of object.
ex:-


Libraryes.....................
{

class abc
{
int a,b,c;
c=a*b;
System.out.println(c"there is result");
}
public static void main(String s[])
{
abc a=new abc(10,20);
/*there is working of pointer class abc there is creating an object of a where value of object passed now we can use a any where........*/
}
}

Version History in java

There are many java versions that has been released.

JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997)
J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004)
Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011)

Preference in android how that working

In preference there we can add sum advantages in his app .in Android   Application there are there is a very great and useful .that's by we can make in each and every apps any how 4 or 5 activity we can make ..that's very easy to make...
in preference there we have to store data ....
Example:-

first time we play a game and we make a score that is 10,000 and we stop that
again next day we play that game and then either our game will start from pose position or either restart and the score will store in internal memory

these are the thing these we can invert in preference

What is Preference:-
1:- Set user name
2:-Update stings
3:-Send Crash Report
4:- Sync Frequency
5:- User name
6:-Password

Monday, November 11, 2013

External Storage of Data in android

External(In Sd card )storage of data:-


package com.example.externalstorage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText editTextFileName,editTextData;
Button saveButton,readButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editTextFileName=(EditText)findViewById(R.id.editText1);
editTextData=(EditText)findViewById(R.id.editText2);
saveButton=(Button)findViewById(R.id.button1);
readButton=(Button)findViewById(R.id.button2);

saveButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString();
String data=editTextData.getText().toString();

FileOutputStream fos;
  try {
  File myFile = new File("/sdcard/"+filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
 
   Toast.makeText(getApplicationContext(),filename + " saved",Toast.LENGTH_LONG).show();
 
 
  } catch (FileNotFoundException e) {e.printStackTrace();}
  catch (IOException e) {e.printStackTrace();}

}

});

readButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString();
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/sdcard/"+filename);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));

while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
 
} catch (IOException e) {
   e.printStackTrace();
}
Toast.makeText(getApplicationContext(),aBuffer,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.activity_main, menu);
return true;
}

}






activity.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"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="20dp"
        android:layout_marginTop="24dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="24dp"
        android:ems="10" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editText1"
        android:layout_alignBottom="@+id/editText1"
        android:layout_alignParentLeft="true"
        android:text="File Name:" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editText2"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignParentLeft="true"
        android:text="Data:" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginLeft="70dp"
        android:layout_marginTop="16dp"
        android:text="save" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/button1"
        android:text="read" />

</RelativeLayout>




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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

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

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

</manifest>



Internal storage of data in android


There are so sum types of storage of data ways :-
internal storage,External Storage(SD Card),URL storage on web,Sqlite ....etc SQl........

1:-internal storage of data in android Device not in SD card

package com.example.internalstorage;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText editTextFileName,editTextData;
Button saveButton,readButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editTextFileName=(EditText)findViewById(R.id.editText1);
editTextData=(EditText)findViewById(R.id.editText2);
saveButton=(Button)findViewById(R.id.button1);
readButton=(Button)findViewById(R.id.button2);

saveButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString();
String data=editTextData.getText().toString();

FileOutputStream fos;
  try {
   fos = openFileOutput(filename, Context.MODE_PRIVATE);
   fos.write(data.getBytes());
   fos.close();
 
   Toast.makeText(getApplicationContext(),filename + " saved",Toast.LENGTH_LONG).show();
 
 
  } catch (FileNotFoundException e) {e.printStackTrace();}
  catch (IOException e) {e.printStackTrace();}

}

});

readButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString();
StringBuffer stringBuffer = new StringBuffer();
try {
   BufferedReader inputReader = new BufferedReader(new InputStreamReader(
           openFileInput(filename)));
   String inputString;
               
   while ((inputString = inputReader.readLine()) != null) {
       stringBuffer.append(inputString + "\n");
   }
 
} catch (IOException e) {
   e.printStackTrace();
}
Toast.makeText(getApplicationContext(),stringBuffer.toString(),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.activity_main, menu);
return true;
}

}




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"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="20dp"
        android:layout_marginTop="24dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="24dp"
        android:ems="10" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editText1"
        android:layout_alignBottom="@+id/editText1"
        android:layout_alignParentLeft="true"
        android:text="File Name:" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editText2"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignParentLeft="true"
        android:text="Data:" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginLeft="70dp"
        android:layout_marginTop="16dp"
        android:text="save" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/button1"
        android:text="read" />

</RelativeLayout>



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

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

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

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

</manifest>









                               Just click on save button then there will generate a toast of message your data has been                                     store or not ............

 Final result generate over there in Particular File name

open data base from sqlite Database in android

CopyDbActivity.java


package amitsharma.opendatabase.com;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.example.opendatabase.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CopyDbActivity extends Activity {
    /** Called when the activity is first created. */
Cursor c=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        ((Button)findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {

     
        DatabaseHelper myDbHelper = new DatabaseHelper(CopyDbActivity.this);
        try {

        myDbHelper.createDataBase();

  } catch (IOException ioe) {

  throw new Error("Unable to create database");

  }

  try {

  myDbHelper.openDataBase();

  }catch(SQLException sqle){

  throw sqle;

  }
  Toast.makeText(CopyDbActivity.this, "Success", Toast.LENGTH_SHORT).show();

 

  c=myDbHelper.query("EMP_TABLE", null, null, null, null,null, null, null,null, null
 
  ,null,null, null
 
  );
  if(c.moveToFirst())
            {
                do {
           
                Toast.makeText(CopyDbActivity.this,
                            "_id: " + c.getString(0) + "\n" +
                            "E_NAME: " + c.getString(1) + "\n" +
                            "E_AGE: " + c.getString(2) + "\n" +
                            "E_DEPT:  " + c.getString(3),
                            Toast.LENGTH_LONG).show();
               
                } while (c.moveToNext());
            }
}
});
     
             
     
    }
}


DatabaseHelper.java


package amitsharma.opendatabase.com;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;



import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    String DB_PATH =null;

    private static String DB_NAME = "extenalDB";

    private SQLiteDatabase myDataBase;
 
    private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DatabaseHelper(Context context) {

    super(context, DB_NAME, null, 1);
        this.myContext = context;
        DB_PATH="/data/data/"+context.getPackageName()+"/"+"databases/";
    }

  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
    //do nothing - database already exist
    }else{

    //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();

        try {

    copyDataBase();

    } catch (IOException e) {

        throw new Error("Error copying database");

        }
    }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
    String myPath = DB_PATH + DB_NAME;
    checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

    //database does't exist yet.

    }

    if(checkDB != null){

    checkDB.close();

    }

    return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
    myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

    }

    public void openDataBase() throws SQLException{

    //Open the database
        String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
public synchronized void close() {

       if(myDataBase != null)
       myDataBase.close();

       super.close();

}
 


@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
 //return cursor
public Cursor query(String table,String[] columns, String selection,String[] selectionArgs,String groupBy,String having,String[] orderBy,String youare,String myname, Object object, Object object2, Object object3, Object object4){
return myDataBase.query("EMP_TABLE", null, null, null, null, null, null, null);


}


}




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=".CopyDbActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="93dp"
        android:text="open" />

</RelativeLayout>



manifestfile:-


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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="amitsharma.opendatabase.com.CopyDbActivity"
            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="amitsharma.opendatabase.com.DatabaseHelper"
                  android:label="@string/app_name">
        </activity>
        
    </application>

</manifest>




Friday, October 25, 2013

TextView in android:-

TextView can only display result as txt type of value.as well as String .that sit.

It's also use for know and required sum info which is hidden
Ex:-
<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" >
 <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" />

     <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click on the Button to change this text" />
   
</RelativeLayout>



MainActivity:-

package com.AmitSharma.textview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
 Button button = (Button) findViewById(R.id.bt);  
button.setOnClickListener(new View.OnClickListener() {
          
           @Override
           public void onClick(View v) {
               // TODO Auto-generated method stub
              
               //Creating TextView Variable
               TextView text = (TextView) findViewById(R.id.tv);
              
               //Sets the new text to TextView (runtime click event)
               text.setText("You Have click the button");
           }
       });
  
   }
}

......................................................................................................................................................................................................................................................................................................................................


u can also give on there styles of text 
ex:-

<style name="TransparentActivity" >
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowAnimationStyle">@android:style/Animation</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowFullscreen">false</item>
</style>




.............thank to u friends .............Look more again nd again .......... 

Thursday, October 24, 2013

First Activity in android TextView:-

first activity:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I&apos;m screen 1 (main.xml)"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click me to another screen" />
 
</LinearLayout>

second activity:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I&apos;m screen 2 (main2.xml)"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</LinearLayout>

 Intent intent = new Intent(context, anotherActivity.class);
    startActivity(intent);
MainActivity:-
 
public class AppActivity extends Activity {
 
 Button button;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  addListenerOnButton();
 }
 
 public void addListenerOnButton() {
 
  final Context context = this;
 
  button = (Button) findViewById(R.id.button1);
 
  button.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View arg0) {
 
       Intent intent = new Intent(context, App2Activity.class);
                            startActivity(intent);   
 
   }
 
  });
 
 }
 
}
ActivitySecond:-

public class App2Activity extends Activity {
 
 Button button;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main2);
 }
 
}

in manifeast you shuld Append :-to go to second activity

 <activity
            android:label="@string/app_name"
            android:name=".SecondActivity" >
        </activity>