Monday, October 28, 2013

10 Great Things About Android 4.3 (Jelly Bean)

As stated on groovypost.com, given below are the tips.

1. Make Restricted Profiles for Users – You can use this feature to ensure that your child does not access anything that you don’t want him to see. This feature helps you decide the apps the user of the profile can access and if he can use Google Play Store for adding new apps.

2. Using an Office Suite for Managing Documents – You can access and edit documents while travelling by using certain great free office suites. Among them is Kingsoft Office that allows you to open no less than 23 types of document files, which include DOC, DOCX, XLS, XLSX, PPT, PPTX or PDF. You can download it from the Google Play Store.

3. Using Google For Getting Information Whenever You Require – Google Now can provide you information as and when you need them. It gives you flight data just before your flight, sports scores for your favorite teams, weather, photo spots and much more. It’s user-friendly and can perform every activity on its own.

4. Not Limiting Yourself to Apps from the Google Play Store – Contrary to iOS, Android permits you to install apps from non-Play Store sources. This helps you in getting better deals on apps that are on offer in other stores. For eg. the Amazon App Store offers a paid app for free each day.

5. Stay Organized with Google Keep – Google Keep was launched in the early part of this year. It’s a user-friendly tool that helps you in keeping yourself organized. It can be used for taking notes like voice recordings, images or text. It can also be used to store shopping lists and allows everything to be synced to your Google Account.

6. Enabling the Emoji Keyboard – Many of us use Emoji for communicating different feelings that traditional emoticons don't offer. For Android 4.3, you have the Emoji keyboard. You need to simply long press the Space bar on the regular Android keyboard and select the Emoji Input. 

7. Enhance the Quality of Your Music – You can enhance the quality of the sound through an equalizer app. Music Equalizer that is available in the Google Play Store is the best and for free. It has presets, and you can also customize your own.

8. Using your Android Device Manager for Locating Your Lost Device – The Android Device Manager is a useful feature allowing you to readily find your device if it is stolen. You can also delete the data on it from a remote location. Off late Google has brought a feature that permits you to set a password on your lost device that can be reset once located.

9. Keeping Your Mobile Data Use In Control – Android’s data usage feature permits you in finding out how much data has been used during a certain period of time. You need to go to Data usage in your device’s Settings menu for locating it. You can then set your billing interval, as well as decide when you should be warned that you’re closing in on your data cap. It can also be set to turn off data completely after a certain amount.

10. Make an Offline Cache of a Google Map – When you are going on a trip and don’t want to use up all your data on Google Map, you can cache the map of the area on your drive.

Wednesday, October 9, 2013

Reading JSON data from asset folder in Android

// Friends.json
{"list":[{"name":"Rajesh"},{"name":"Sudheer"},{"name":"Rao"},{"name":"Wadood"},{"name":"Jitendra"},{"name":"Naidu"},{"name":"Srinu"},{"name":"Sujith"},{"name":"Sathish"},{"name":"Amju"},{"name":""}]}

// parsing class

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

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


public class JsonParsingHelper {

private static final String TAG = JsonParsingHelper.class.getSimpleName();

public static ArrayList<Category> getCities(String countryJson) throws JSONException {
ArrayList<Category> cities = new ArrayList<Category>();

JSONArray names = null;

// getting JSON string from asset
JSONObject json = new JSONObject(countryJson);

try {
// Getting Array of Contacts
names = json.getJSONArray("list");
// looping through All Contacts
for(int i = 0; i < names.length(); i++){
JSONObject c = names.getJSONObject(i);
// Storing each json item in variable
Category cat = new Category();
String name = c.getString("name");

cat.setName(name);

cities.add(cat);

}
} catch (JSONException e) {
e.printStackTrace();
}
return cities;
}
}

// pojo class
package com.network;

import android.os.Parcel;
import android.os.Parcelable;

public class Category implements Parcelable {
String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}

}

// Utils class
package com.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.content.res.AssetManager;

public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
    
public static String jsonToStringFromAssetFolder(String fileName,
Context context) {

String jsonString = null;

try {
AssetManager manager = context.getAssets();
InputStream file = manager.open(fileName);

byte[] data = new byte[file.available()];
file.read(data);
file.close();
jsonString = new String(data);
} catch (IOException ie) {

}
return jsonString;
}
}

// List activity
package com.android;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.network.Category;
import com.network.JsonParsingHelper;
import com.network.Utils;

public class ReadingDataFromAsset extends Activity {

TextView mCategory, mEmptyTextView;
ProgressBar mProgressBar;

ListView list;

String friendsJSON;

ArrayList<Category> arraylist;
JsonParsingHelper parser = new JsonParsingHelper();

public void onBackPressed() {
finish();
};

@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar

setContentView(R.layout.activity_friends_list);

list = (ListView) findViewById(android.R.id.list);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mEmptyTextView = (TextView) findViewById(R.id.empty);

mEmptyTextView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);

friendsJSON = Utils.jsonToStringFromAssetFolder("Friends.json",
getApplicationContext());

new getList().execute();

list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub

Toast.makeText(getApplicationContext(),
"selected " + arraylist.get(arg2).getName(), 3000)
.show();
}

});

list.setVerticalScrollBarEnabled(false);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setCacheColorHint(getResources().getColor(
R.color.listCacheColorHint));

list.setVerticalScrollBarEnabled(false);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setCacheColorHint(getResources().getColor(
R.color.listCacheColorHint));
}

class getList extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}

protected Void doInBackground(Void... unused) {

try {
arraylist = parser.getFriends(friendsJSON);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}

protected void onPostExecute(Void unused) {

if (arraylist != null && arraylist.size() - 1 != 0) {
list.setAdapter(new MyAdapter());
} else {
mEmptyTextView.setVisibility(View.VISIBLE);
mEmptyTextView.setText("No data found..!!");
}
mProgressBar.setVisibility(View.GONE);
}
}

public class MyAdapter extends BaseAdapter {

public int getCount() {
// TODO Auto-generated method stub
return arraylist.size() - 1;
}

public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}

public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

public View getView(final int position, View v1, ViewGroup arg2) {
// TODO Auto-generated method stub
View v = null;

LayoutInflater l = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v = l.inflate(R.layout.adapter_content, null);

// list-optimisation
View rowview = v;
if (rowview == null) {
LayoutInflater linf = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowview = linf.inflate(R.layout.adapter_content, null);
}

mCategory = (TextView) v.findViewById(R.id.category);

mCategory.setText(arraylist.get(position).getName());

return v;

}
}
}


// activity_friends_list layout

<?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="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" >

        <ListView
            android:id="@id/android:list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:drawSelectorOnTop="false"
            android:padding="10dp"
            android:divider="#000000"
            android:dividerHeight="1dp"
            />

        <TextView
            android:id="@+id/emptyText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="#000000"
            android:textStyle="bold" />

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true" />

        <TextView
            android:id="@+id/empty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/emptyText"
            android:layout_centerHorizontal="true"
            android:text="No results found"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:visibility="gone"/>

    </RelativeLayout>

</LinearLayout>

// row layout  - adapter_content
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <TextView
        android:id="@+id/category"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_toLeftOf="@+id/img"
        android:text="friend name"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000000"/>

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:background="@drawable/right_arrow" />

</RelativeLayout>

Friday, October 4, 2013

JSON parsing in Android using GSON

Add  GSON jar file to lib folder

// list activity

public class FriendsList extends Activity{

String mUrl;

TextView mCategory, mEmptyTextView;

ProgressBar mProgressBar;

ArrayList<NamesPojo> arraylist;
NamesJsonParsing parser = new NamesJsonParsing();

ListView list;

public void onBackPressed() {
finish();
};

@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar

setContentView(R.layout.activity_friends_list);

list = (ListView) findViewById(android.R.id.list);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mEmptyTextView = (TextView) findViewById(R.id.empty);

mEmptyTextView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);

mUrl = "url here";

new getList().execute();

list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub

Toast.makeText(getApplicationContext(), "selected "+arraylist.get(arg2).getName(), 3000).show();
}

});

list.setVerticalScrollBarEnabled(false);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setCacheColorHint(getResources().getColor(
R.color.listCacheColorHint));

list.setVerticalScrollBarEnabled(false);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setCacheColorHint(getResources().getColor(
R.color.listCacheColorHint));
}

class getList extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {

mProgressBar.setVisibility(View.VISIBLE);
}

protected Void doInBackground(Void... unused) {

mUrl.trim();

try{
arraylist = parser.getList(mUrl);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}

protected void onPostExecute(Void unused) {

if (arraylist != null && arraylist.size()-1 != 0) {
list.setAdapter(new MyAdapter());
} else {
mEmptyTextView.setVisibility(View.VISIBLE);
mEmptyTextView.setText("No users found..!!");
}

mProgressBar.setVisibility(View.GONE);

}
}


public class MyAdapter extends BaseAdapter {

public int getCount() {
// TODO Auto-generated method stub
return arraylist.size()-1;
}

public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}

public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

public View getView(final int position, View v1, ViewGroup arg2) {
// TODO Auto-generated method stub
View v = null;

LayoutInflater l = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v = l.inflate(R.layout.adapter_content, null);

// list-optimisation
View rowview = v;
if (rowview == null) {
LayoutInflater linf = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowview = linf.inflate(R.layout.adapter_content, null);
}

mCategory = (TextView) v.findViewById(R.id.category);

mCategory.setText(arraylist.get(position).getName());

return v;

}

}

}


// parsing & pojo classes

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.google.myjson.Gson;

public class NamesJsonParsing {

private static final String TAG = "NamesJsonParsing";
// ListPojo listPojoObject;
ArrayList<NamesPojo> list;
// protected ArrayList<Pojo> arrayListObject;
NamesListPojo listPojo;

// method to parse the given JSON object by taking the url of the JSON as
// argument
public ArrayList<NamesPojo> getList(String url) {
url=url.replace(" ", "%20");
HttpGet getRequest = new HttpGet(url);

try {
//Log.d(TAG, "url:"+url);
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d(TAG, "DefaultHttpClient");
HttpResponse getResponse = httpClient.execute(getRequest);

Log.d(TAG, "HttpResponse");

HttpEntity getResponseEntity = getResponse.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();

Reader inputStreamReader = new InputStreamReader(httpResponseStream);

// json cmpleted

Log.d(TAG, "Before fromJson method");

Gson gson = new Gson();
Log.d(TAG, gson.toString());
Log.d(TAG, "BEFORE JSON METHOD");
this.listPojo = gson.fromJson(inputStreamReader, NamesListPojo.class);

list = new ArrayList<NamesPojo>();

for (NamesPojo pojoObject : this.listPojo.list) {
list.add(pojoObject);

}

} catch (IOException e) {

}
return list;

}

}

// list pojo

import java.util.ArrayList;

import android.util.Log;

public class NamesListPojo {

private static final String TAG = "NamesListPojo";
public ArrayList<NamesPojo> list;

public ArrayList<NamesPojo> getPojoList() {   /*getter method*/
return list;
}

public NamesListPojo() {
Log.d(TAG, "construcor");
       
list = new ArrayList<NamesPojo>();
}

}

// pojo
package com.dialus;

import java.io.Serializable;

public class NamesPojo implements Serializable {

/**
*/
private static final long serialVersionUID = 1054589568733453137L;
String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public NamesPojo(String name) {
// TODO Auto-generated constructor stub
this.name = name;
}

}

SQLite example in Android

// activity

package com.example.testingproject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

String user,pass;
MyDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testing);
       
        db = new MyDatabase(MainActivity.this);
       
        Button addbtn = (Button)findViewById(R.id.button1);
       
        addbtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

EditText username = (EditText)findViewById(R.id.editText1);
EditText password = (EditText)findViewById(R.id.editText2);

user = username.getText().toString();
pass = password.getText().toString();

long xyz = db.insert(user, pass);

if (xyz == -1) {
Toast.makeText(getApplicationContext(), "Not Inserted ", Toast.LENGTH_SHORT).show();
} else {

Toast.makeText(getApplicationContext(), "Value Inserted ", Toast.LENGTH_SHORT).show();
}

}
});
       
       
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
   
}

// db class

package com.example.testingproject;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabase extends SQLiteOpenHelper {


public static final String TABLE_NAME = "login";
 public static final String COLUMN_ID = "_id";
 public static final String COLUMN_USERNAME = "username";
 public static final String COLUMN_PASSWORD = "password";

 private static final String DATABASE_NAME = "login.db";
 private static final int DATABASE_VERSION = 1;
 SQLiteDatabase sd;


 public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String DATABASE_CREATE = "create table "
     + TABLE_NAME + "(" + COLUMN_ID
     + " integer primary key autoincrement, " + COLUMN_USERNAME + " text not null," + COLUMN_PASSWORD + " text not null);";
db.execSQL(DATABASE_CREATE);
}

public void open() throws SQLException

{
SQLiteDatabase sd = this.getWritableDatabase();

//Here database is open for read and write operation
}
public void close()

{
if (sd != null)

{
sd.close();
}
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public long insert(String user,String pass)
{
long abc = 0;
open();
SQLiteDatabase sd = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, user);
values.put(COLUMN_PASSWORD, pass);
 
abc = sd.insert(TABLE_NAME, null, values);
close();
return abc;
}


}


// activity 
<?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" >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10" >

            <requestFocus />
        </EditText>

    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPassword" />

    </TableRow>

    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:layout_marginTop="30dp"
            android:text="Button" />

    </TableRow>

</LinearLayout>

// manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testingproject"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testingproject.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>
        <activity 
            android:name=".MyDatabase"></activity>
    </application>

</manifest>