Tuesday, September 15, 2015

accelerometer

package com.example.accelerometer;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener {
    //a TextView  
   private TextView tv;  
   //the Sensor Manager  
   private SensorManager sManager;  
 
   
   
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       
     //get the TextView from the layout file  
       tv = (TextView) findViewById(R.id.tv);  
 
       //get a hook to the sensor service  
       sManager = (SensorManager) getSystemService(SENSOR_SERVICE);  
       
       
       
       
   }
   
   protected void onResume()  
   {  
       super.onResume();  
       /*register the sensor listener to listen to the gyroscope sensor, use the
       callbacks defined in this class, and gather the sensor information as quick
       as possible*/  
       sManager.registerListener(this, sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_FASTEST);  
   }  
   
   
   
   protected void onStop()  
   {  
       //unregister the sensor listener  
       sManager.unregisterListener(this);  
       super.onStop();  
   }  
   
   
   public void onAccuracyChanged(Sensor arg0, int arg1)  
   {  
       //Do nothing.  
   }  
   
   
   public void onSensorChanged(SensorEvent event)  
   {  
       //if sensor is unreliable, return void  
       if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)  
       {  
           return;  
       }  
 
       //else it will output the Roll, Pitch and Yawn values  
       tv.setText("Orientation X (Roll) :"+ Float.toString(event.values[2]) +"\n"+  
                  "Orientation Y (Pitch) :"+ Float.toString(event.values[1]) +"\n"+  
                  "Orientation Z (Yaw) :"+ Float.toString(event.values[0]));  
   }  
   
   
   

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.activity_main, menu);
       return true;
   }

   
}

JSON

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.
Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting temperature only.
{
  "sys":
  {
     "country":"GB",
     "sunrise":1381107633,
     "sunset":1381149604
  },
  "weather":[
  {
     "id":711,
     "main":"Smoke",
     "description":"smoke",
     "icon":"50n"
  }
],
"main":
  {
     "temp":304.15,
     "pressure":1009,
  }
}

JSON - Elements

An JSON file consist of many components. Here is the table defining the components of an JSON file and their description −
Sr.No
Component & description
1
Array([)
In a JSON file , square bracket ([) represents a JSON array
2
Objects({)
In a JSON file, curly bracket ({) represents a JSON object
3
Key
A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
4
Value
Each key has a value that could be string , integer or double e.t.c

JSON - Parsing

For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is:
String in;
JSONObject reader = new JSONObject(in);
The last step is to parse the JSON. An JSON file consist of different object with different key/value pair e.t.c. So JSONObject has a separate function for parsing each of the component of JSON file. Its syntax is given below:
JSONObject sys  = reader.getJSONObject("sys");
country = sys.getString("country");
           
JSONObject main  = reader.getJSONObject("main");
temperature = main.getString("temp");
The method getJSONObject returns the JSON object. The methodgetString returns the string value of the specified key.
Apart from the these methods , there are other methods provided by this class for better parsing JSON files. These methods are listed below −
Sr.No
Method & description
1
get(String name)
This method just Returns the value but in the form of Object type
2
getBoolean(String name)
This method returns the boolean value specified by the key
3
getDouble(String name)
This method returns the double value specified by the key
4
getInt(String name)
This method returns the integer value specified by the key
5
getLong(String name)
This method returns the long value specified by the key
6
length()
This method returns the number of name/value mappings in this object..
7
names()
This method returns an array containing the string names in this object.

Example

To experiment with this example , you can run this on an actual device or in an emulator.
Steps
Description
1
You will use Android studio to create an Android application. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2
Modify src/MainActivity.java file to add necessary code.
3
Modify the res/layout/activity_main to add respective XML components
4
Modify the res/values/string.xml to add necessary string components
5
Run the application and choose a running android device and install the application on it and verify the results


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.jsontutorial"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
       android:minSdkVersion="8"
       android:targetSdkVersion="15" />
   
   <uses-permission android:name="android.permission.INTERNET"/>
   

   <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       <activity
           android:name=".MainActivity"
           android:label="@string/title_activity_main" >
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>

</manifest>



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  android:layout_height="match_parent"
  
  
  
  tools:context=".MainActivity">
  
  <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="JSON example"
     android:id="@+id/textView"
     android:layout_alignParentTop="true"
     android:layout_centerHorizontal="true"
     android:textSize="30dp" />
  
  <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="KJS_JSON"
     android:id="@+id/textView2"
     android:layout_below="@+id/textView"
     android:layout_centerHorizontal="true"
     android:textSize="35dp"
     android:textColor="#ff16ff01" />
     
  <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="New Text"
     android:id="@+id/textView1"
     android:layout_below="@+id/textView2"
      />
</RelativeLayout>





package com.example.jsontutorial;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import android.app.Activity;
import android.os.StrictMode;

import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;




public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       
       TextView output = (TextView) findViewById(R.id.textView1);
       String strJson="{ \"Employee\" :[ { \"id\":\"01\",\"name\":\"Ketan Sarvakar\",\"salary\":\"800000\"} ] } ";
   
       String data = "";
       try {
          JSONObject  jsonRootObject = new JSONObject(strJson);
          
          //Get the instance of JSONArray that contains JSONObjects
          JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
          
          //Iterate the jsonArray and print the info of JSONObjects
          for(int i=0; i < jsonArray.length(); i++){
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             
             int id = Integer.parseInt(jsonObject.optString("id").toString());
             String name = jsonObject.optString("name").toString();
             float salary = Float.parseFloat(jsonObject.optString("salary").toString());
             
             data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
          }
          output.setText(data);
       } catch (JSONException e) {e.printStackTrace();}
    }
 }