Friday, 30 January 2015

Android Commulative Distribution on Android Api

Silent Mode Toggle App

Java Part : 
package com.example.silent.mode.toggle;

import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.view.View;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.widget.Button;

public class MainActivity extends Activity {

 private AudioManager mAudioManager;
 private boolean mPhoneIsSilent;
 Button normal, silent;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        super.onCreate(savedInstanceState);
        mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
        checkIfPhoneIsSilent();
        setButtonClickListener();
        Log.d("SilentModeApp", "This is a test");
        
    }    
        
    // Does not detect phones current status and just displays to activate Silent Mode 
    
        private void setButtonClickListener() {
        final TextView txt = (TextView) findViewById(R.id.txt1); 
        final Button toggleButton = (Button)findViewById(R.id.silent);
        toggleButton.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
          
         if (mPhoneIsSilent) {
          //change back to normal mode
          
          mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
          mPhoneIsSilent = false;
          toggleButton.setText("Activate Silent Mode");
          txt.setText("Mobile Is In Vibration Mode");
          Toast.makeText(getBaseContext(), "Vibration Mode Activated", 
                  Toast.LENGTH_LONG).show();
         }
          else
          {
           //change to silent mode
           mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
           mPhoneIsSilent = true;
           toggleButton.setText("Activate Vibration Mode");
           txt.setText("Mobile Is In Silent Mode");
           Toast.makeText(getBaseContext(), "Silent Mode Activated",
                            Toast.LENGTH_LONG).show();
          }
         // Now toggle the UI again
         toggleUi(); 
         }
         });
    }
        private void checkIfPhoneIsSilent() {
         int ringermode = mAudioManager.getRingerMode();
         if (ringermode == AudioManager.RINGER_MODE_SILENT) {
          mPhoneIsSilent = true;
         }
         else
         {
          mPhoneIsSilent = false;
         }
        }
        private void toggleUi() {
         ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
         Drawable newPhoneImage;
         if (mPhoneIsSilent){
          newPhoneImage = 
          getResources().getDrawable(R.drawable.phone_silent);
        }
        else
        {
          newPhoneImage = 
           getResources().getDrawable(R.drawable.vibration_on);
        
        }
         imageView.setImageDrawable(newPhoneImage);
    
}
@Override      
protected void onResume() {
 super.onResume();
 checkIfPhoneIsSilent();
 toggleUi();
 
}
}
Here is the XML part
<?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:background="#ffffff"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/phone_icon"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
  android:layout_weight="1"
        android:layout_gravity="center"
        android:layout_marginTop="12dp"
        android:src="@drawable/phone_silent" />

    <Button
        android:id="@+id/silent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="35dp"
        android:text="@string/silent_on" />
    
    <TextView 
        android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="45dp"
      />
       

    </LinearLayout>

Android Json Parsing

Step 1 :
Make an android project.
Step 2 :
Paste the following code in MainActivity. java file.

import java.util.ArrayList;
import java.util.HashMap;

import learn2crack.listview.R;
import learn2crack.listview.library.JSONParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
       ListView list;
       TextView ver;
       TextView name;
       TextView api;
       Button Btngetdata;
       // ProgressBar pgbar;
       ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
       // URL to get JSON Array
       private static String url = "http://10.0.2.2/android/jsonos/";
       // JSON Node Names
       private static final String TAG_OS = "android";
       private static final String TAG_VER = "ver";
       private static final String TAG_NAME = "name";
       private static final String TAG_API = "api";
       JSONArray android = null;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              oslist = new ArrayList<HashMap<String, String>>();
              Btngetdata = (Button) findViewById(R.id.getdata);
              Btngetdata.setOnClickListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View view) {
                           new JSONParse().execute();
                     }
              });
       }

       private class JSONParse extends AsyncTask<String, String, JSONObject> {
              private ProgressDialog pDialog;

              @Override
              protected void onPreExecute() {
                     super.onPreExecute();
                     ver = (TextView) findViewById(R.id.vers);
                     name = (TextView) findViewById(R.id.name);
                     api = (TextView) findViewById(R.id.api);
                     // pgbar = (ProgressBar) findViewById(R.id.progressBar1);

                     pDialog = new ProgressDialog(MainActivity.this);
                     pDialog.setMessage("Getting Data ...");
                     pDialog.setIndeterminate(false);
                     pDialog.setCancelable(true);
                     pDialog.show();
              }

              @Override
              protected JSONObject doInBackground(String... args) {
                     JSONParser jParser = new JSONParser();
                     // Getting JSON from URL
                     JSONObject json = jParser.getJSONFromUrl(url);
                     return json;
              }

              @Override
              protected void onPostExecute(JSONObject json) {
                     // pgbar.setVisibility(View.GONE);
                     pDialog.dismiss();
                     try {
                           // Getting JSON Array from URL
                           android = json.getJSONArray(TAG_OS);
                           for (int i = 0; i < android.length(); i++) {
                                  JSONObject c = android.getJSONObject(i);
                                  // Storing JSON item in a Variable
                                  String ver = c.getString(TAG_VER);
                                  String name = c.getString(TAG_NAME);
                                  String api = c.getString(TAG_API);
                                  // Adding value HashMap key => value
                                  HashMap<String, String> map = new HashMap<String, String>();
                                  map.put(TAG_VER, ver);
                                  map.put(TAG_NAME, name);
                                  map.put(TAG_API, api);
                                  oslist.add(map);
                                  list = (ListView) findViewById(R.id.list);
                                  ListAdapter adapter = new SimpleAdapter(MainActivity.this,
                                                oslist, R.layout.list_v, new String[] { TAG_VER,
                                                              TAG_NAME, TAG_API }, new int[] { R.id.vers,
                                                              R.id.name, R.id.api });
                                  list.setAdapter(adapter);
                                  list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                         @Override
                                         public void onItemClick(AdapterView<?> parent,
                                                       View view, int position, long id) {
                                                Toast.makeText(
                                                              MainActivity.this,
                                                              "You Clicked at "
                                                                           + oslist.get(+position).get("name"),
                                                              Toast.LENGTH_SHORT).show();
                                         }
                                  });
                           }
                     } catch (JSONException e) {
                           e.printStackTrace();
                     }
              }
       }
}
Step 3 :
Make another  package in src file.
Step 4 :
Make another Java class named “JSONParser” in your new package.
Step 5 :
Paste the following code in JSONParser.java file.

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
       static InputStream is = null;
       static JSONObject jObj = null;
       static String json = "";

       // constructor
       public JSONParser() {
       }

       public JSONObject getJSONFromUrl(String url) {
              // Making HTTP request
              try {
                     // defaultHttpClient
                     DefaultHttpClient httpClient = new DefaultHttpClient();
                     HttpPost httpPost = new HttpPost(url);
                     HttpResponse httpResponse = httpClient.execute(httpPost);
                     HttpEntity httpEntity = httpResponse.getEntity();
                     is = httpEntity.getContent();
              } catch (UnsupportedEncodingException e) {
                     e.printStackTrace();
              } catch (ClientProtocolException e) {
                     e.printStackTrace();
              } catch (IOException e) {
                     e.printStackTrace();
              }
              try {
                     BufferedReader reader = new BufferedReader(new InputStreamReader(
                                  is, "iso-8859-1"), 8);
                     StringBuilder sb = new StringBuilder();
                     String line = null;
                     while ((line = reader.readLine()) != null) {
                           sb.append(line + "\n");
                     }
                     is.close();
                     json = sb.toString();
              } catch (Exception e) {
                     Log.e("Buffer Error", "Error converting result " + e.toString());
              }
              // try parse the string to a JSON object
              try {
                     jObj = new JSONObject(json);
              } catch (JSONException e) {
                     Log.e("JSON Parser", "Error parsing data " + e.toString());
              }
              // return JSON String
              return jObj;
       }
}
Step 6:
Paste the following code in activity_main.xml file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="435dp"
        android:layout_above="@+id/getdata" >
    </ListView>

    <Button
        android:id="@+id/getdata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="Get Data" />

</RelativeLayout>
Step 7 :
Make another layout file in layout folder named “list_v.xml”.
Step 8 :
Paste the following code in list_v.xml file.
<?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:id="@+id/vers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/api"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
Step 9:
Paste the following code in AndroidMenifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="learn2crack.listview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

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

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

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


</manifest>

Note :
Json was in format.


{
"android": [
{
"ver": "1.5",
"name": "Cupcake",
"api": "API level 3"
},
{
"ver": "1.6",
"name": "Donut",
"api": "API level 4"
},
{
"ver": "2.0-2.1",
"name": "Eclair",
"api": "API level 5-7"
},
{
"ver": "2.2",
"name": "Froyo",
"api": "API level 8"
},
{
"ver": "2.3",
"name": "Gingerbread",
"api": "API level 9-10"
},
{
"ver": "3.0-3.2",
"name": "Honeycomb",
"api": "API level 11-13"
},

{
"ver": "4.0",
"name": "Ice Cream Sandwich",
"api": "API level 14-15"
},
{
"ver": "4.1-4.3",
"name": "JellyBean",
"api": "API level 16-18"
},
{
"ver": "4.4",
"name": "KitKat",
"api": "API level 19"
}
]
}