Wednesday, 30 September 2015

print a random number every second

package com.example.raj.testview;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.ThemedSpinnerAdapter;

import java.util.Random;
import java.util.TimerTask;



public class MainActivity extends AppCompatActivity {
    TextView tv;
    Handler handler;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         tv=(TextView)findViewById(R.id.tv);
        Thread th=new Thread(new MyThread());
        th.start();
        handler=new Handler(){
            @Override            public void handleMessage(Message msg) {
                //super.handleMessage(msg);                int k=msg.arg1;
                tv.setText(Integer.toString(k));
            }
        };


    }

    class MyThread implements Runnable{


        @Override        public void run() {

            for(int i=0;i<100;i++)
            {
                Message message=Message.obtain();
                Random r=new Random();
                int y=r.nextInt();
                message.arg1=y;
                handler.sendMessage(message);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

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

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Saturday, 26 September 2015

custom button


Custom button
other than having a png image in drawable we also need a xml in drawable the will totally define the button that we have
xml example

<item android:state_presses="true" android:drawable="@drawable/plusselected"></item>
<item android:state_focused="true" android:drawable="@drawable/plushlight"></item>
<item android:drawable="@drawable/plus"></item>


now in the xml where the actual button resides , we should change the
layout width and height to wrap_content , so that the image remains to itself
and the background of the button should be @drawable/ourxml

Create a ListMenu for Android

Create a ListMenu for Android

unlike other classes our class for Listmenu will extend ListActivity not Activity

two methods need to be overrided here
1.onCreate like we did previously
2.onListItemClick

 Then we set up a String array (as instance varible bcz we want to use it in both the methods)
 String classes[]={"startingPoint","example1","example2","example3"};// we will name it exact same as the class name(case sensitive)

 we will not use any layout here,
 we will develop all in java here

 now we need to set setListAdapter(); // it takes a array adapter or a list adapter
 setListAdapter(new ArrayAdapter<String>(context,int,StringArray));//<> gives the type
 cotext= ClassName.this
 StringArray =classes
 int = android.R.layout.simple_list_item1

 for any of the list item when clicked it will call method onListItemClick

 WE need one more method now,
 3.onListItemClick
 the function has a parameter called position which will tell us about the item clicked
 we now set up a local string there
 String cheese= classes[position];// classes was our global string array containing the names of all the classes
 so now we can setup our class for intent according to the list item that was clicked

 Class ourclass- Class.forName("com.thenewboston.travis."+cheese);// will return the class name of particular class which has the intent filter in the manifest

 Intent ourIntent= new Intent(Menu.this, ourClass);
 startActivity(ourIntent);


 

onClick function

declaring a single onClick function for all instead of using all innerClass stuff

first we need to implements View.OnClickListener

then in the onClick funtion which recives View as parameter
we need to setup swich Case to know which element has been clicked
so in the the switch case we need to write

switch(view.getId())
{
case R.id.b1: .......;break;
case R.id.b2: .......;break;
}

email

Sending email from android
using android email Intent

Intent emailIntent= new Intent(android.content.Intent,ACTION_SEND);
emailIntent.putExtra(messsage,value);
emailIntent.putExtra(android.content.Intent.Extra_EMAIL, String array value of email address(emailAdress));//adding email array

//adding subject
emailIntent.putExtra(android.content.Intent.Extra_SUBJECT, "this is my subject area");

//adding message
emailIntent.putExtra(android.content.Intent.Extra_TEXT, message);

//we can also setup text as plain type in case we are using encoding as /n and all
emailIntent.setType("plain/text");

finally start the intent
startActivity(emailIntent);

starting activity for result

starting activity for result

make the intent
pass it to startActivityForResult(intent, Acode)

overRide method onActivityResult(int requestCode, int resultCode, Intent data)
{
// inside it we first check wherether some proper result has been returned or not
if(resultCode==RESULT_OK)
{
 Bundle extra= data.getExtras();
            bit=(Bitmap)extra.get("data");
            iv.setImageBitmap(bit);

}


}

whenever we put some extra at the backend side where the data is recieved we can grab that extra
using data.getExtras() method.

Thursday, 17 September 2015

setting up onclick method

declaring a single onClick function for all instead of using all anonymous   innerClass stuff

first we need to implements View.OnClickListener

then in the onClick funtion which recives View as parameter
we need to setup swich Case to know which element has been clicked
so in the the switch case we need to write

switch(view.getId())
{
case R.id.b1: .......;break;
case R.id.b2: .......;break;
}

and in the setOnClickListener thing insead on declaring whole view.onclicklistener
just type (this)

xml design tips

1. if u want want stuffs to be in the horizontal line all together

put them in a single new  linear layout
make android:orinetation=horizontal ,
but that makes others shift to other end where we cant see them

of the individual elements,
set width = match_parent
height= wrap_content

now the magic happens when if the linear layout we add
android:weightSum="100"  // can be anything

in the elements add
android:layout_weight="50"// shares half the width of the parent

imp notes

can the sound recorder keep on recoding sound even if  i turn the screen off?

can recording be done even if i swtich to different activity or app?

can recoring be made  a android service?


in the app made by asus all the three things are working , i dont know whether its a service or not but its working even in different screen , different app and with screen offf.


android theme set up part is done in manifest for each activity


in a list for xml we can set its value from xml its self and that can be done using
android:entries="@arrays/list"
no number of list items will be equal to the number of elements in the array
and they can have their entryvalues also which will not be shown but can extracted for the use
android:entryvalues="arrays/lValues"

Now even if a preference activity class has a listactivity we will not extend it with list activity but will extend it with (extends PreferenceActivity)
To addPreference from xml we just use addPreferenceFromResource(R.xml....)


to exit application just use finish() function



To get the value of preference that is there , we need to use PreferenceManager,
actually something like this

SharedPreferences sps=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Now to check value using this sps
for example we are checking the checkbox thing
boolean b=sps.getBoolean(key,defvalue); // now in the xml checkbox declaration we had given it a key to get identified, and defvalue as true
 

imp liks for projects

imp links
android sound project imp links
http://stackoverflow.com/questions/7955041/voice-detection-in-android-application/7976877#7976877
in this app in not working in presence of while loop


working version of above code

http://stackoverflow.com/questions/7955041/voice-detection-in-android-application/7976877#7976877

aplitude detection
http://stackoverflow.com/questions/14181449/android-detect-sound-level

changing ok google
http://android.stackexchange.com/questions/55447/can-i-change-the-phrase-ok-google-now-to-something-else

question on how to create a sound recoding servicec , ans not confirmed yeet but this is the link

http://stackoverflow.com/questions/10025824/how-to-record-audio-voice-in-background-contineously-in-android


listview created by java

Create a ListMenu for Android

unlike other classes our class for Listmenu will extend ListActivity not Activity

two methods need to be overrided here
1.onCreate like we did previously
2.onListItemClick

 Then we set up a String array (as instance varible bcz we want to use it in both the methods)
 String classes[]={"startingPoint","example1","example2","example3"};// we will name it exact same as the class name(case sensitive)

 we will not use any layout here,
 we will develop all in java here

 now we need to set setListAdapter(); // it takes a array adapter or a list adapter
 setListAdapter(new ArrayAdapter<String>(context,int,StringArray));//<> gives the type
 cotext= ClassName.this
 StringArray =classes
 int = android.R.layout.simple_list_item1

 for any of the list item when clicked it will call method onListItemClick

 WE need one more method now,
 3.onListItemClick
 the function has a parameter called position which will tell us about the item clicked
 we now set up a local string there
 String cheese= classes[position];// classes was our global string array containing the names of all the classes
 so now we can setup our class for intent according to the list item that was clicked

 Class ourclass- Class.forName("com.thenewboston.travis."+cheese);// will return the class name of particular class which has the intent filter in the manifest

 Intent ourIntent= new Intent(Menu.this, ourClass);
 startActivity(ourIntent);


 

Splash Screen

Splash Screen

We accomplish this task by using Thread
The Thread will have a timer ad after sometime a new activity will come up, thus fullfilling our concept of splash screen

Set the content view in starting class as the splash screen.

 Thread timer= new Thread(){
  public void run(){
    try{
        sleep(3000);
       
    }
    catch(InterruptedException e)
    {
        e.printStackTrace();
        // or can do a log
    }
    finally{
            Intent openStartingPoint=new Intent("com.thenewboston.travis.STARTINGPOINT");// whatever the action name is or just the (fromclassname, toclassname)
            startActivity(openStartingPoint);
    }
  }
 };

 timer.start();

 // this makes the thing work but the problem is that if we hit the back button, it gors back to the splash screen
 // and then can take up some memory , so we should free up that



 so if we want to destroy the splashScreenActivity
 we should override the onPause() Method and call finish() inside it.



 Note- uri can be used to streamMusicFrom internet

  adding media to splsah screen
    MediaPlayer ourSong= MediaPlayer.create(context,ResourceID);// make oursong a class (instance variable)
    ourSong.start();
    One more thing to note is that  we dont want this song to keep playing in the next activity
    so ,
   
    in the onPause method we will release the oursong
    ourSong.release.

Saturday, 12 September 2015

Preference xml Activity and check Boxes

To create a Different activity of Preferences

first we need to a have a button or so to take it that activity

Create preference xml file and a java file for the layout

The xml is create as type preference and goes to the xml directory

Adding checkBoxes to the xml file

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference android:key="first"    android:title="first"    android:summary="this is the first option"></CheckBoxPreference>
    <CheckBoxPreference android:key="Second"        android:title="SEcond"        android:summary="this is the Second option"></CheckBoxPreference>

</PreferenceScreen>

The java file of Preference Activity is bit different 

the class Extends preference Activity

It doesnt use set content view but uses
addPreferencesFromResource(R.xml.pref);

add the class to the manifest




Being a prefernece thing itself we dont need to save it while onstop and all


Shared Preference (for storage)

This is a simple api that allows the user to save the key value pairs.

For a simple example
we will create a global edittext

get reference to it in the oncreate method

then we create an instance of shared preferences

SharedPreferences setting=getSharedPreferences("MYPREFS",0);
MYPREFS is the file and if it doesnt exist , it will go and create that

Now what we want t odo it read it and put whatever value it has in the edit text

et.setText(setting.getString("tvalue","this is default value"),);

now we try to extract a string out of it , (tvalue is just any name, a key name, its like a map and the key value thing that we generally use) , and if any value 
doesn't exist it just tries to read the second parameter which makes it the default values.


Now ,we want to save whatever we have written in that edittext before we exit
so we override onstop method

@Overrideprotected void onStop() {
    super.onStop();
    SharedPreferences setting= getSharedPreferences("MYPREFS",0);// again create shared preference
   to do changes to this shared preferences we need call an editor
    SharedPreferences.Editor editor= setting.edit();
    editor.putString("tvalue",et.getText().toString());
// put value that is there in the edit text and the keyvalue is Tvalue
     editor.commit();
// and the last this is to commit the changes that we have done
    



}

Friday, 11 September 2015

Using Camera

We set a imageView in the the android xml layout
and a button to capture image

In the onclick of the button we

Set uo an Intent to capture image
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

after the we start activity of this Intent
startActivityForResult(intent,0);

but it must be noticed that its not just startActivity but StartActivity for Result
which mean that we will be able to capure the result

To Capture the result we will have to override a method called onActivityResult

We will recieve our image in bitmap format and for that we will create a bitmap object

We also create a global ImageView variable in our class and initialize that while we are in
 Oncreate


in the onActivityresult 
we put this code

Bitmap bm= (Bitmap) data.getExtras().get("data");
// gets the image of the result
iv.setImageBitmap(bm);




Toast

Its very simple we just put these pieces of code wherever necessary

Toast t= Toast.makeText(MainActivity.this,"THis is some Toast",5000);
t.setGravity(Gravity.CENTER,0,0);
t.show();

creating notification

First we need to use Notification builder
NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");

Then we need to have a intent
Intent resultIntent = new Intent(this, ResultActivity.class);
need not to say that if it is being defined in a inner class then instead of writing this we write MainActivitiy.this

Now, we create a pending  activity
PendingIntent resultPendingIntent =
    PendingIntent.getActivity(
    this,
    0,
    resultIntent,
    PendingIntent.FLAG_UPDATE_CURRENT);
WE make our builder content intent equal to our pending activity
mBuilder.setContentIntent(resultPendingIntent);

Now the last thing i.e. to issue the notification , which is done with the help of notification manager, which get the android notification service
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = 
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());


my questions

What is intent and pendingintent in android?

what actually is a inflator?

what is gradle?

what is android sandbox?
Ans-Android has another layer of protection in that it doesn’t give one app access to the resource of another app. This is known as the ‘sandbox’ where every app gets to play in its own sandbox and can’t use another app’s toys! Android does this by giving each app a unique user id (a UID) and by running that app as a separate process with that UID. Only processes with the same UIDs can share resources which, as each ID is uniquely assigned, means that no other apps have permission.

How is an intent created?
Ans- Intent i= new Intent(from, to);
eg Intent i = new Intent(MainActivity.this, to class where we want to go);
MainaActivity.this is used whenever we are in a inner class



what is bundle?
bundle in android is like a basket, it can hold datas like string n all ,
can also be compared to a map , where its holds data as key value pair.
and we can always put extras with out intent and that extras can also be a bundle,
and that can be extracted in the new acctivity.



when we start an activity for result and the other class has to manually send result to the previous class
in the new class
set the intent
if there is any bundle to set up then complete that
attach it with the intent using putExtras
now comes the setResult
setResult(RESULT_OK,Intent variable)// the RESULT_OK tells that everything is ok
now call finish()




q.
why does everything saved goes back to default when we change the layout from potrait to landscape and vice versa?

Progress show



final ProgressDialog pd= new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// there are two type of styles available
pd.setIndeterminate(false);
pd.setCancelable(true);
 
and whenever and whereever we want to start and show the progress dialog box we do
pd.show(); 
for example in an onclick event

Create alert

for example

The alert is shown when a button is clicked

we set its onclick listener

inside the onclcik we write

AlertDialog.Builder builder =new AlertDialog.Builder(MainActivity.this);

builder.setMessage("do u really want to close this app");
builder.setCancelable(false);
// setCancelble wont allow the back button to work
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
    @Override    public void onClick(DialogInterface dialog, int which) {
        MainActivity.this.finish();
    }
});

builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    @Override    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});
AlertDialog a=builder.create();
// a alert dialog is finally created out of builder 
a.show();
// then alert dialog is shown 



long press menu (called context menu )

We create a xml file for the menu show as done in the previous post

to create context menu

we get reference for a button and register it for context menu

Button button= (Button) findViewById(R.id.button);
registerForContextMenu(button);
 
then we modify oncreate context menu
 
@Overridepublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                   super.onCreateContextMenu(menu, v, menuInfo);

    MenuInflater menuInflater= getMenuInflater();
    menuInflater.inflate(R.menu.contextm,menu);
}
 
 the above does the job of creating context menu

now , what if any of the option clicked

we redefine onContextItemSelected

creating simple menu

Create a xml file of type menu and that will go into menu folder

put whatever option u want as <item > inside the xml

<item android:id="@+id/item2" android:title="option2"  android:icon="@android:drawable/ic_menu_call" >
</item>
 
 then we will have to modify the Oncreatemenu thing
 
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                   super.onCreateContextMenu(menu, v, menuInfo);

    MenuInflater menuInflater= getMenuInflater();
    menuInflater.inflate(R.menu.contextm,menu);
}
 
use inflater to inflate it with the xml file the we created
 
this just does the work to create the option and menu thing
now, to control the clicks we onOptionsSelected
 
 
 
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will    // automatically handle clicks on the Home/Up button, so long    // as you specify a parent activity in AndroidManifest.xml.    int id = item.getItemId();

    //noinspection SimplifiableIfStatement    if (id == R.id.action_settings) {
        return true;
//can also do a logcat here
    }

    return super.onOptionsItemSelected(item);
} 

Animation Xml

first we put all the images set for the animation in drawable

Then we make a xml file of type animation (that goes in anim folder)

there we write something like this inside animation-list

<item android:drawable="@drawable/animation_00031" android:duration="30"></item>
<item android:drawable="@drawable/animation_00032" android:duration="30"></item>
<item android:drawable="@drawable/animation_00033" android:duration="30"></item>
<item android:drawable="@drawable/animation_00034" android:duration="30"></item>
<item android:drawable="@drawable/animation_00035" android:duration="30"></item>
<item android:drawable="@drawable/animation_00036" android:duration="30"></item>
<item android:drawable="@drawable/animation_00037" android:duration="30"></item>
 
 our main layout just has a imageview for which we will set our xml anil files
 
final ImageView iv= (ImageView) findViewById(R.id.imageView);
iv.setBackgroundResource(R.anim.frame_animation); 

to start animation just do

AnimationDrawable anim  = (AnimationDrawable) iv.getBackground();
anim.start();
 
 

create a list

To create a list

We extend mainActivity as ListActivity

set ListAdapeter as

setListAdapter(new MyAdapter(this,android.R.layout.simple_list_item_1,R.id.textView,getResources().getStringArray(R.array.countries)));
 
Myadapter class is a custom class created by us so will need to be redefined later to create the options list as we want
 or in simple case it wud have been ArrayAdapter which is already defined
 
 
 
 Then we have out oncreateOptionsMenu
 
@Overridepublic boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
 
in the above code inflater class holds to change the options as we want
here its refering to a xml file helping it modify the options as the xml file looks 
 
 
Now the options in the list being selected we havee a different claass to handle that
 
@Overridepublic boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will    // automatically handle clicks on the Home/Up button, so long    // as you specify a parent activity in AndroidManifest.xml.    int id = item.getItemId();

    //noinspection SimplifiableIfStatement    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
} 
 
 
 Our Myadapter class
 
private  class MyAdapter extends ArrayAdapter<String>{

        public MyAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
            super(context, resource, textViewResourceId, objects);
        }

        @Override        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater layoutinflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE );
            View row= layoutinflater.inflate(R.layout.llist_item,parent, false);
            String[] items= getResources().getStringArray(R.array.countries);
            ImageView im= (ImageView) row.findViewById(R.id.imageView);
            TextView tv= (TextView) row.findViewById(R.id.textView);
            tv.setText(items[position]);
            if(items[position].equals("United states"))
            {
                im.setImageResource(R.drawable.usa);
            }
            if(items[position].equals("United kingdom"))
            {
                im.setImageResource(R.drawable.france);
            }


            return row;
        }
    }
} 
 
 
overrides the getview of arrayAdapter to customize the view 

Wednesday, 9 September 2015

General concepts

 Android

The General important components are
1.Activity

2.Perform long running operations in the background,
do not have a user interface,
useful for things like network operation , music ect
it runs independetly of the component that created it
it can be bounded to by other application components if allowed

3.Content Providers
 Used to store and retrieve data and make it accessible to all apps
 only way to share data across application
 Exposes a public uri that uniquely identifies its data set
 Android Contains many providers for things like contacts , media etc

4.Broadcast Announcements
A component that responds to System wide broadcast announcements
examply when screen turns off , the battery is low
Application can also initialte their own breadcast
It has no UI
They can create a status bar notification to alert the user

5.Android Manifest File
Presents information about the application to the Android System.
Describes the components used in the application
Describle the permissions required to run the application
Declares the minimun Android Api level that the application requires



Android manifest
Its the activity->Intent-filter->action that tell the manifest which screen is launched first
the value is <action android:name="android.intent.action.MAIN"

General concepts

Android

The General important components are
1.Activity

2.Perform long running operations in the background,
do not have a user interface,
useful for things like network operation , music ect
it runs independetly of the component that created it
it can be bounded to by other application components if allowed

3.Content Providers
 Used to store and retrieve data and make it accessible to all apps
 only way to share data across application
 Exposes a public uri that uniquely identifies its data set
 Android Contains many providers for things like contacts , media etc

4.Broadcast Announcements
A component that responds to System wide broadcast announcements
examply when screen turns off , the battery is low
Application can also initialte their own breadcast
It has no UI
They can create a status bar notification to alert the user

5.Android Manifest File
Presents information about the application to the Android System.
Describes the components used in the application
Describle the permissions required to run the application
Declares the minimun Android Api level that the application requires



Android manifest
Its the activity->Intent-filter->action that tell the manifest which screen is launched first
the value is <action android:name="android.intent.action.MAIN"