Thursday 29 October 2015

AsyncTask

AsyncTask

  • AsyncTask enables proper and easy use of the UI thread. 
  • This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
  •  AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. 
  • If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs.

  • An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. 
  • An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Usage:

AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)



 Example coding:

public class MainActivity extends AppCompatActivity {

    Button download; ImageView iv;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        download=(Button)findViewById(R.id.button);

        iv=(ImageView)findViewById(R.id.imageView);

    }

    @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);

    }

    public void go(View v){

        Downloadimage dli=new Downloadimage(MainActivity.this,iv);

        dli.execute("http://de.wallpapersma.com/wp-

                 content/uploads/2013/05/Cute-Baby-im-Herbst.jpg");

    }

}



public class Downloadimage extends AsyncTask<String,String,Bitmap> {

    ProgressDialog pd;

    Context c;

    ImageView img;

    public Downloadimage( Context c, ImageView img) {

       // this.pd = pd;

        this.c = c;

        this.img = img;

    }

    @Override

    protected Bitmap doInBackground(String... params) {

        Bitmap b=null;

        try {

            b = BitmapFactory.decodeStream((InputStream) new

                URL(params[0]).getContent());

        }catch (Exception e){

           

        }

        return b;

    }

    @Override

    protected void onPreExecute() {

        super.onPreExecute();

        pd=new ProgressDialog(c);

        pd.setMessage("Loading image");

        pd.show();

    }

    @Override

    protected void onPostExecute(Bitmap bitmap) {

        super.onPostExecute(bitmap);

        pd.dismiss();

        img.setImageBitmap(bitmap);

    }

}


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.retro.karthik.asyncimagedownkarapp" >

<uses-permission

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

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name=".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>


AsyncTask's generic types:

 

The three types used by an asynchronous task are the following:
  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.
To mark a type as unused, simply use the type Void:

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }


The 4 steps:

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2.  doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Threading rules:

There are a few threading rules that must be followed for this class to work properly:

 



 

 


 

Monday 19 October 2015

Passing data from one activity to other in android

Passing data from one activity to other in android

 

  • The data can be passed to other activity using intent putExtra() method. 

  • Data is passed as extras and are key/value pairs. 

  • The key is always a String. As value you can use the primitive data types int, float, chars, etc. 

  • We can also pass Parceable and Serializable objects from one activity to other.

*We have two ways for sending data .

Example 1: 

Intent intent=new Intent(MainActivity.this,Main2Activity.class)

*intent.putExtras("key","value");

intent.putExtras("key",Welcome Android");

startActivity(intent); 

Example 2: 

EditText ed1;

Intent intent=new Intent(MainActivity.this,Main2Activity.class)

*intent.putExtras("key","value");

intent.putExtras("key",ed1.getText.toString");

startActivity(intent); 

 

Retrieving data from android activity

 

  • You can retrieve the information using  getData() methods on the Intent object. 

  • The Intent object can be retrieved via the getIntent() method.

Example:

TextView tv;

Intent intent=getIntent();

String s=intent.getStringExtras("key");

tv.setText(s);

 

 

 

 

 

 

 

Wednesday 14 October 2015

Types Of Intents

Intent

What is Intent:

  • An intent is an abstract description of an operation to be performed. 

An Android Intent can be used to perform following 3 tasks :
  1. Open another Activity or Service from the current Activity
  2. Pass data between Activities and Services
  3. Delegate responsibility to another application. For example, you can use Intents to open the browser application to display a URL.


We Have Two Types Intent:

  1. Explicit Intent
  2. Implicit Intent

Explicit Android Intent:

  • Explicit Android Intent is the Intent in which you explicitly define the component that needs to be called by Android System.

  • When you open an activity from another activity in the same Android app, you use Explicit Intents. Let us understand through an example :

    Intent CodeLearnFirstIntent = new Intent (getApplicationContext(), SecondActivity.class);
  •   you are passing the SecondActivity class name as an identifier for this intent.

Let's see an example:

 

Implicit Android Intent:

  • Implicit Android Intents is the intent where instead of defining the exact components, you define the action you want to perform. 

  • The decision to handle this action is left to the operating system. 

  • The OS decides which component is best to run for implicit intents.

  • Whenever you delegate responsibility to another application from your application, you use Implicit Intents.

Let us see an example:

                Intent sendIntent = new Intent();

                         sendIntent.setAction(Intent.ACTION_SEND); 




Let us now observe a couple of examples to see how Intent works, how you pass data and how you use Implicit Intents to delegate responsibilities to other apps.

 

 

Friday 9 October 2015

Storage Options

Storage Options

  • Android provides several options for you to save persistent application data.
  • The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires. 


 Your data storage options are the following:
Store private primitive data in key-value pairs.
Store private data on the device memory.
Store public data on the shared external storage.
Store structured data in a private database.
Store data on the web with your own network server.
Using Shared Preferences:
  • The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. 
  • You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. 
  • This data will persist across user sessions (even if your application is killed).
To get a SharedPreferences object for your application, use one of two methods:
  • getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.


  • getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
    To write values:
  • Add values with methods such as putBoolean() and putString().
  • Commit the new values with commit().

    Example : 
    To Store the data into Shared preferences
    SharedPreferences sharedpreferences = getSharedPreferences(“MyPreferences”, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(“Myname”, “xyz”);
    editor.commit();

    To get the data from Shared preferences


    String name = SharedPreferences.putString(“Myname”,””);


Using the Internal Storage:
  • You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). 

  • When the user uninstalls your application, these files are removed.

    To create and write a private file to the internal storage:
  • Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.
  • Write to the file with write().
  • Close the stream with close().
To read a file from internal storage:
  1. Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
  2. Read bytes from the file with read().
  3. Then close the stream with close().
Saving cache files:
  • If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.

  • When the device is low on internal storage space, Android may delete these cache files to recover space.

  • However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.
Using the External Storage:
  • Every Android-compatible device supports a shared "external storage" that you can use to save files. 

  • This can be a removable storage media (such as an SD card) or an internal (non-removable) storage.

  • Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.
Getting access to external storage:
In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions.
For example:
<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>
If you need to both read and write files, then you need to request only the WRITE_EXTERNAL_STORAGE permission, because it implicitly requires read access as well.

Example : 
FileOutputStream outputStream;
File file = new  
File(Environment.getExternalStoragePublicDirectory(
           Environment.DIRECTORY_PICTURES), “hai.txt”);
try {
  outputStream = new FileOutputStream(file);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
 e.printStackTrace();

}
Using Databases:
  • Android provides full support for SQLite databases. Any databases you create will be accessible by name to any class in the application, but not outside the application.

  • The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database.

  • You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've defined. 

  • To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.
    • You can execute SQLite queries using the SQLiteDatabase query() methods, which accept various query parameters, such as the table to query, the projection, selection, columns, grouping, and others. 

    • For complex queries, such as those that require column aliases, you should use SQLiteQueryBuilder, which provides several convienent methods for building queries.

    • Every SQLite query will return a Cursor that points to all the rows found by the query.

    • The Cursor is always the mechanism with which you can navigate results from a database query and read rows and columns.
    Using a Network Connection:
    You can use the network (when it's available) to store and retrieve data on your own web-based services. To do network operations, use classes in the following packages: