Search This Blog

Wednesday 15 April 2020

XML and JSON are both designed to form a simple and standartized way of describing different kinds of hierarchical data structures and to facilitate their transportation and consumption in a standartized way. Nonetheless, there are few substantial differences that deserve attention. 
 

The major differences

Take a look at the following example:
JSON :





XML :




Clearly XML is somehow easier to understand for a human. That’s why it’s commonly used for configuration files (although lambdas and fluent APIs are recently emerging as a way of configuration). JSON, on ther other hand, is harder to read, but only from a human perspective. ​​
Aside from that, XML is also a markup language (as the name suggests) and is therefore suitable for document description – the hierarchical elements can also have attributes, which is not present in JSON. On ther other hand, JSON has a very concise syntax for defining lists of elements, which makes it preferrable for text format object serialization.
XML is also the usual choice of base when it comes to Domain Specific Languages
 

JSON and JavaScript

JSON's succinct syntax makes it very light and compact. It is also easier to parse from JavaScript, and that’s one of the main reasons it’s preferred for browser-based client-side applications (note that JSON stands for JavaScript Object Notation, it’s just natural). If you want to work with XML from JavaScript, you'll need to use an extra library for that. With JSON, you can just parse the message (let’s say with JSON.Parse() ) and work directly with js objects.

3 taire

details.java

package com.ann;




public class details {

String name,age,place;




public void setName(String name) {

this.name=name;

// TODO Auto-generated method stub




}



public void setAge(String age) {

this.age=age;

// TODO Auto-generated method stub




}



public void setPlace(String place) {

this.place=place;

// TODO Auto-generated method stub




}

public String getName(){

return name;



}
public String getAge(){

return age;





}

public String getPlace(){

return place;



}




}

2________________
package com.ann;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class databasehandler extends SQLiteOpenHelper {
 private static final String MYDB="mydb";
 private static final String MYTB="USER";

 public databasehandler(Context context) {
  super(context,MYDB, null, 32);
  // TODO Auto-generated constructor stub
 }
 public void onCreate(SQLiteDatabase db) {
  // TODO Auto-generated method stub
  db.execSQL("create table if not exists "+MYTB+"(name text,age text,qualification text,place text)");

 }
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // TODO Auto-generated method stub
  db.execSQL("drop table if exists "+MYTB);
  onCreate(db);
 }
public void insert(details d) {
 SQLiteDatabase db=getWritableDatabase();
 ContentValues cv=new ContentValues();
 cv.put("name",d.getName());
 Log.v("name",d.getName());
 cv.put("age",d.getAge());
 Log.v("age",d.getAge());

 cv.put("place",d.getPlace());
 Log.v("place",d.getPlace());

    db.insert(MYTB,null,cv);
    Log.v("data","inserted");
}
public ArrayList<String> resultdata() {
 ArrayList<String> results=new ArrayList<String>();
 SQLiteDatabase db = this.getReadableDatabase();
 try {
  Cursor c=null;
   c = db.rawQuery("select * from "+MYTB, null);

  if (c!= null) {
  Log.v("cursor","notnull");
   c.moveToFirst();

   do {
     int cc=c.getCount();
     Log.v("cursor count",""+cc);
  
     String Name = c.getString(c.getColumnIndex("name"));
     Log.v("Name",Name);
     String Age = c.getString(c.getColumnIndex("age"));
     Log.v("Age",Age);
  
  
  
     String Place=c.getString(c.getColumnIndex("place"));
     Log.v("Place",Place);
  
     results.add("Name: " +Name+"\n Age : " +Age+"\n Place :"+Place);
     //results.add("dfrty");
     Log.v("Array",""+results);
    } while (c.moveToNext());
   }


 } catch (SQLiteException se) {
  Log.e(getClass().getSimpleName(),
    "Could not create or Open the database");
 }

 return results;
}

}   3------------------------------- package com.ann;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class DatabaseThreeActivity extends Activity {
 EditText ename,eage,eplace;
 String name,age,place;
 ListView lv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ename=(EditText)findViewById(R.id.editText1);
        eage=(EditText)findViewById(R.id.editText2);
        eplace=(EditText)findViewById(R.id.editText3);
        lv=(ListView)findViewById(R.id.listView1);
    }
    public void submit(View v){
     name=ename.getText().toString();
     age=eage.getText().toString();
     place=eplace.getText().toString();
     details d=new details();
     d.setName(name);
     d.setAge(age);
     d.setPlace(place);
     databasehandler db=new databasehandler(this);
     db.insert(d);
        Toast.makeText(getApplicationContext(),"Details Submitted Successfully", Toast.LENGTH_LONG).show();
   
    }
    public void view(View v){
     databasehandler db=new databasehandler(getApplicationContext());
     ArrayList<String > result=new ArrayList<String>();
     result=db.resultdata();
     Log.v("reached",""+result);
   
     if (result.isEmpty()==true)
     //Log.v("after clear",""+result);
   
     {
      Toast.makeText(getApplicationContext(),"Database empty",Toast.LENGTH_LONG).show();
   
     }
     else
     {
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, result);
      lv.setAdapter(adapter);
     }
    }
    public void updatate(View v){

 }
}





details.java

package com.ann;





public class details {
String name,age,place;





public void setName(String name) {
this.name=name;
// TODO Auto-generated method stub



}



public void setAge(String age) {
this.age=age;
// TODO Auto-generated method stub



}



public void setPlace(String place) {
this.place=place;
// TODO Auto-generated method stub



}

public String getName(){
return name;



}

public String getAge(){
return age;




}

public String getPlace(){
return place;



}



}

Tuesday 5 June 2012

Questions and Answer for Android Interview


1)What is Android?

Android is a stack of software for mobile devices which includes an Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java languages byte code which later transforms into .dex format files.
2)Can I write code for Android using C/C++?
Android applications are written using the Java programming language.
Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.
Android only supports applications written using the Java programming language at this time.
3)What languages does Android support for application development?
Android applications are written using the Java programming language.
4)What Virtual Machine Android runs on?
Dalvik virtual machine
5)Android Latest Version?
Android 4.0
 6)Creating an Android Application using the Eclipse Plugin
Using the Android Eclipse plugin is the fastest and easiest way to start creating a new Android application. The plugin automatically generates the correct project structure for your application, and keeps the resources compiled for you automatically.
It is still a good idea to know what is going on though. Take a look at Overview of an Android Application to understand the basics of how an Android application works.
It is also recommended that you take a look at the ApiDemos application and the other sample applications in the samples/ folder in the SDK.
Finally, a great way to started with Android development in Eclipse is to follow both the Hello Android and Notepad code tutorials. In particular, the start of the Hello Android tutorial is an excellent introduction to creating a new Android application in Eclipse.
7)What is Android Runtime?
Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.
8)Features of Android
  • Application framework enabling reuse and replacement of components
  • Dalvik virtual machine optimized for mobile devices
  • Integrated browser based on the open source WebKit engine
  • Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
  • SQLite for structured data storage
  • Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
  • GSM Telephony (hardware dependent)
  • Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
  • Camera, GPS, compass, and accelerometer (hardware dependent)
  • Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE.
Android is a software stack for mobile devices that includes an operating system, middleware and key applications. This early look at the Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
9)Describe the APK format.
The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.

10)What are the advantages of Android?
     The following are the advantages of Android:
 *  The customer will be benefited from wide range of mobile applications to choose,         since the monopoly of wireless carriers like Orange and AT&T will be broken by Google       Android.
* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized
* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in  Android.
11)Describe Briefly the Android Application Architecture

Android Application Architecture has the following components:
Services like Network Operation
Intent - To perform inter-communication between activities or services
Resource Externalization - such as strings and graphics
Notification signaling users - light, sound, icon, notification, dialog etc.
Content Providers - They share data between application.

12)What is an adb

Android Debug Bridge, a command-line debugging application shipped with the SDK. It provides tools to browse the device, copy tools on the device, and forward ports for debugging.
14)What Programming languages does Android support for application development?
Android applications supports using Java Programming Language. which is coded in Java and complied using Android SDK
15)What is APK format.
The file itself is a compressed collection of an AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.
16)How to Translate in android
The Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.
17)What is activity?
An
Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface.
18)What is an action?
A description of something that an Intent sender desires.
19)What Programming languages does Android support for application development?
Android applications supports using Java Programming Language. which is coded in Java and complied using Android SDK.
20)What is a resource?
A user-supplied XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.
21)What is intent in Android?
A class (Intent) will describes what a caller desires to do. The caller will send this intent to Android's intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF document is an intent, and the Adobe Reader apps will be the perfect activity for that intent(class).
22)What is an activity?
A single screen in an application, with supporting Java code.
An activity presents a visual user interface for one focused endeavor the user can undertake.
For example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions.
Each one is implemented as a subclass of the Activity base class.
23)What is a service?
A service doesn’t have a visual user interface, but rather runs in the background for an indefinite period of time.
For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate
something and provide the result to activities that need it.
Each service extends the Service base class.
24)What is a Broadcast receivers?
A broadcast receiver is a component that does nothing but receive and react to broadcast announcements.
For example, announcements that the timezone has changed, that the battery is low or that the user changed a language preference.
All receivers extend the BroadcastReceiver base class.
Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive,
or they may use the NotificationManager to alert the user like(flashing the backlight, vibrating the device, playing a sound)
25)What is a content provider?
A content provider makes a specific set of the application’s data available to other applications.The content provider extends the ContentProvider
base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls.
However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead.
26)How do you define the user interface?
XML Format is the best.
27)Does Android support the Bluetooth serial port profile?
Yes.
28)Can an application be started on powerup?
Yes.

29)What is a Sticky Intent?
sendStickyBroadcast() performs a sendBroadcast (Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves
packet that a communication protocol can pass. The size can be fixed by some standard or decided at the time of connection

Fragmentation is a process of breaking the IP packets into smaller pieces. Fragmentation is needed when the datagram is larger than the MTU. Each fragment becomes a datagram in itself and transmitted independently from source. When received by destination they are reassembled.
the same as sendBroadcast(Intent).

30)Example for sticky broadcast
When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
31)How to start a browser instance with some url ?
1
Intent intent = new Intent(Intent.ACTION_VIEW);
2
Uri u = Uri.parse("http://google.com");

3
intent.setData(u);
4
startActivity(intent);
//Function called when return from a sub activity.
1
protected void onActivityResult(int requestCode, int resultCode, String data, Bundle extras) {
2
}
32)How to retrieve the device IMEI Number
1
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
2
imei = mTelephonyMgr.getDeviceId();
33)How to call a subactivity?
1
Intent intent = new Intent(this, SubActivity.class);
2
//to pass data

3
addintent.putExtra(name, value);

34)How will you record a phone call in Android? How to get a handle on Audio Stream for a call in Android?
Permissions.PROCESS_OUTGOING_CALLS: Allows an application to monitor, modify, or abort outgoing calls.

35)How the nine-patch Image different from a regular bitmap? or Different between nine-patch Image vs regular Bitmap Image

It is one of a resizable bitmap resource which is being used as backgrounds or other images on the device. The NinePatch class allows drawing a bitmap in nine sections. The four corners are unscaled; the middle of the image is scaled in both axes, the four edges are scaled into one axis.

36)Explain about the exceptions of Android?      

 The following are the exceptions that are supported by Android
 InflateException : When an error conditions are occurred, this exception is thrown
 Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown
 SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
 WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.

37)What dialog boxes are supported in android?Android supports 4 dialog boxes:

AlertDialog: An alert dialog box supports 0 to 3 buttons and a list of selectable elements, including check boxes and radio buttons. Among the other dialog boxes, the most suggested dialog box is the alert dialog box.
ProgressDialog: This dialog box displays a progress wheel or a progress bar. It is an extension of AlertDialog and supports adding buttons.
DatePickerDialog: This dialog box is used for selecting a date by the user.
TimePickerDialog: This dialog box is used for selecting time by the user.

38)Explain IP datagram, Fragmentation and MTU ?           

IP datagram can be used to describe a portion of IP data. Each IP datagram has set of fields arranged in an order. The order is specific which helps to decode and read the stream easily. IP datagram has fields like Version, header length, Type of service, Total length, checksum, flag, protocol, Time to live, Identification, source and destination ip address, padding, options and payload.

MTU:- Maximum Transmission Unit is the size of the largest

39)What is the TTL (Time to Live)? Why is it required?

TTL is a value in data packet of Internet Protocol. It communicates to the network router whether or not the packet should be in the network for too long or discarded. Usually, data packets might not be transmitted to their intended destination within a stipulated period of time. The TTL value is set by a system default value which is an 8-bit binary digit field in the header of the packet. The purpose of TTL is, it would specify certain time limit in seconds, for transmitting the packet header. When the time is exhausted, the packet would be discarded. Each router receives the subtracts count, when the packet is discarded, and when it becomes zero, the router detects the discarded packets and sends a message, Internet Control Message Protocol message back to the originating host.
What’s the difference between file, class and activity in android?
File – It is a block of arbitrary information, or resource for storing information. It can be of any type.
Class – Its a compiled form of .Java file . Android finally used this .class files to produce an executable apk
Activity – An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.

Tuesday 8 May 2012

Worker thread


Worker thread

Worker threads are background threads. They are the threads that are created separately, other than the UI thread. Since blocking the UI thread is restricted according to the rule, user should run the child processes and tasks in worker threads. 

An example for creation and working of worker thread is given below:

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            Bitmap b = loadImageFromNetwork("http://example.com/image.png");
            mImageView.setImageBitmap(b);
        }
    }).start();
}

In the above example code, the download operation is handled by a second thread other than the UI thread. But the program violates the second rule. The imageView from UI thread is manipulating from this worker thread.

According to the second rule, UI could not be accessed from outside the UI thread. Solution for such a restriction is runOnUiThread(Runnable) method. The main or UI thread can be accessed from other threads using runOnUiThread(Runnable) method.
As a result, the specified runnable action passed through this method will run on the UI thread. The action will execute immediately, if the current thread is in the UI itself. Else the action will be posted to the event queue.

An example code:

MainClassName.this.runOnUiThread(new Runnable() {
                    public void run() {
                        textViewObject.setText("Set this " + value from worker thread + "!");
                    }
                });

Only using the methods like runOnUiThread(Runnable), the program can touch the UI views.

Handlers and Runnable

A better solution to process the messages delivered from the UI thread is handlers. The runnable objects can also be processed using the handlers. Runnable is a command that can be executed. It is used to run the code in other thread.

An example that users handlers and runnable objects in worker thread is given here;

WorkerThreadActivity.class

package com.febi.worker;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class WorkerThreadActivity extends Activity{
          ImageView image;
          String url="http://icons.iconarchive.com/icons/icons-land/sport/256/Soccer-Ball-icon.png";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
    }
    public void onClick(View v){ 
        final Handler threadHandler; 
        final Context cbt; 
         
        cbt = this; 
        threadHandler = new Handler(); 
         
        new Thread(new Runnable() { 
            @Override 
            public void run() {
                  
                threadHandler.post(new Runnable() { 
                    @Override 
                    public void run() { 
//                        
                            
                             InputStream is = null;
                             try{
                             URL ulrn = new URL(url);
                        HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
                        is = con.getInputStream();
                             }catch(Exception e)
                             {
                                      Log.i("LOGCAT Run", ""+e);
                             }
                        Bitmap bmp = BitmapFactory.decodeStream(is);

                            
                             ImageView image=(ImageView)findViewById(R.id.imageView1);
                             image.setImageBitmap(bmp);
                    } 
                }); 
            } 
        }).start();
       
      AlertDialog.Builder ab = new AlertDialog.Builder(cbt); 
      ab.setMessage("A message sent from UI thread"); 
      ab.show();
    } 
         
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
   
    <Button android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="Click Me"
        android:onClick="onClick"
        />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

Set permission for Internet in manifest file ;

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