Monday, 30 November 2015

Sunday, 29 November 2015

schedule a repeating task

timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        synchronized public void run() {

            \\ here your todo;
            }

        }}, 60000, 60000);
 
 
http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android
 
timer = new Timer();
TimerTask task = new TimerTask(){

    @Override    public void run() {
        new GetJson().execute(url);
    }

};
long whenToStart = 5*1000L; // 5 secondslong howOften = 5*1000L; // 5 secondstimer.scheduleAtFixedRate(task, whenToStart, howOften); 

heads up notification 2

private void showNotification(boolean showAsHeadsUp)
{
    final Intent intent = getIntent();
    intent.putExtra("launched_from_notification", true);

    final Notification.Builder nb = new Notification.Builder(this);
    nb.setContentTitle("Foobar");
    nb.setContentText("I am the content text");
    nb.setOngoing(true);
    nb.setSmallIcon(android.R.drawable.ic_dialog_info);
    nb.setContentIntent(PendingIntent.getActivity(
            this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
    nb.setPriority(Notification.PRIORITY_HIGH);

    // Notifications without sound or vibrate will never be heads-up    nb.setDefaults(showAsHeadsUp ? Notification.DEFAULT_ALL : 0);

    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(0, nb.build());
}

heads up notification

private void showHeadsUpNotification()
{
    final Notification.Builder nb = new Notification.Builder(this);
    nb.setContentTitle("Foobar");
    nb.setContentText("I am the content text");
    nb.setDefaults(Notification.DEFAULT_ALL);
    nb.setOngoing(true);
    nb.setSmallIcon(android.R.drawable.ic_dialog_info);
    nb.setContentIntent(PendingIntent.getActivity(this, 0, getIntent(), 0));

    // Commenting this line 'fixes' it by not making it heads-up, but that's    // not what I want...    nb.setPriority(Notification.PRIORITY_HIGH);

    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(0, nb.build());
}

Saturday, 28 November 2015

delay any event in android

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 100ms
  }
}, 100);

Thursday, 29 October 2015

php to send json

<?php
$servername = "localhost";
$username   = "root";
$password   = "";
$database   = "userdata";
$connect    = mysql_connect($servername, $username, $password);
$check      = mysql_select_db($database, $connect);
if (!$check) {
    echo"not connected bro";
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   
    $name     = $_POST['name'];
   
    $username = $_POST['username'];
   
   
    $password = $_POST['password'];
   
   
    if ($name == '' || $username == '' || $password == '' ) {
        echo 'please fill all values';
    } else {
        $numrow = 0;
      
       
        if ($numrow > 0) {
            echo "values already exist";
        } else {
            $sql    = "INSERT INTO `uesr` (`id`, `username`, `password`) VALUES (NULL, '$username', '$password')";
           
            $result = mysql_query($sql);
            echo "successfully resgistered";
        }
    }
}
?>

Tuesday, 27 October 2015

login system registration

http://www.simplifiedcoding.net/android-login-and-registration-with-php-mysql/

http://stackoverflow.com/questions/22830251/refreshing-screen-which-uses-json-in-android

creating php script for json parsing
http://www.simplifiedcoding.net/android-json-parsing-retrieve-from-mysql-database/

Tuesday, 6 October 2015

programming with sensors

 class implements SensorEventListener





SensorManager sm=(SensorManager) getSystemService(Context.SENSOR_SERVICE);if(    sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size()!=0)
{
    Sensor s=sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);    sm.registerListener(this,s,SensorManager.SENSOR_DELAY_NORMAL);}
 
in the function public void onSensorChanged(SensorEvent event)
Sensor ss=event.sensor;
if(ss.getType()==Sensor.TYPE_ACCELEROMETER){
senx=event.values[0];seny=event.values[1];senz=event.values[2];  

update gallary after saving any image

Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pictureUri);sendBroadcast(intent);

Save Photo from Camera in Android, Fix NullPointerException

https://www.youtube.com/watch?v=IMomzqwTuKA


package com.kishlay.raj.vbicam;
import android.content.Intent;import android.graphics.Bitmap;import android.media.MediaScannerConnection;import android.net.Uri;import android.os.Environment;import android.provider.MediaStore;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.Gravity;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.Switch;import android.widget.TextView;import android.widget.Toast;
import java.io.File;import java.io.FileOutputStream;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    EditText name,emailId,lname;    public static final int MEDIA_TYPE_IMAGE = 1,MEDIA_TYPE_VIDEO=2;    Button button;    ImageView im;    Intent intent;    TextView tv1;    static final int cameraData=0;    private Uri fileUri;    Bitmap bm;    String First_name,Last_name,email;    Uri pictureUri;    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initialize();    }

    private void initialize() {
        name=(EditText)findViewById(R.id.name);        lname=(EditText)findViewById(R.id.last);        emailId=(EditText)findViewById(R.id.email);        button=(Button)findViewById(R.id.button);        im=(ImageView)findViewById(R.id.imageView);        button.setOnClickListener(this);    }


    @Override    public void onClick(View v) {
        switch(v.getId())
        {
            case R.id.button:
                /*i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                //File file = getOutputMediaFile(1); // create a file to save the image                 fileUri = Uri.fromFile(file);                i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);                startActivityForResult(i,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);*/
                intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                First_name=name.getText().toString();                Last_name=lname.getText().toString();                email=emailId.getText().toString();                File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);                String pictureName=First_name+"_"+Last_name+"_"+email+".jpg";                File imgFile=new File(pictureDirectory,pictureName);                 pictureUri=Uri.fromFile(imgFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri); // set the image file name
                // start the image capture Intent                startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pictureUri);                sendBroadcast(intent);
                break;        }


    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);        if(requestCode==CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            if(resultCode==RESULT_OK)
            {
                //set text that image has been saved                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pictureUri);                sendBroadcast(intent);                Toast t= Toast.makeText(MainActivity.this,"Image Saved :)",5000);                t.setGravity(Gravity.CENTER, 0, 0);                t.show();            }
            else            {
                // try again message                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pictureUri);                sendBroadcast(intent);                Toast t= Toast.makeText(MainActivity.this,"Plz try again :(",5000);                t.setGravity(Gravity.CENTER, 0, 0);                t.show();            }
        }
    }
}

Friday, 2 October 2015

Splsh screen using handler

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.peace);
    new Handler().postDelayed(new Runnable() {
        @Override        public void run() {
            Intent mainIntent= new Intent(MainActivity.this,peace.class);
            MainActivity.this.startActivity(mainIntent);
        }
    },1000);
}

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