Monday 28 December 2015

StringBuilder

StringBuilder

  • StringBuilder class is used to create mutable(modifiable) string.
  • The java Stringbuilder calss is same as Stringbuffer.
  • StringBuilder is a non-synchronized.
  • Its is available since JDK 1.5.

Important constructors of StringBuilder Class:

  1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
  2. StringBuilder(String str): creates a string Builder with the specified string.
   3.StringBuilder(int length): creates an empty string Builder with the     specified capacity as length.

Important methods of StringBuilder class:

Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this string.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello ");  
  4. sb.append("Java");//now original string is changed  
  5. System.out.println(sb);//prints Hello Java  
  6. }  
  7. }  

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the given position.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello ");  
  4. sb.insert(1,"Java");//now original string is changed  
  5. System.out.println(sb);//prints HJavaello  
  6. }  
  7. }  

3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.replace(1,3,"Java");  
  5. System.out.println(sb);//prints HJavalo  
  6. }  
  7. }  

4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.delete(1,3);  
  5. System.out.println(sb);//prints Hlo  
  6. }  
  7. }  

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.reverse();  
  5. System.out.println(sb);//prints olleH  
  6. }  
  7. }  

6) StringBuilder capacity() method

The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. }  
  10. }  

7) StringBuilder ensureCapacity() method

The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. sb.ensureCapacity(10);//now no change  
  10. System.out.println(sb.capacity());//now 34  
  11. sb.ensureCapacity(50);//now (34*2)+2  
  12. System.out.println(sb.capacity());//now 70  
  13. }  

 

Monday 21 December 2015

StringBuffer

Java StringBuffer class

 

 Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.

Important methods of StringBuffer class:

  • public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.

  •  public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.

  • public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.

  • public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex.

  • public synchronized StringBuffer reverse(): is used to reverse the string.
    public int capacity(): is used to return the current capacity.

  • public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.

  • public char charAt(int index): is used to return the character at the specified position.

  • public int length(): is used to return the length of the string i.e. total number of characters.

  • public String substring(int beginIndex): is used to return the substring from the specified beginIndex.

  • public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.

What is mutable string:

A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.


next we see about StringBuilder

 


 

 

 

 

Thursday 17 December 2015

Android - JSON Parser

JSON Parser


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 the JSON given below. 


For example: 

http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php


{"Users":
[
{"firstname":"Mike","lastname":"Dalisay","username":"mike143"},

{"firstname":"Jemski","lastname":"Panlilios","username":"jemboy09"},

{"firstname":"Darwin","lastname":"Dalisay","username":"dada08"},

{"firstname":"Jaylord","lastname":"Bitamug","username":"jayjay"},

{"firstname":"Justine","lastname":"Bongola","username":"jaja"},

{"firstname":"Jun","lastname":"Sabayton","username":"jun"},

{"firstname":"Lourd","lastname":"De Veyra","username":"lourd"},

{"firstname":"Asi","lastname":"Taulava","username":"asi"},

{"firstname":"James","lastname":"Yap","username":"james"},

{"firstname":"Chris","lastname":"Tiu","username":"chris"},

{"firstname":"xxxrrr","lastname":"xxxrrr","username":"xxrrr"}
]}


JSON - Elements:

An JSON file consist of many components. Here is the table defining the components of an JSON file and their description −

 


Component & description

Array([) In a JSON file , square bracket ([) represents a JSON array

Objects({) In a JSON file, curly bracket ({) represents a JSON object

Key A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object

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 s;
JSONObject jsonObject=new JSONObject(s);
JSONArray jsonArray=jsonObject.getJSONArray("Users"); 
 
 
 
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:

jsonArray.getJSONObject().getString("firstname");
jsonArray.getJSONObject().getString("username");
jsonArray.getJSONObject().getString("lastname") 
 


 
The method getJSONObject returns the JSON object. The method getString 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 −
 
 
Method & description:
 



get(String name) This method just Returns the value but in the form of Object type

getBoolean(String name) This method returns the boolean value specified by the key

getDouble(String name) This method returns the double value specified by the key


getInt(String name) This method returns the integer value specified by the key

getLong(String name) This method returns the long value specified by the key

length() This method returns the number of name/value mappings in this object..

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.


Here, I have Student details json and i download all student details using Asynctask for that i create pojo class and i put in to the listview for that i create Adapter class.In manifest need INTERNET Permission.



MainActivity:

package com.example.root.studentjson;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;


public class MainActivity extends ActionBarActivity {
    Button getlist_bt;
    ListView list;
    MyAsync async;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getlist_bt=(Button)findViewById(R.id.button);
        list=(ListView)findViewById(R.id.listView);
        getlist_bt.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                async= new MyAsync(MainActivity.this,list);
                async.execute("http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php");

            }
        });
    }

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

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

MyAdapter:

package com.example.root.studentjson;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/** * Created by root on 9/12/15. */public class MyAdapter extends BaseAdapter {
    Context c;
    ArrayList<Users> al;
    LayoutInflater layoutInflater;

    public MyAdapter(Context c, ArrayList<Users> al) {
        this.c = c;
        this.al = al;
        layoutInflater=LayoutInflater.from(c);
    }

    @Override    public int getCount() {

        return al.size();
    }

    @Override    public Object getItem(int position) {
        return null;
    }

    @Override    public long getItemId(int position) {
        return 0;
    }

    @Override    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView==null)
        {
            convertView=layoutInflater.inflate(R.layout.item_list,parent,false);
        }
        TextView firstname_tv=(TextView)convertView.findViewById(R.id.firstname);
        TextView username_tv=(TextView)convertView.findViewById(R.id.username);
        TextView lastname_tv=(TextView)convertView.findViewById(R.id.lastname);
        firstname_tv.setText(al.get(position).getFirstname());
        username_tv.setText(al.get(position).getUsername());
        lastname_tv.setText(al.get(position).getLastname());

        return convertView;
    }
}

MyAsync:
 
package com.example.root.studentjson;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

/** * Created by root on 9/12/15. */public class MyAsync extends AsyncTask<String,String ,String > {
    Context c;
    ListView list;
    MyAdapter adapter;
    ProgressDialog pd;

    public MyAsync(Context c, ListView list) {
        this.c = c;
        this.list = list;
    }

    @Override    protected String doInBackground(String... params) {
        try {
            URL url=new URL(params[0]);
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            httpURLConnection.connect();
            InputStream inputStream=httpURLConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line+"\n");
            }
            br.close();
            return sb.toString();


        }catch (Exception e){

        }
        return null;
    }

    @Override    protected void onPostExecute(String s) {

        super.onPostExecute(s);
        try {
            ArrayList<Users> arrayList=new ArrayList<>();
            JSONObject jsonObject=new JSONObject(s);
            JSONArray jsonArray=jsonObject.getJSONArray("Users");
            for (int i=0;i<jsonArray.length();i++){


                Users users=new Users(jsonArray.getJSONObject(i).getString("firstname"),jsonArray.getJSONObject(i).getString("username"),jsonArray.getJSONObject(i).getString("lastname"));
                arrayList.add(users);
            }
            adapter=new MyAdapter(c,arrayList);
            list.setAdapter(adapter);
            pd.dismiss();

        }catch (Exception e){

        }
    }

    @Override    protected void onPreExecute() {
        pd=new ProgressDialog(c);
        pd.setMessage("downloading json");
        pd.show();
        super.onPreExecute();
    }

    @Override    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }
}
 
Users:
 
package com.example.root.studentjson;

/** * Created by root on 9/12/15. */public class Users {
    String firstname,username,lastname;

    public Users(String firstname, String username, String lastname) {
        this.firstname = firstname;
        this.username = username;
        this.lastname = lastname;
    }

    public String getFirstname() {

        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}
Manifest:

 
 
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.root.studentjson" >
    <uses-permission android:name="android.permission.INTERNET">

    </uses-permission>

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

</manifest>

Can you run this code, you will get student details list show in listview.