Tuesday, 16 April 2013

Introduction of the JSON ,JSONObject & JSONArray in Android.

Be The First To Comment
JSON-
A dense indexed sequence of values. Values may be any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL. Values may not be NaNsinfinities, or of any type not listed here.
JSONArray has the same type coercion behavior and optional/mandatory accessors as JSONObject. See that class' documentation for details.
Warning: this class represents null in two incompatible ways: the standard Java null reference, and the sentinel value NULL. In particular, get fails if the requested index holds the null reference, but succeeds if it holds JSONObject.NULL.
Instances of this class are not thread safe. Although this class is nonfinal, it was not designed for inheritance and should not be subclassed. In particular, self-use by overridable methods is not specified. See Effective Java Item 17, "Design and Document or inheritance or else prohibit it" for further information.

modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObjectsJSONArrays, Strings, Booleans, Integers, Longs, Doubles or NULL. Values may not be nullNaNsinfinities, or of any type not listed here.
This class can coerce values to another type when requested.
  • When the requested type is a boolean, strings will be coerced using a case-insensitive comparison to "true" and "false".
  • When the requested type is a double, other Number types will be coerced using doubleValue. Strings that can be coerced using valueOf(String) will be.
  • When the requested type is an int, other Number types will be coerced using intValue. Strings that can be coerced using valueOf(String) will be, and then cast to int.
  • When the requested type is a long, other Number types will be coerced using longValue. Strings that can be coerced using valueOf(String) will be, and then cast to long. This two-step conversion is lossy for very large values. For example, the string "9223372036854775806" yields the long 9223372036854775807.
  • When the requested type is a String, other non-null values will be coerced using valueOf(Object). Although null cannot be coerced, the sentinel value NULL is coerced to the string "null".
This class can look up both mandatory and optional values:
  • Use getType() to retrieve a mandatory value. This fails with a JSONException if the requested name has no value or if the value cannot be coerced to the requested type.
  • Use optType() to retrieve an optional value. This returns a system- or user-supplied default if the requested name has no value or if the value cannot be coerced to the requested type.
Warning: this class represents null in two incompatible ways: the standard Java null reference, and the sentinel value NULL. In particular, calling put(name, null) removes the named entry from the object but put(name, JSONObject.NULL) stores an entry whose value is JSONObject.NULL.
Instances of this class are not thread safe. Although this class is nonfinal, it was not designed for inheritance and should not be subclassed. In particular, self-use by overrideable methods is not specified. See Effective Java Item 17, "Design and Document or inheritance or else prohibit it" for further information.

1 step-
Create a Android Application Project "JSON_Project".
2 step-
Create a XML file "httpex.xml".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/tvHttp"
        />

</LinearLayout>

3 step-
Create a   Java File " HttpExample.java ". 

package com.example.counterproject;

import java.io.IOException;
import java.security.PublicKey;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.string;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class HttpExample extends Activity {
final static String URL="http://twitter.com";
TextView httpStuff;
HttpClient client;
JSONObject json;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff=(TextView)findViewById(R.id.tvHttp);
client=new DefaultHttpClient();
new Read().execute("text");
}
public JSONObject lastTweet(String username) throws ClientProtocolException, IOException, JSONException{
StringBuilder url=new StringBuilder(URL);
url.append(username);
HttpGet get=new HttpGet(url.toString());
HttpResponse r=client.execute(get);
int status=r.getStatusLine().getStatusCode();
if(status == 200)
{
HttpEntity e = r.getEntity();
String data=EntityUtils.toString(e);
JSONArray timeline= new JSONArray(data);
JSONObject last=timeline.getJSONObject(0);
return last;
}
else
{
Toast.makeText(HttpExample.this, "error", Toast.LENGTH_SHORT);
return null;
}
}

public class Read extends AsyncTask <String, Integer, String>
{

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
json=lastTweet("mybringback");
return json.getString(params[0]);
}catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}


4 step-

 Add permission in Android manifest  file (Internet permission).







Monday, 15 April 2013

How to Create Menus in Android Application.

Be The First To Comment

Menus:
Creating the Menu Helper Methods:

1. Using Eclipse, create a new Android project and name it as Menus.
2. In the MainActivity.java file, add the following statements in bold:


package com.sartaj.Menus;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private void CreateMenu(Menu menu)
{
MenuItem mnu1 = menu.add(0, 0, 0, “Item 1”);
{
mnu1.setAlphabeticShortcut(‘a’);
mnu1.setIcon(R.drawable.icon);
}
MenuItem mnu2 = menu.add(0, 1, 1, “Item 2”);
{
mnu2.setAlphabeticShortcut(‘b’);
mnu2.setIcon(R.drawable.icon);
}
MenuItem mnu3 = menu.add(0, 2, 2, “Item 3”);
{
mnu3.setAlphabeticShortcut(‘c’);
mnu3.setIcon(R.drawable.icon);
}
MenuItem mnu4 = menu.add(0, 3, 3, “Item 4”);
{
mnu4.setAlphabeticShortcut(‘d’);
}
menu.add(0, 4, 4, “Item 5”);
menu.add(0, 5, 5, “Item 6”);
menu.add(0, 6, 6, “Item 7”);
}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0:
Toast.makeText(this, “You clicked on Item 1”,Toast.LENGTH_LONG).show();
return true;
case 1:
Toast.makeText(this, “You clicked on Item 2”,Toast.LENGTH_LONG).show();
return true;

case 2:
Toast.makeText(this, “You clicked on Item 3”,Toast.LENGTH_LONG).show();
return true;
case 3:
Toast.makeText(this, “You clicked on Item 4”,Toast.LENGTH_LONG).show();
return true;
case 4:
Toast.makeText(this, “You clicked on Item 5”,Toast.LENGTH_LONG).show();
return true;
case 5:
Toast.makeText(this, “You clicked on Item 6”,Toast.LENGTH_LONG).show();
return true;
case 6:
Toast.makeText(this, “You clicked on Item 7”,Toast.LENGTH_LONG).show();
return true;
}
return true;
}
}
Options Menu:

1.    Using the same project created in the previous section, add the following statements in bold to the MainActivity.java file:
     
package com.sartaj.Menus;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
MenuChoice( item);
return true;
}
private void CreateMenu(Menu menu)
{
//...
}
private boolean MenuChoice(MenuItem item)
{
//...
}
}
Context Menu:

1.    Using the same project created in the previous section, add the following statements in bold to the MainActivity.java file:
2.     
package com.sartaj.Menus;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn1);
btn.setOnCreateContextMenuListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
MenuChoice( item);
return true;

}
@Override
public void onCreateContextMenu(ContextMenu menu, View view,ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu(menu);
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
super.onContextItemSelected(item);
 MenuChoice(item);
 return true;
}
private void CreateMenu(Menu menu)
{
//...
}
private boolean MenuChoice(MenuItem item)
{
//...
}
}
NOTE: Notice that the shortcut keys for the menu items do not work. To enable the shortcuts keys, you need to call the setQuertyMode() method of the Menu object, like this:
Context menu do not show icon at all,so there is no need to draw icon in case of Context menu.

{
{
}
}

Broadcast Receiver in Android Application.(Sending Message one Emulator to another Emulator.

Be The First To Comment

 Broadcast Receiver
In this project we make an application which will be able to broadcast a event say a message to a sender when it receive a particular type of event say a particular type of message.
We extend this application to the application we made to send a message.
1)create  a new java file named as ReceiveSms( in the package which we use in developing application for sending a sms) and extends with BroadcastReceiver and match it as:
package com.sartaj.sms;   //package name

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

public class RecieveSms extends BroadcastReceiver {

       public void onReceive(Context arg0, Intent arg1) {
              // TODO Auto-generated method stub

              // ---get the SMS message passed in---
              Bundle bundle = arg1.getExtras();
              SmsMessage[] msgs = null;
      
              String str2 = "";
              if (bundle != null) {
                     // ---retrieve the SMS message received---
                     Object[] pdus = (Object[]) bundle.get("pdus");
                     msgs = new SmsMessage[pdus.length];

                     for (int i = 0; i < msgs.length; i++) {

                          
                           msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                          
                           str2 = msgs[i].getOriginatingAddress();
                          
                     }

             
                     SmsManager sm = SmsManager.getDefault();
             
                     sm.sendTextMessage(str2, null, "I m in Metting", null, null);
             

              }

       }

}

2)Add the permission(android.permission.RECEIVE_SMS)in AndroidManifest.xml also add the receiver attribute in application attribute of AndriodManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.sartaj.sms"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="9" />
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Sms"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="RecieveSms">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
            </intent-filter>
        </receiver>
      

    </application>
</manifest>

3)Now run the application on emulator say 5554.Create another emulator say 5556 .When we send a message from 5556 to 5554 it will automatically send a message to the sender that is 5556.
 

© 2011 Reach 2 Android - Tutorials on Android and PHP - Designed by Mukund | ToS | Privacy Policy | Sitemap

About Us | Contact Us | Write For Us