Wednesday 6 June 2018

Complete download file/image from server in android

1. Complete download file/image from server in android.
2. If file was downloaded in-complete then it will be deleted from storage and if user again try to download then it will download complete file.

Step-1

 Create Utils class and put below methods inside-

  public File createFileDirectory(Context context) {
        if (Utils.isSdCardAvailable() && Utils.isExternalStorageWritable()) {
            directory = new File(Utils.getDirectory());
        } else {
            ContextWrapper cw = new ContextWrapper(context);
            directory = cw.getDir(cw.getString(R.string.folder_name), Context.MODE_PRIVATE);
        }
        return directory;
    }

    public static String getDirectory() {
        String dirPath = null;
        try {
            dirPath = Environment.getExternalStorageDirectory() + subRootFolder;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dirPath;
    }

    /* Checks if external storage is available for read and write */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available for read and write */
    public static boolean isSdCardAvailable() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

Step -2

 MyActivity implements DownloadingAsync.IDownloadAttachment-

    File directory = null;
    String savingPath = null;


    boolean isFileAlreadyDownloaded(String mFile) {
        if (mFile != null) {
            Utils utils = new Utils();
            directory = utils.createFileDirectory(this);
            savingPath = directory + File.separator + mFile;
            File file = new File(savingPath);
            if (file.exists()) {
                return true;
            }
        }
        return false;
    }


    String fileUrl = UrlFactory.IMG_BASEURL +mFilteredList.get(position).getDownload_path();
    String file_name = mFilteredList.get(position).getFile_name();

     if (isFileAlreadyDownloaded(file_name)) {
                        Toast.makeText(getApplicationContext(), MyActivity.this.getString(R.string.file_already_downloaded), Toast.LENGTH_LONG).show();
                    } else {
                        if (Build.VERSION.SDK_INT >= 23) {
                            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    == PackageManager.PERMISSION_GRANTED) {
                                new DownloadingAsync(MyActivity.this, file_name, fileUrl, directory).execute();
                            } else {
                                ActivityCompat.requestPermissions(MyActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                            }
                        } else {
                            new DownloadingAsync(MyActivity.this, file_name, fileUrl, directory).execute();
                        }
      }


    @Override
    public void isAttachmentDownloaded(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        myDealsListAdapter.notifyDataSetChanged();
    }

Step-3

public class DownloadingAsync extends AsyncTask<Void, Void, Void> {
    private static final String TAG = "Download Task";
    private Context context;
    private String file_name;
    private String downloadUrl;
    private File outputFile = null;
    private long total = 0;
    private int contentLength = 0;
    private File mFileDirectory;
    private IDownloadAttachment iDownloadAttachment;
    private String deliverMessage = null;
    private ProgressDialog dialog;

    public DownloadingAsync(Context context, String file_name, String downloadUrl, File directory) {
        this.context = context;
        this.file_name = file_name;
        this.downloadUrl = downloadUrl;
        this.mFileDirectory = directory;
        iDownloadAttachment = (IDownloadAttachment) context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(context);
        dialog.setMessage("Downloading started, please wait.");
        dialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {

        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        if (outputFile != null) {
            iDownloadAttachment.isAttachmentDownloaded(deliverMessage);
      /*    MimeTypeMap map = MimeTypeMap.getSingleton();
            String ext = MimeTypeMap.getFileExtensionFromUrl(file_name);
            String type = map.getMimeTypeFromExtension(ext);

            if (type == null)
              //  type = ";

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data = Uri.fromFile(outputFile);

            intent.setDataAndType(data, type);

            context.startActivity(intent); */
        }
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            String savingPath = null;
            URL url = new URL(downloadUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            //connect
            urlConnection.connect();
            switch (urlConnection.getResponseCode()) {
                case HttpURLConnection.HTTP_OK: {
                    contentLength = urlConnection.getContentLength();

                    //If File is not present create directory
                    if (!mFileDirectory.exists()) {
                        mFileDirectory.mkdir();
                    }
                   /* File parent = directory.getParentFile();
                    if (parent != null)
                        parent.mkdirs();*/

                    savingPath = mFileDirectory + File.separator + file_name;
                    outputFile = new File(mFileDirectory, file_name);

                    /**
                     * CHECK INCOMPLETE DOWNLOADED FILE
                     * IF TRUE THE DELETE THE INCOMPLETE FILE AND START DOWNLOAD        SAME FILE AGAIN
                     */
                    //**********************************************
                    File file = new File(savingPath);
                    if (file.exists()) {
                        if (file.length() != contentLength) {
                            if (outputFile.exists()) {
                                outputFile.delete();
                                     System.out.println(context.getString(R.string.incomplete_download_file_deleted));
                            }
                        } else {
                            contentLength = 0;
                            deliverMessage = context.getString(R.string.file_already_downloaded);
                            return null;
                        }
                    }
                    //**********************************************
                    try {
                        outputFile.createNewFile();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    try {
                        InputStream inputStream = urlConnection.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(outputFile);
                        int bytesRead = -1;
                        byte[] buffer = new byte[4096];
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            total += bytesRead;
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        outputStream.flush();
                        outputStream.close();
                        inputStream.close();

                    } catch (OutOfMemoryError e) {
                        // TODO: handle exception
                    }

                    if (total == contentLength) {
                        deliverMessage = context.getString(R.string.file_download_completed);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.d(TAG, "Error : IOException " + e);
            e.printStackTrace();
        } catch (Exception e) {
            Log.d(TAG, "Error: Exception " + e);
        }

        return null;
    }

    public interface IDownloadAttachment {
        void isAttachmentDownloaded(String message);
    }
}

Capture image from camera and set to imageview with runtime permission

private int hasCameraPermission;
private List<String> permissions = new ArrayList<>();
private final static int PERMISSION_CODE = 100;
private Bitmap mBitmap=null;
private String mImagePath = null;

Step-1

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkCameraPermissions()) {
        openCamera();
    } else {
        requestCameraPermissions();
    }
} else {
    openCamera();
}

private boolean checkCameraPermissions() {
    hasCameraPermission= ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (hasCameraPermission== PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    return false;
}

@RequiresApi(api = Build.VERSION_CODES.M)
private void requestCameraPermissions() {
    if (hasCameraPermission!= PackageManager.PERMISSION_GRANTED) {
        permissions.add(android.Manifest.permission.CAMERA);
    }
    if (!permissions.isEmpty()) {
        requestPermissions(permissions.toArray(new String[permissions.size()]), PERMISSION_CODE);
    }
}

Step-2
private void openCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA_REQUEST);
}


Step-3

@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
   
    if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) {
        if (data != null && data.getExtras() != null) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");

            // CALL THIS METHOD TO GET THE URI FROM THE BITMAP            Uri mUri = getImageUri(getApplicationContext(), photo);

            // CALL THIS METHOD TO GET THE ACTUAL PATH            File mFile = new File(getRealPathFromURI(mUri));

            // Save a file: path for use with ACTION_VIEW intents            mImagePath = mFile.getAbsolutePath();

            Bitmap bm = BitmapFactory.decodeFile(mImagePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object            byte[] byteArrayImage = baos.toByteArray();
            String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
            byte[] decodeResponse = Base64.decode(encodedImage, Base64.DEFAULT | Base64.NO_WRAP);
            mBitmap= BitmapFactory.decodeByteArray(decodeResponse, 0, decodeResponse.length); // load
            mBitmap= Bitmap.createScaledBitmap(mBitmap, 400, 400, false);

            imageView.setImageBitmap(mBitmap);
        
        }
    } 
}

public Uri getImageUri(Context mContext, Bitmap image) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), image, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(index);
}

Thursday 31 May 2018

Load Image from gallery

@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    Bitmap bitmap = null;
    String selectedImagePath = null;
 
   if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) {
      if (data != null) {
        Uri selectedImage = data.getData();
        selectedImagePath = getPath(selectedImage);
        String[] filePath = {MediaStore.Images.Media.DATA};
        Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePath[0]);
        selectedImagePath = c.getString(columnIndex);
        c.close();
        if (selectedImagePath != null) {
            Bitmap bm = BitmapFactory.decodeFile(selectedImagePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object            byte[] byteArrayImage = baos.toByteArray();
            String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
            byte[] decodeResponse = Base64.decode(encodedImage, Base64.DEFAULT | Base64.NO_WRAP);
            bitmap = BitmapFactory.decodeByteArray(decodeResponse, 0, decodeResponse.length); // load            bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, false);
            iv_profile.setImageBitmap(bitmap);
            imageUpload(selectedImagePath);
        }
    } 
}

Wednesday 23 May 2018

Toolbar search view implementation in fragment

menu_action_search.xml-

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.activities.MyActivity">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="always" />

</menu>



  Class- MyFragment.java

  private MyFilterAdpater mAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mAdapter = new MyFilterAdpater(getContext(), mArrayList);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onPrepareOptionsMenu(menu);
        inflater.inflate(R.menu.menu_action_search, menu);
        MenuItem item = menu.findItem(R.id.action_search);
        searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                searchView.clearFocus();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                final List<MyModel> filteredList = filter(mArrayList, s.toLowerCase());
                mAdapter.setFilter(filteredList);
                return true;
            }
        });

    }

      private List<MyModel.Data> filter(List<MyModel.Data> models, String query) {
        query = query.toLowerCase();
        final List<MyModel.Data> filteredList = new ArrayList<>();
        for (MyModel model : models) {
            final String text = (model.getCustmorName()).toLowerCase();
            if (text.contains(query)) {
                filteredList.add(model);
            }
        }
        return filteredList;
    }

Class- MyFilterAdpater

   private ArrayList<MyModel>  mResultList;

   public void setFilter(List<MyModel.Data> model) {
        mResultList = new ArrayList<>();
        mResultList.addAll(model);
        notifyDataSetChanged();
    }

Thursday 17 May 2018

Download attached file from url in sdcard or device internal memory in android


Utils class-

  public File createFileDirectory(Context context) {
        if (Utils.isSdCardAvailable() && Utils.isExternalStorageWritable()) {
            directory = new File(Utils.getDirectory());
        } else {
            ContextWrapper cw = new ContextWrapper(context);
            directory = cw.getDir(cw.getString(R.string.folder_name), Context.MODE_PRIVATE);
        }
        return directory;
    }

    public static String getDirectory() {
        String dirPath = null;
        try {
            dirPath = Environment.getExternalStorageDirectory() + subRootFolder;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dirPath;
    }

    /* Checks if external storage is available for read and write */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available for read and write */
    public static boolean isSdCardAvailable() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }


 MyActivity implements DownloadingAsync.IDownloadAttachment-

    File directory = null;
    String savingPath = null;


    boolean isFileAlreadyDownloaded(String mFile) {
        if (mFile != null) {
            Utils utils = new Utils();
            directory = utils.createFileDirectory(this);
            savingPath = directory + File.separator + mFile;
            File file = new File(savingPath);
            if (file.exists()) {
                return true;
            }
        }
        return false;
    }


    String fileUrl = UrlFactory.IMG_BASEURL +mFilteredList.get(position).getDownload_path();
    String file_name = mFilteredList.get(position).getFile_name();

     if (isFileAlreadyDownloaded(file_name)) {
                        Toast.makeText(getApplicationContext(),  MyActivity.this.getString(R.string.file_already_downloaded), Toast.LENGTH_LONG).show();
                    } else {
                        if (Build.VERSION.SDK_INT >= 23) {
                            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    == PackageManager.PERMISSION_GRANTED) {
                                new DownloadingAsync(MyActivity.this, file_name, fileUrl, directory).execute();
                            } else {
                                ActivityCompat.requestPermissions(MyActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                            }
                        } else {
                            new DownloadingAsync(MyActivity.this, file_name, fileUrl, directory).execute();
                        }
      }


    @Override
    public void isAttachmentDownloaded(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        myDealsListAdapter.notifyDataSetChanged();
    }


public class DownloadingAsync extends AsyncTask<Void, Void, Void> {
    private static final String TAG = "Download Task";
    private Context context;
    private String file_name;
    private String downloadUrl;
    private File outputFile = null;
    private long total = 0;
    private int contentLength = 0;
    private File mFileDirectory;
    private IDownloadAttachment iDownloadAttachment;
    private String deliverMessage = null;
    private ProgressDialog dialog;

    public DownloadingAsync(Context context, String file_name, String downloadUrl, File directory) {
        this.context = context;
        this.file_name = file_name;
        this.downloadUrl = downloadUrl;
        this.mFileDirectory = directory;
        iDownloadAttachment = (IDownloadAttachment) context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(context);
        dialog.setMessage("Downloading started, please wait.");
        dialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {

        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        if (outputFile != null) {
            iDownloadAttachment.isAttachmentDownloaded(deliverMessage);
      /*    MimeTypeMap map = MimeTypeMap.getSingleton();
            String ext = MimeTypeMap.getFileExtensionFromUrl(file_name);
            String type = map.getMimeTypeFromExtension(ext);

            if (type == null)
              //  type = ";

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data = Uri.fromFile(outputFile);

            intent.setDataAndType(data, type);

            context.startActivity(intent); */
        }
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            String savingPath = null;
            URL url = new URL(downloadUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            //connect
            urlConnection.connect();
            switch (urlConnection.getResponseCode()) {
                case HttpURLConnection.HTTP_OK: {
                    contentLength = urlConnection.getContentLength();

                    //If File is not present create directory
                    if (!mFileDirectory.exists()) {
                        mFileDirectory.mkdir();
                    }
                   /* File parent = directory.getParentFile();
                    if (parent != null)
                        parent.mkdirs();*/

                    savingPath = mFileDirectory + File.separator + file_name;
                    outputFile = new File(mFileDirectory, file_name);

                    /**
                     * CHECK INCOMPLETE DOWNLOADED FILE
                     * IF TRUE THE DELETE THE INCOMPLETE FILE AND START DOWNLOAD SAME FILE AGAIN
                     */
                    //**********************************************
                    File file = new File(savingPath);
                    if (file.exists()) {
                        if (file.length() != contentLength) {
                            if (outputFile.exists()) {
                                outputFile.delete();
                                System.out.println(context.getString(R.string.incomplete_download_file_deleted));
                            }
                        } else {
                            contentLength = 0;
                            deliverMessage = context.getString(R.string.file_already_downloaded);
                            return null;
                        }
                    }
                    //**********************************************
                    try {
                        outputFile.createNewFile();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    try {
                        InputStream inputStream = urlConnection.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(outputFile);
                        int bytesRead = -1;
                        byte[] buffer = new byte[4096];
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            total += bytesRead;
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        outputStream.flush();
                        outputStream.close();
                        inputStream.close();

                    } catch (OutOfMemoryError e) {
                        // TODO: handle exception
                    }

                    if (total == contentLength) {
                        deliverMessage = context.getString(R.string.file_download_completed);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.d(TAG, "Error : IOException " + e);
            e.printStackTrace();
        } catch (Exception e) {
            Log.d(TAG, "Error: Exception " + e);
        }

        return null;
    }

    public interface IDownloadAttachment {
        void isAttachmentDownloaded(String message);
    }
}

Add .gitignore file in android studio project

When we compile android project then few auto generated file automatically generated.
These auto generated files are not required during code commit. We can ignore auto
generated file from android project using below .gitignore file.

Follow below steps to add .gitignore file in your git project directory.

1. Open notepad and copy paste below text.
2. Save it using file name like abc.gitignore.
3. Put .gitignore file at root directory of project. After that clean your project.


#built application files
*.apk
*.ap_

# files for the dex VM
*.dex

# Java class files
*.class

# built native files (uncomment if you build your own)
# *.o
# *.so

# generated files
bin/
gen/

# Ignore gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Windows thumbnail db
Thumbs.db

# OSX files
.DS_Store

# Eclipse project files
.classpath
.project

# Android Studio
*.iml
.idea
#.idea/workspace.xml - remove # and delete .idea if it better suit your needs.
.gradle
build/

#NDK
obj/

Wednesday 11 April 2018

Android Objective type Questions with Answers

Q1) Once installed on a device, each Android application lives in_______?  a)device memory  b)external memory  c) security sandbox  d)None of the above Ans) c Q2)Parent class of Activity?  a)Object  b)Context  c)ActivityGroup  d)ContextThemeWrapper Ans) d Q3)What are the Direct subclasses of Activity?  a)AccountAuthenticatorActivity  b) ActivityGroup  c) ExpandableListActivity  d) FragmentActivity  e) ListActivity  f) all the aove Ans) f Q4)What are the indirect Direct subclasses of Activity?  a)LauncherActivity  b)PreferenceActivity  c)TabActivity  d)All the above Ans) d
Q5)Parent class of Service?  a)Object  b)Context  c) ContextWrapper  d)ContextThemeWrapper Ans) c Q6)What are the indirect Direct subclasses of Services?  a) RecognitionService  b) RemoteViewsService   c)SpellCheckerService  d)InputMethodService Ans) d
Q7)Which component is not activated by an Intent?  a)Activity  b)Services  c)ContentProvider  d)BroadcastReceiver Ans) c
Q8)When contentProvider would be activated?  a)Using Intent  b)Using SQLite  c)Using ContentResolver  d)None of the above Ans) c
Q9)Which of the  important device characteristics that you should consider as you design and develop your application?  a)Screen size and density  b)Input configurations  c)Device features  d)Platform Version  e)All of the above Ans) e
Q10)Which are the screen sizes in Android?  a)small  b)normal  c)large  d)extra large  e)All of the above Ans) e
Q11)Which are the  screen densities in Android?  a)low density  b)medium density  c)high density  d)extra high density  e)All of the above Ans) e
Q12)You can shut down an activity by calling its _______ method  a)onDestory()  b)finishActivity()  c)finish()  d)None of the above Ans) c
Q13)What is the difference between Activity context and Application Context?  a) The Activity instance is tied to the lifecycle of an Activity.     while the application instance is tied to the lifecycle of the application,  b) The Activity instance is tied to the lifecycle of the application,     while the application instance is tied to the lifecycle of an Activity.  c) The Activity instance is tied to the lifecycle of the Activity,     while the application instance is tied to the lifecycle of an application.  d) None of the above Ans) a
Q14)Which one is NOT related to fragment class?  a)DialogFragment  b)ListFragment  c)PreferenceFragment  d)CursorFragment Ansa)d
Q15)Definition of Loader?  a) loaders make it easy to asynchronously load data in an activity or fragment.  b) loaders make it easy to synchronously load data in an activity or fragment.  c) loaders does not make it easy to asynchronously load data in an activity or fragment.  d) None of the above. Ans) a
Q16)Characteristics of the  Loaders?  a)They are available to every Activity and Fragment.  b)They provide asynchronous loading of data.  c)They monitor the source of their data and deliver new results when the content changes.  d)They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.  e)All of the above. Ans) e
Q17)How many ways to start services?  a)Started  b)Bound  c)a & b  d)None of the above. Ans) c Q18)If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the ________class?  a) Messenger   b) Binder   c) AIDL   d)None of the above Ans) b
Q19)If you need your interface to work across different processes, you can create an interface for the service with a ________?   a)Binder   b)Messenger   c)AIDL   d) b or c Ans) d
Q20)AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread.   a)true   b)false Ans) a
Q21)Layouts in android?  a)Frame Layout  b)Linear Layout  c)Relative Layout  d)Table Layout  e)All of the above Ans) e
Q22) Dialog classes in android?   a)AlertDialog   b)ProgressDialog   c)DatePickerDialog   d)TimePickerDialog   e)All of the above Ans) e
Q23)If you want share the data accross the all applications ,you should go for?   a)Shared Preferences   b)Internal Storage   c)SQLite Databases   d)content provider Ans) d
Q1. What method you should override to use Android menu system? a. onCreateOptionsMenu() b. onCreateMenu() c. onMenuCreated() d. onCreateContextMenu() Answer: A Q2. What Activity method you use to retrieve a reference to an
Android view by using the id attribute of a resource XML? a. findViewByReference(int id); b. findViewById(int id) c. retrieveResourceById(int id) d. findViewById(String id) Answer: B Q3. Which of the following is not an Android component (i.e. a point from which the system can enter your application)? a. Service b. Activity c. Layout d. Content Provider Answer: C Q4. During an Activity life-cycle, what is the first callback method invoked by the system? a. onStop() b. onStart() c. onCreate() d. onRestore() Answer: C Q5. Which configuration file holds the permission to use the internet? a. Layout file b. Property file c. Java source file d. Manifest file Answer: D
Q6. What does the following line of code achieve? Intent intent = new Intent(FirstActivity.this, SecondActivity.class ); a. Creates an hidden Intent b. Creates an implicit Intent c. Create an explicit Intent d. Starts an activity. Answer: D Q7. Which of the following is NOT a valid usage for Intents? a. Activate and Activity b. Activate a Service c. Activate a Broadcast receiver d. Activate a SQLite DB Connection. Answer: D Q8. Which of the following is not a valid Android resource file name? a. mylayout.xml b. myLayout.xml c. my_layout.xml d. mylayout1.xml Answer: B Q9. Which of these is not defined as a process state? a. Non-visible b. Visible c. Foreground d. Background Answer: A Q10. What is the name of the folder that contains the R.java file? a. src b. res c. bin d. gen Answer: D Q11. What is a correct statement about an XML layout file? a. A layout PNG image file b. A file used to draw the content of an Activity c. A file that contains all application permission information d. A file that contains a single activity widget. Answer: B Q12. What does the src folder contain? a. Image and icon files b. XML resource files c. The application manifest file d. Java source code files Answer: D Q13. Which file specifies the minimum required Android SDK version your application supports? a. main.xml b. R.java c. strings.xml d. AndroidManifest.xml Answer: D Q14. What is the parent class of all Activity widgets? a. ViewGroup b. Layout c. View d. Widget Answer: C Q15.What is the name of the class used by Intent to store additional information? a. Extra b. Parcelable c. Bundle d. DataStore Answer: C

Q16. Which is not included in the Android application framework? a. WindowManager b. NotificationManager c. DialerManager d. PackageManager Answer: C Q17.What Eclipse plugin is required to develop Android application? a. J2EE b. Android Software Development Kit c. Android Development Tools d. Web Development Tools Answer: C Q18.You can create a custom view by extending class Activity. a. True b. False Answer: B Q19.Which of these files contains text values that you can use in your application? a. AndroidManifest.xml b. res/Text.xml c. res/layout/Main.xml d. res/values/strings.xml Answer: D Q20. What does the Android project folder “res/” contain? a. Java Activity classes b. Resource files c. Java source code d. Libraries Answer: B

Q21. What does this code do? Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(android.net.Uri.parse("http://www.androidatc.com")); startActivity(intent); a. Starts a sub-activity b. Starts a service c. Sends results to another activity. d. Starts an activity using an implicit intent. Answer: D Q22. Which of the following is a Java call-back method invoked when a view is clicked? a. Detector b. OnTapListener c. OnClickDetector d. OnClickListener Answer: D Q23.Which of the following is not an Activity lifecycle call-back method?
a. onStart b. onCreate c. onPause d. onBackPressed Answer: D Q24.Which method is used to close an activity? a. Destroy( ) b. Finish( ) c. Stop( ) d. Close( ) Answer: B Q25. Which of the following Activity life-cycle methods is called once the activity is no longer visible? a. onStop b. onPause c. onDestroy d. onHide Answer: A

Q26. Which of the following is a correct Android Manifest statement? a. <uses-permission android:name =”android.Internet”/> b. <uses-permission android:name =”android.Internet”></uses-permission> c. <uses-permission android:name =”android.permission.Internet”> d. <uses-permission android:name =”android. permission.Internet”/> Answer: D Q27.Which of the following is true about attribute android:windowSoftInputMode of the <activity> tag in file AndroidManifest.xml? a. It specifies whether the window is in full screen or not b. It adjusts how the main window of the activity interacts with keyboard c. It adjusts how the window should be launched d. It adjusts the window orientation Answer: B
Q28. Which of the following tools dumps system log messages including stack traces when the device or emulator throws an error? a. DDMS b. Logcat c. Console d. ADB Answer: B Q29. Javascript is enabled by default in a WebView a. True b. False Answer: B Q30. How to enable JavaScript in WebView? a. myWebView. setJavaScriptEnabled(true); b. myWebView.getJavaScriptSettings.setEnabled(true) c. myWebView.getSettings().setJavaScriptEnabled(true); d. Java script is always enabled in WebView Answer: C
Q31.What does the following code achieve? Intent intent = new Intent(FirstActivity.this, SecondActivity.class); startActivityForResult(intent); a. Starts a browser activity b. Starts a sub-activity c. Starts an activity service d. Sends results to another activity. Answer: B Q32. When using an implicit intent, what process does the system use to know what to do with it? a. Intent resolution b. Intent declaration c. Intent overloading d. Intent transition Answer: A Q33.Which of the following is NOT true about the MenuItem interface? a. The MenuItem instance will be returned by the Menu class add(...) method. b. MenuItem can decide the Intent issued when clicking menu components. c. MenuItem can display either an icon or text. d. MenuItem can set a checkbox. Answer: B
Q34. Which of the following is correct about XML layout files? a. In order to display a Ul defined in the XML layout file "main.xml", call the setContentView method of the Activity with the parameter string “main.xml". b. There is no distinction between implementation of the layout definition by code, or by XML layout file. c. In an Eclipse project using the ADT plugin, the XML layout file is found in the /res/layout directory. d. Layout information written in the XML layout file will be converted into code by the Android platform when the screen is displayed. Answer: C
Q35. The DalvikVM core libraries are a subset of which of the following? a. Java ME b. Java SE c. Java EE d. JAX-WS Answer: B Q36. Which of the following is correct about file access in the Android system? a. Generally, files are handled as dedicated resources per each application. b. Files created by an application can be directly accessed by any application. c. The content of file created by application cannot be accessed by any other application. d. You can only access a file from within an Activity. Answer: A
Q37. Which is the correct explanation of ListView? a. It is necessary to use ListView as a set with ListActivity. b. You cannot use a ListView when there is no information to be displayed. c. When displaying a list of Strings using an ArrayAdapter class in ListView, you must save the value in an ArrayList.. d. ListView has a function to display a list of uniquely defined Views other than TextView. Answer: D Q38. Which of following is incorrect about the Toast class? a. You cannot set a custom layout for a Toast. b. A Toast can only create by an Activity class c. There is no need to close or hide a Toast, since it closes automatically. d. A Toast is displayed for only one of the following periods: Toast.LENGHT_SHORT or Toast.LENGTH_LONG Answer: B Q39. Which of the following is not a ContentProvider provided natively by Android? a. The contacts list b. The telephone log c. The bookmarks d. The application list Answer: D
Q40. When creating a file using android.content.Context.openFileOutput("test.txt", 0), where is the file created? a. /data/app/<package name>/files b. /data/data/<package name>/files c. /system/app/<package name>/files d. /system/data/<package name>/files Answer: B Q41. Which of the following is incorrect about the LogCat tool? a. A LogCat view is available as part of the ADT plugin of Eclipse b. You can create a log in your application using Log.v(String, String) c. Each log message has a tag d. Only one of your application can create log entries, and it should be component class (Activity, Service,...etc) Answer: D Q42. Which of the following information is not included in the Manifest file? a. The activities contained in the application b. The permissions required by the application c. The application’s minimum SDK version required. d. The handset model compatible with your application. Answer: D
Q43. Which method should you use to start a sub-activity? a. startActivity(Intent intent) b. startActivityForResult(Intent intent) c. startService(Intent intent) d. startSubActivity(Intent intent) Answer: B Q44. Which package of the following does not have classes needed for Android network connections? a. java.net b. org.apache.http c. android.location d. android.net Answer: C
Q45. Which of the following tools creates certificates for signing Android applications? a. adb b. logcat c. keytool d. certgen Answer: C Q46. Which manifest file permission you should add to allow your application to read the device’s address book? a. READ_ADDRESS_DATA b. READ_PHONE_STATE c. READ_PHONE_CONTACTS d. READ_CONTACTS Answer: D Q47. You can create a custom view by extending class: a. android.widget.View b. android.widget.LinearLayout c. android.view.View d. android.content.Context Answer: C
Q48. In which Activity life-cycle method you should do all of your normal static set up such as: creating views and bind data to lists? a. onResume() b. onStart() c. onCreate() d. onPause() Answer: C Q49. Which of the following lines of code starts activity Activity2 from a current activity Activity1? a. Intent intent = new Intent(this,new Activity2()); startActivity(intent); b. Intent intent = new Intent(new Activity2()); startActivity(intent); c. Intent intent = new Intent (Activity1.class,Activity2.class); startActivity(intent); d. Intent intent = new Intent(this,Activity2.class); startActivity(intent); Answer: d
Q50. Difference between android api and google api?   a)The google API includes Google Maps and other Google-specific libraries. The Android one only includes core android libraries.   b)The google API one only includes core android libraries. The Android  includes Google Maps and other Google-specific libraries.   c)None of the above. Ans) a
Q51. Which of the following methods is called in an Activity when another activity gets into the foreground? a. onStop( ) b. onPause( ) c. onDestroy( ) d. onExit( ) Answer: B
Q52.Which of the following attributes is used to set an activity screen to landscape orientation? a. screenorientation = landscape b. screenOrientation=”landscape” c. android:ScreenOrientation=“landscape” d. android:screenOrientation=”landscape” Answer: D Q53. What is not true about the AndroidManifest.xml file? a. It declares the views used within the application b. It declares user permissions the application requires c. It declares application components d. It declares hardware and software features used within the application Answer: A Q54. If your application is throwing exception android.content.ActivityNotFoundException, how to fix it? a. Create a new activity Java sub-class. b. Rename your activity c. Create the activity layout d. Add the activity to the AndroidManifest Answer: D
Q55. Consider the following code: Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(android.net.Uri.parse("http://www.androidatc.com")); startActivity(intent); Which of the following is correct about the code above? a. It sends a result to a new Activity in a Bundle. b. It will not compile without adding the INTERNET permission the Manifest file. c. It starts any activity in the application that has a WebView in its layout. d. When it is executed, the system starts an intent resolution process to start the right Activity. Answer: D Q56. Which of the following is not true about <activity> tag in AndroidManifest file? a. Declares an activity that implements part of the application's visual user interface b. Contained in <application> tag. c. Declares a single hardware or software feature that is used by the application. d. Has an attribute that specifies the name of the Activity sub-class that implements the activity. Answer: C Q57. Which of the following Android View sub-classes uses the WebKit rendering engine to display web pages? a. PageView b. WebView c. MapView d. HttpClient Answer: B
Q58. Which of the following lines of codes adds zoom controls to a WebView? a. webView.getSettings().setBuiltInZoomControls(true); b. webView.getSettings().setZoomControls(true); c. webView.getZoomSettings().setControls(CONTROLS.enabled); d. Zoom controls are included by default in WebViews. Answer: A Q59. Which of the following best explains the Android option menus? a. It is a popup menu that displays a list of items in a vertical list anchored to the view that invoked the menu. b. It is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame. c. It is the primary collection of menu items for an activity where you should place actions that have a global impact on the app, such as "Search," "Compose email,” and "Settings." d. It is a type of List Activity with predefined headers and footers for special commands. Answer: c Q60. Which of the following best explains the Android context menus? a. It is a popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu. b. It is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame. c. It is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email,” and "Settings." d. It is a sub-menu of an options menu item. Answer: B
Q61. Which of the following applies a context menu on a ListView? (Choose two) a. ListView lv = getListView(); lv.registerForContextMenu() b. ListView lv= getListView(); registerForContextMenu(lv); c. ListView lv = (ListView) findViewById(R.id.list_view_id); registerForContextMenu(lv) d. getListView().setConextMenuEnabled(true) Answer: B & C Q62. Consider the following code : @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Menu"); AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) menuInfo; menu.add(1, cmi.position, 0, "Open file"); menu.add(2, cmi.position, 0, "Save file"); } Which of the following best explains the code above? a. The code inflates an xml file into menu items b.The code creates menu items for context menu programmatically c.The code assign actions to menu items d.The code Opens a menu resource file, modifies it, and saves the changes. Answer: B
Q63. Which of the following does NOT correctly describe interface android.widget.Adapter? a. It is an object that acts as a bridge between a View and underlying data for that view. b. It provides access to the data items. c. It provides access to deprecated ListView methods. d. It is responsible for making a View for each item in the data set. Answer: C Q64.Which of the following methods updates a ListView when an element is added to the data set? a. notify( ) b. notifyAll( ) c. notifyDataSetChanged( ) d. notifyDataSetInvalidate( )
Answer: C Q65. The values of which of the following classes cannot be mapped in a Bundle object? a. Parcelable b. String c. ArrayList d. Context Answer: D Q66. Which of the following is true about method startActivity? a. It starts a new activity and destroys the previous one b. It starts a new activity and sends the previous one to the background. c. It starts a new activity and pauses the previous one. d. It starts a new activity in a paused mode. Answer: B
Q67. Which of the following are primary pieces of information that are required to define in an implicit Intent? a. An action to be performed and data to operate on. b. An action to be performed and a category for additional information. c. A Bundle for extra data. d. A category of additional information and data to operate on. Answer: A Q68. When is the intent resolution process triggered? a. When the system receives an implicit intent to start an activity. b. When an explicit intent starts a service. c. When the system receives an explicit intent to start an activity. d. When the application calls method startAcitivyIntentResolution. Answer: A Q69. Which of the following applies to the onDraw() method of class View? (Choose two) a. It must be overridden if a customize drawing of a view is required. b. It takes two parameters: a Canvas and a View. c. It takes one parameter of type Canvas. d. It uses the Canvas parameter to draw the border of the activity that contains it. Answer: A & C Q70. Which of the following you cannot achieve by creating your own View sub-classes? a. Create a completely new customized View type. b. Combine a group of View components into a new single component. c. Specify when to destroy an activity and all its views. d. Override the way that an existing component is displayed on the screen. Answer: C
Q71. Which of the following is required to allow the Android Developer Tools to interact with your view? a. Provide a constructor that takes a Context and an AttributeSet object as parameters. b. Provide a constructor that takes a Context object as parameter. c. Extend class View. d. Override method onDraw() of class View. Answer: A Q72. What are the main two types of thread in Android? a. Main thread and worker threads. b. Main thread and UI thread. c. Activities and services. d. Main thread and background process. Answer: A Q73. Which of the following AsyncTask methods is NOT executed on the UI thread? a. onPreExecute() b. onPostExecute() c. publishProgress() d. onProgressUpdate() Answer: C Q74. Which of the following is NOT true about method getWindow() of class Dialog do? a. It retrieves the current window for the activity. b. It can be used to access parts of the Windows API. c. It displays the dialog on the screen. d. It returns null if the activity is not visual. Answer: C
Q75. Which of the following is true about the Dialog class? (Choose two) a. You can add a custom layout to a dialog using setContentView(). b. A dialog has a life-cycle independent of the Activity. c. A dialog is displayed on the screen using method show(). d. It does not have a method to access the activity that owns it. Answer: A & C Q76. Which of the following is a NOT valid form of notification invoked by the NotificationManager? a. A Flashing LED. b. A persistent icon in the status bar. c. A sound played. d. A SMS sent. Answer: D Q77. Which of the following a Notification object must contain? (Choose three) a. A small icon. b. A detail text. c. A notification sound. d. A title. Answer: A , B & D.
Q78. Which of the following is the most "resource hungry" part of dealing with Activities on Android
 a.    Closing an app
 b.    Suspending an app 
 c.    Opening a new app 
 d.    Restoring the most recent app
Answer: c