Sunday, September 10, 2017
Sunday, September 18, 2016
Memory and Memory Management in Java/Android
There are three type of physical memory in android.
There are three type of physical memory in android.
- RAM - Random Accessed Memory - When running an application on your phone, the application is loaded from your device memory into the RAM, just like on a computer, the main purpose for this is access speed is far greater in RAM. You can clear the apps that is in the RAM on your phone depending on your smartphone (Samsung for example hold home button down and click ram manager > clear RAM - this will clear what's in RAM however most background apps will automatically be loaded back into the RAM hence the free space decreasing straight away
- As you mentioned SD Card is a external memory card which you can switch and swap with a variety of different sizes if needed
- Device Memory is your phones built in memory, just like SD Card has memory however this one cannot be swapped or taken out of the phone. It will hold all of your phones files that make it work, just like a PC, as standard you cannot edit these files as they are read only, however through rooting your phone you may access these files and change if needed.To understand the memory concept and memory management you have to understand how JVM provide the memory to your code.Mainly Java code is stored in the Heap and Stack memory. The main difference between heap and stack is that stack memory is used to store local variables and function call while heap memory is used to store objects in Java. No matter, where the object is created in code e.g. as a member variable, local variable or class variable, they are always created inside heap space in Java.All the local variables and method calling is in stack, If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space.If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is a lot lesser than the size of heap memory in Java.Variables stored in stacks are only visible to the owner Thread while objects created in the heap are visible to all thread. In other words, stack memory is kind of private memory of Java Threads while heap memory is shared among all threads.
What is a memory leak?
Some objects have a limited lifetime. When their job is done, they are expected to be garbage collected. If a chain of references holds an object in memory after the end of its expected lifetime, this creates a memory leak. When these leaks accumulate, the app runs out of memory.For instance, after Activity.onDestroy() is called, the activity, its view hierarchy and their associated bitmaps should all be garbage collectable. If a thread running in the background holds a reference to the activity, then the corresponding memory cannot be reclaimed. This eventually leads to an OutOfMemoryError crash.
How do I avoid memory leaks? - Avoid passing Context objects further that your activity or fragment
- NEVER make/store a Context or View in a static variable. This is the first sign of a memory leak.
- private static TextView textView; //DO NOT DO THIS // private static Context context;
- Always unregister listeners in your onPause()/ onDestroy() methods. This includes Android listeners, to things such as Location services or display manager services and your own custom listeners.
- Don’t store strong references to activities in your AsyncTasks or background threads. Your activity may get closed, but your AsyncTask will continue execution and hold onto that reference of your activity.
- Use Context-application (getApplicationContext()) instead of Context from an activity if you can.
- Try not to use non-static inner classes if you can avoid it. Storing reference to something like an Activity or View inside this can lead to memory leaks. Use WeakReference if you need to store reference to them.
- Never give image in src in xml for preview, use instead tools:src for preview. It will take image for preview only but android:src loads image in memory, so that create a memory blocker if heavy image is used.
Saturday, January 31, 2015
2D ARRAY
Declaration :--
datatype arr[][];or
datatype [][]arr;
int a[][];
Memory Allocation:--
arr = new datatype[rowwise][colum wise];
a = new int [3][4];
marks = new int[25][5];
scales = new float[10][4];
int[][] = new int [3][4];
INITIALIZATION:--
int a[][] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
1 2 3 4
5 6 7 8
9 10 11 12
SHORTING IN JAVA
SHORTING
1.)Selection Sort:--
class sel Shot
{
public static void main(string args[]){
int a[] = { };
int i,j.t;
int n= a.length;
system.out.println("Array");
for(i=0; i<n; i++)
{
system.out.println(a[i] + "\t")
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(a[i] > a[j])
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
System.out.println("\n shorted list");
for(i=o; i<n; i++)
system.out.print( a[i] + "\t");
}
}
}
system.out.println("\n shorted array")
for(i=o; i<n; i++)
system.out.print(a[i]+ "\t");
}
}
}
2.) Insertion Short:--
class inser Shot
{
public static void main(string args[]){
int a[] = { };
int i,j.t;
int n= a.length;
system.out.println("Array");
for(i=0; i<n; i++)
{
system.out.println(a[i] + "\t")
}
for(i=0; i<n; i++)
{
for(j=i; j<0; j--)
{
if(a[j-1] > a[j])
{
t = a[j-1];
a[j-1] = a[j];
a[j] = t;
}
}
}
system.out.println("\n shorted array")
for(i=o; i<n; i++)
system.out.print(a[i]+ "\t");
}
}
}
system.out.println("\n shorted array")
for(i=o; i<n; i++)
system.out.print(a[i]+ "\t");
}
}
}
2.) Bubble Short:--
class bub Shot
{
public static void main(string args[]){
int a[] = { };
int i,j.t;
int n= a.length;
system.out.println("Array");
for(i=0; i<n; i++)
{
system.out.println(a[i] + "\t")
}
for(i=0; i<n; i++)
{
for(j=0; j<n-1; j++)
{
if(a[j] > a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
system.out.println("\n shorted array")
for(i=o; i<n; i++)
system.out.print(a[i]+ "\t");
}
}
}
system.out.println("\n shorted array")
for(i=o; i<n; i++)
system.out.print(a[i]+ "\t");
}
}
}
SEARCHING
1.) Sequential Search(Linear Searching)
class seqSearch
{
puclic static void main (string args[]){
int x = Integer.parseInt(args[0]);
int a[x] = { };
int i, pas = -1;
for(i=0; i<a.length; i++)
{
if(a[i] == x)
{
pas = i;
break;
}
}
if(pas == -1)
system.out.println("value not found");
else
system.out.println("value found at index:-" +pas);
}
}
2.) Binary Search :--
class seqSearch
{
puclic static void main (string args[]){
int x = Integer.parseInt(args[0]);
int a[x] = { };
while(first<=last)
{
mid = (first+last)/2;
if( x > a[mid])
first = mid +1;
else if(x<a[a])
last= mid-1;
else
{
pass= mid;
break;
}
}
Friday, January 30, 2015
ARRAYs
ARRAYs
Declaration:-
datatype arr name[];
or
datatype[] arrname;
MEMORY ALLOCATION :-
array name = new datatype[size]a = new int [10]
per = new float[20]
INITIALIZATION :-
int a[] = {3,6,4,1,8,5,9,2}
SIZE:-
n = a.length;
RUN TIME INPUT
import java.io.*;
class runime
{
public static void main (string args[])throws IO Exception{
InputStreamReader input = new InputStreamReader(system.in);
BufferedReader in = new BufferedReader(input);
system.out.println("enter 2 numbers");
string val = in.read lin();
int a = Integer.parseInt(val);
int b = Integer.parseInt(in.readLine());
int c = a+b;
system.out.println("sum=" +c);
}
}
CREATING A SIZED ARRAY :--
import java.io.*;
class arr{
public static void main(string args[])throws IO Exception{
BufferReader in = new BufferReader(new ISR(system.in));
int n,i;
system.out.println("enter size of array");
n = Integer.parseInt(in.readLIne());
int a[] = new int[n];
for(i=0; i<a.length; i++);
{
system.out.println("enter value");
a{i] = Integer.parseInt(in.readLine);
}
system.out.println("Array");
int s = 0;
for(i=0; i<n; i++)
{
system.out.println(a[i] +"\t");
s = s+a[i];
}
system.out.println("\n sum =" +s);
float avg = (float) s/n;
system.out.println("Avg =" +avg);
}
}
COUNT EVEN OR ODD ELEMENTs :--
class arr
{
public static void main(string args[])throws IO Exception{
BufferReader in = new BufferReader(new ISR(system.in));
int n,i;
system.out.println("enter size of array");
n = Integer.parseInt(in.readLIne());
int a[] = new int[n];
for(i=0; i<a.length; i++);
{
system.out.println("enter value");
a{i] = Integer.parseInt(in.readLine);
}
system.out.println("Array");
int even = 0;
int odd = 0;
for(i=0; i<n; i++)
{
system.out.println( a[i] + "\t");
if(a[a]%2==0)
even++;
else
odd++;
}
system.out.println("Even elements =" +even);
system.out.println("Odd elements =" +odd);
}
}
REVERSE OF ARRAY:--
{
public static void main(srting args[]){
int a[] = { };
int i.j.t;
system.out.println("Array");
for(i=0; i<a.length; i++)
{
system.out.println(a[i] +"\t");
}
for(i=0, j= a.length-1; i<a.length/2; i++, j--)
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
system.out.println("Reversed Array");
for(i=0; i=a.length; i++)
{
system.out.println(a[i] + "\t");
}
}
}
Thursday, January 29, 2015
LOOPs
LOOPs
1.) for loop
2.) while loop
3.) do while loop
FIRSTLY WE ARE GOING TO TALK ABOUT FOR LOOP
In programming language FOR loop is used to allow code executed repeatedly. For loop is useful when you know how many times a task to be repeatedly.
example :-
for(exp1; exp2; exp3)
{
statements;
}
where :
exp1 :- initialization expression
exp2 :- test expression
exp3 :- update expression.
EXAMPLE FOR CHECK WEATHER NUMBER IS PRIME OR NOT
class prime
{
public static void main(string args[]){
int n = Integer.parseInt(args[0]);
boolean flag = true;
for(int i=2; i<n/2; i++)
{
if(n%i==0)
{
d=i;
flag = false
break;
}
}
if(flag)
system.out.println("number is prime");
else
system.out.println("number is not prime");
}
}
NESTED LOOP
The placing of one loop inside the body of another loop is called nesting. The most common nested loop are for loop.
Example of nested loop a table up to n numbers :-
class table
{
public static void main(string args[]){
for(int i=1; i<=10; i++)
{
for(int j=1; j<=10; j++)
{
system.out.println(i + "" + j);
}
}
}
WHILE LOOP
In programming language WHILE loop is used to control flow statement that allow code to repeatedly executed based on the condition.
example :-
while(condition)
{
statements
________
________
}
example :-
while(condition)
{
statements
________
________
}
Example for sum of digits
class digitSum
{
public static void main(string args[]){
int n = Integer.parseInt(args[0]);
int r,s = 0;
while (n!=0)
{
r = n%10;
s = s+r;
n = n/10;
}
system.out.println("sum of digits="+s);
}
}
}
system.out.println("sum of digits="+s);
}
}
DO WHILE LOOP
In programming language DO WHILE loop is used to control flow statement that executes a part of code single time and then repeatedly executes the part of code, its depend on the giving condition in the program.
example:-
do
{
statements;
_______
_______
}
while(condition)
Example to print number from 1 to 19
class example
{
public static void main(string args[]){
int x= 1;
do
{
system.out.println("x is :=" +x);
x++;
system.out.println("/n");
}
while(x=<20);
}
}
{
statements;
_______
_______
}
while(condition)
Example to print number from 1 to 19
class example
{
public static void main(string args[]){
int x= 1;
do
{
system.out.println("x is :=" +x);
x++;
system.out.println("/n");
}
while(x=<20);
}
}
SWITCH CASE
switch (exp)
{
case constant 1;
statement;
break;
case constant 2;
statement;
break;
_____________
________
________
default;
statement;
}
RULES FOR SWITCH CASE :=
1.) CASE CONSTANTS MUST BE OF TYPE INT OR CHAR.
2.) NO TWO CASE MAY BE SAME.
3.) BREAK IS OPTIMAL.
4.) DEFAULT IS OPTIMAL.
EXAMPLE
class color
{
public static void main (string args[])
{
char ch = args[0.].char At(0);
switch(ch)
{
case "R":
system.out.println("RED");
break;
case "G":
system.out.println("GREEN");
break;
case "B":
system.out.println("BLUE");
break;
default;
system.out.println("UNDEFINED");
}
}
}
AS SAME WE CAN MAKE A CALCULATOR OR MORE OTHER PROGRAMS.
Saturday, January 17, 2015
A Example of "if else" loop
Here i'm going to give you an example of of "if else" loop to write a program on
class student
{
public static void main(string args[]);
{
int a,b,c,d,e,t;
float p;
a= Integer.parseInt(args[0]);
b= Integer.parseInt(args[1]);
c= Integer.parseInt(args[2]);
d= Integer.parseInt(args[3]);
e= Integer.parseInt(args[4]);
t=(a+b+c+d+e);
system.out.println("total marks are" +t);
p=(t/500)*100;
system.out.println("percentage is " +p);
if (p>=4)
{
system.out.println("student is passed");
}
else
{
system.out.println("student failed");
}
}
}
FIND THE TOTAL MARKS AND PERCENTAGE OF AA STUDENT IN 5 SUBJECTS
class student
{
public static void main(string args[]);
{
int a,b,c,d,e,t;
float p;
a= Integer.parseInt(args[0]);
b= Integer.parseInt(args[1]);
c= Integer.parseInt(args[2]);
d= Integer.parseInt(args[3]);
e= Integer.parseInt(args[4]);
t=(a+b+c+d+e);
system.out.println("total marks are" +t);
p=(t/500)*100;
system.out.println("percentage is " +p);
if (p>=4)
{
system.out.println("student is passed");
}
else
{
system.out.println("student failed");
}
}
}
Thursday, June 26, 2014
Capture image from camera in android
To capture image from android first fire an intent.
private static final int REQUEST_CODE_IMAGE = 101;
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE_IMAGE);
// get data on on Activity Result use the below code
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
if (data != null) {
if (data.getExtras().get("data") != null) {
Uri fileUri = data.getData();
String filePath = getRealPathFromURI(fileUri,
MediaStore.Images.Media.DATA);
File file = new File(filePath);
String fileName = file.getName();
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
} catch (Exception ex) {
}
}
}
}
Show or Read PDF in Android
To Show PDF file in your android phone first save it in your assets folder than read PDF file by using below two methods.
These methods first store your pdf in local storage than show it from local storage.
private void CopyReadAssets(String fileName) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), fileName);
try {
in = assetManager.open(fileName);
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/" + fileName),
"application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Saturday, February 15, 2014
How to get screen dimensions in android
There is Display class to get the display of screen in android.
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
//getSize() method is introduced in API level 13.
int width = size.x;
int height = size.y;
Before API level 13 below method are used.
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); //this method is deprecated now
int height = display.getHeight();//this method is deprecated now
Wednesday, February 12, 2014
Example to show Animated GIF image in Android
Android doesnot support GIF image simply you should use WebView or other thing to run gif image.
I use WebView to implement the GIF image .
First create a GIFView by extending webview.
public class GIFView extends WebView {
public static final String HTML_FORMAT = "<html><body style=\"text-align: center; vertical-align: right;background-color: transparent;\"><img src = \"%s\" /></body></html>";
public GIFView(Context context, String fileUrl) throws IOException {
super(context);
final String html = String.format(HTML_FORMAT, fileUrl);
setBackgroundColor(Color.TRANSPARENT);
loadDataWithBaseURL("", html, "text/html", "UTF-8", "");
}
}
Create your activity class here.
public class MainActivity extends Activity {
private WebView webView;
// private ProgressBar pd;
private LinearLayout llProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llProgress = (LinearLayout) findViewById(R.id.ll_progress);
try {
// give your gif image name here(example.gif).
GIFView gif = new GIFView(this,
"file:///android_asset/example.gif");
llProgress.addView(gif);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here is your activity_main 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:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/ll_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
I use WebView to implement the GIF image .
First create a GIFView by extending webview.
public class GIFView extends WebView {
public static final String HTML_FORMAT = "<html><body style=\"text-align: center; vertical-align: right;background-color: transparent;\"><img src = \"%s\" /></body></html>";
public GIFView(Context context, String fileUrl) throws IOException {
super(context);
final String html = String.format(HTML_FORMAT, fileUrl);
setBackgroundColor(Color.TRANSPARENT);
loadDataWithBaseURL("", html, "text/html", "UTF-8", "");
}
}
Create your activity class here.
public class MainActivity extends Activity {
private WebView webView;
// private ProgressBar pd;
private LinearLayout llProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llProgress = (LinearLayout) findViewById(R.id.ll_progress);
try {
// give your gif image name here(example.gif).
GIFView gif = new GIFView(this,
"file:///android_asset/example.gif");
llProgress.addView(gif);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here is your activity_main 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:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/ll_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
Tuesday, February 11, 2014
Example to create Round Shape image bitmap android
public static Bitmap getRoundedShape(Bitmap scaleBitmapImage,
int targetWidth, int targetHeight, Context context) {
// TODO Auto-generated method stub
// int targetWidth = width;
// int targetHeight = height;
targetHeight = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, targetHeight, (context)
.getResources().getDisplayMetrics());
targetWidth = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, targetWidth, (context)
.getResources().getDisplayMetrics());
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth) / 2, ((float) targetHeight) / 2,
(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
Path.Direction.CCW);
Log.d("", "In process: width" + targetWidth + " height" + targetHeight);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), null);
return targetBitmap;
}
Android ViewPager Example
This is simple example for a viewpager in android.First add "android-support-v4.jar" library in your libs folder.than create an activity and add this code.
public class MainActivity extends Activity implements OnClickListener {
private ViewPager viewPager;
private TextSwipping pagerAdapter;
private ArrayList<String> alText = new ArrayList<String>();
private Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcomepage);
alText.add("Hi");
alText.add("This");
alText.add("is");
alText.add("Manu");
viewPager = (ViewPager) findViewById(R.id.welcome_text_pager);
pagerAdapter = new TextSwipping(alText, this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int pos) {
// TODO Auto-generated method stub
if (viewPager.getCurrentItem() == 0) {
// set your conditions here
} else if (viewPager.getCurrentItem() == 1) {
// set your conditions here
} else if (viewPager.getCurrentItem() == 2) {
// set your conditions here
} else if (viewPager.getCurrentItem() == 3) {
// set your conditions here
}
}
});
}
}
add this viewpager in your welcomepage.xml file
<android.support.v4.view.ViewPager
android:id="@+id/welcome_text_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
and create Adapter for the text displaying in your viewpager.
public class TextSwipping extends PagerAdapter {
ArrayList<String> alText;
Context context;
public TextSwipping(ArrayList<String> alText, Context context) {
this.alText = alText;
this.context = context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 4;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View view= inflater.inflate(R.layout.textswitcher, null);
// I am using a dynamic text view you could use
//a layout using inflater or use a fragment as your necessity.
TextView tvTextSwitcher = new TextView(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tvTextSwitcher.setTextColor(Color.parseColor("#ff78ff"));
tvTextSwitcher.setTextSize(TypedValue.COMPLEX_UNIT_DIP,20);
tvTextSwitcher.setLayoutParams(lp);
tvTextSwitcher.setGravity(Gravity.CENTER_HORIZONTAL);
tvTextSwitcher.setText(" " + alText.get(position));
tvTextSwitcher.setTypeface(WidgetProperties
.setTextTypefaceRegular(context));
((ViewPager) container).addView(tvTextSwitcher);
return tvTextSwitcher;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView((View) object);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
}
android:id="@+id/welcome_text_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
and create Adapter for the text displaying in your viewpager.
public class TextSwipping extends PagerAdapter {
ArrayList<String> alText;
Context context;
public TextSwipping(ArrayList<String> alText, Context context) {
this.alText = alText;
this.context = context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 4;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View view= inflater.inflate(R.layout.textswitcher, null);
// I am using a dynamic text view you could use
//a layout using inflater or use a fragment as your necessity.
TextView tvTextSwitcher = new TextView(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tvTextSwitcher.setTextColor(Color.parseColor("#ff78ff"));
tvTextSwitcher.setTextSize(TypedValue.COMPLEX_UNIT_DIP,20);
tvTextSwitcher.setLayoutParams(lp);
tvTextSwitcher.setGravity(Gravity.CENTER_HORIZONTAL);
tvTextSwitcher.setText(" " + alText.get(position));
tvTextSwitcher.setTypeface(WidgetProperties
.setTextTypefaceRegular(context));
((ViewPager) container).addView(tvTextSwitcher);
return tvTextSwitcher;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView((View) object);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
}
Saturday, October 27, 2012
Android Simple Button click Example with String Resources
Your Activity
package pro2.pro3;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ButtonExample extends Activity implements OnClickListener
{
private Button hiButton;
private Button helloButton;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
hiButton = (Button) findViewById(R.id.hi_button);
hiButton.setOnClickListener(this);
helloButton = (Button) findViewById(R.id.hello_button);
helloButton.setOnClickListener(this);
}
public void onClick(View v)
{
EditText nameField = (EditText) findViewById(R.id.name_field);
String name = nameField.getText().toString();
if (name.length() == 0)
{
new AlertDialog.Builder(this).setMessage(R.string.error_name_missing)
.setNeutralButton(R.string.error_ok, null).show();
return;
}
if (v == hiButton || v == helloButton)
{
int resourceId = v == hiButton ? R.string.hi_greeting
: R.string.hello_greeting;
String greeting = getResources().getString(resourceId, name);
Toast.makeText(this, greeting, Toast.LENGTH_LONG).show();
TextView greetingField = (TextView) findViewById(R.id.greeting_field);
greetingField.setText(greeting);
}
}
}
Create 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:id="@+id/greeting_field"
android:layout_height="wrap_content"
android:text="@string/hello"
android:layout_width="match_parent"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20dp"
android:text="@string/enter_your_name"
android:textColor="#ff00ff"/>
<EditText
android:id="@+id/name_field"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2">
<Button
android:id="@+id/hi_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hi_button"
android:textSize="20dp"
android:layout_weight="1"
android:textColor="#ff00ff"/>
<Button
android:id="@+id/hello_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_button"
android:textSize="20dp"
android:layout_weight="1"
android:textColor="#ff00ff"/>
</LinearLayout>
</LinearLayout>
Define main.xml strings in your strings.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, manu!</string>
<string name="app_name">pro1</string>
<string name="enter_your_name">Enter your name:</string>
<string name="hi_button">Say Hi!</string>
<string name="hello_button">Say Hello!</string>
<string name="error_name_missing">Please enter your name</string>
<string name="error_ok">OK</string>
<string name="hi_greeting">Hi %s!</string>
<string name="hello_greeting">Hello %s!</string>
</resources>
Simple Example to move one activity to another in android
First Create your 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"
android:gravity="center">
<EditText
android:id="@+id/et_data"
android:hint="EditText"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</EditText>
<Button
android:text="Next Screen"
android:id="@+id/next_screen_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</Button>
</LinearLayout>
Define your first Activity screen
package but.clk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class clicking extends Activity
{
private Button nextBtn;
private EditText etData;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nextBtn=(Button)findViewById(R.id.next_screen_btn);
etData=(EditText)findViewById(R.id.et_data);
nextBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String Data=etData.getText().toString();
Intent intent=new Intent(clicking.this,NextScreen.class);
intent.putExtra("DATA",Data );
startActivity(intent);
}
});
}
}
Second Activity 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:text="text"
android:id="@+id/data_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:textColor="#ff00ff">
</TextView>
</LinearLayout>
Define your next Activity screen
package but.clk;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class NextScreen extends Activity
{
private TextView tvText;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nextview);
String Data=getIntent().getExtras().getString("DATA");
tvText=(TextView)findViewById(R.id.data_text);
tvText.setText(Data);
}
}
and don't forget to add second activity in manifest file
<activity android:name=".NextScreen"/>
Your manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="but.clk"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".clicking"
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=".NextScreen"/>
</application>
</manifest>
Subscribe to:
Comments (Atom)
