Friday 29 July 2016

Android Toolbar Example.
Toolbar is a complete replacement to Android ActionBar.ToolBar works well with apps targeted to API 21 and above and it is introduced after lollipop release.

Toolbar may contain a combination of the following optional elements:
  • Using the Navigation button.
  • Using the logo Image.
  • Using the title and subtitle.
Implementing the Navigation button and icon on Toolbar.

Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create Xml file in project.    
Open => app => res => layout - activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<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="laptop.example.com.toolbaricon.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="58dp"
        android:background="@color/colorPrimary"
        android:minHeight="?attr/actionBarSize"></android.support.v7.widget.Toolbar>
</RelativeLayout>

Create Xml file in project.
Open => app => res => menu => main.xml.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/search"
        android:title="Search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />
    <item
        android:id="@+id/action_setting"
        android:icon="@drawable/setting"
        android:orderInCategory="300"
        android:title="Setting"
        app:showAsAction="ifRoom"></item>
</menu>


Create the Java file in project.
Open app => main => src = MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ToolBar();

    }

    private void ToolBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.drawable.hamburger);
        toolbar.setNavigationOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "Click App Logo", 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;
    }

    @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.

        switch (item.getItemId()) {
            case R.id.action_search:
                Toast.makeText(MainActivity.this, "I am Search", Toast.LENGTH_LONG).show();
                break;
            case R.id.action_setting:
                Toast.makeText(MainActivity.this, "I am Setting", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}



Output:-

 


May this code help you. Thanks!!!!!!
 

Thursday 28 July 2016

How to debug an Android app without using USB in android studio.

Open the terminal(android studio) or cmd.
  • First time  need data cable
  • Go to ADB location inside platform tools.
  • Attach data cable .
  • cmd>  adb devices(press enter)
  • adb tcpip 5555 +enter.
  • Remove cable.
  • Go to phone settings => About Phone => Status => Check IP Address.
  • adb connect IP address:5555

Example: 
  • C:\Users\Laptop>d:
  • D:\>cd AnddroidStudio\platform-tools
  • D:\AnddroidStudio\platform-tools>adb devices
  • List of devices attached
  • 0123456789ABCDEF        device
  • D:\AnddroidStudio\platform-tools>adb tcpip 5555
  • restarting in TCP mode port: 5555
  • D:\AnddroidStudio\platform-tools>adb connect 192.168.1.8:5555

After that connectivity is done(Android phone and Android studio).


May this lines help you. Thanks!!!!!!

Wednesday 27 July 2016

Spinner Example to Load JSON using Volley in android studio

File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.


First we need to add Volley Library to our project.
 compile 'com.android.support:design:22.2.0'
 compile 'com.mcxiaoke.volley:library-aar:1.0.0'


Create Xml file in project.  
Open => app => res => layout - activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical"
        android:paddingLeft="24dp"
        android:paddingRight="24dp"
        android:paddingTop="56dp">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>



Create the Config.java file in project.


package laptop.example.com.testdemo;

/**
 * Created by Laptop on 27-07-2016.
 */
public class Config {
    public static String URL = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";

    public static final String TAG_RANK = "rank";
    public static final String TAG_COUNTRY = "country";
    public static final String TAG_POPULATION = "population";
    //JSON array name
    public static final String JSON_ARRAY = "worldpopulation";
}



Create the Java file in project.
Open app => main => src = MainActivity.java



package laptop.example.com.testdemo;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    Spinner spinner;
    ProgressDialog dialog;
    //ArrayList for Spinner Items
    private ArrayList<String> country;
    //JSON Array
    private JSONArray worldpopulation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init();
        Login();
        Listener();

        //Initializing the ArrayList
        country = new ArrayList<String>();
    }

    private void Listener() {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void Login() {

        showDialog(true);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        showDialog(false);
                        JSONObject json = null;
                        try {
                            //Parsing the fetched Json String to JSON Object
                            json = new JSONObject(response);

                            //Storing the Array of JSON String to our JSON Array
                            worldpopulation = json.getJSONArray(Config.JSON_ARRAY);

                            //Calling method getStudents to get the students from the JSON Array
                            getRank(worldpopulation);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        showDialog(false);
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                // map.put(KEY_EMAIl,email);

                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void getRank(JSONArray worldpopulation) {
        for (int i = 0; i < worldpopulation.length(); i++) {
            try {
                JSONObject jsonObject = worldpopulation.getJSONObject(i);
                //Adding the name of the Rank to array list
                country.add(jsonObject.getString(Config.TAG_COUNTRY));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //Setting adapter to show the items in the spinner
        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, country));
    }

    private void showDialog(boolean check) {
        if (check) {
            dialog = ProgressDialog.show(MainActivity.this, "", "Loading....");
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

    private void Init() {
        spinner = (Spinner) findViewById(R.id.spinner);
    }

}


Add Internet permission in your manifest
<uses-permission android:name="android.permission.INTERNET"/>

May this code help you. Thanks!!!!!!

Monday 25 July 2016

How to get the data through Parsing with SQLite in android studio.

File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Volley Library to our project.
    compile 'com.android.support:design:23.1.1'
    compile 'com.google.code.gson:gson:2.2.3'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile files('libs/picasso-2.5.0.jar')  


Create Xml file in project.   

Open => app => res => layout - activity_main.xml.

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>


Open => app => res => layout - row_item.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:background="#307fc1"
    android:orientation="vertical"
    android:padding="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/txtname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Kamal Sharma"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#ffffff" />

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginLeft="42dp"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

    <TextView
        android:id="@+id/txtdes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="William Bradley 'Brad'"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/txtdob"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="14-09-1989"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/txtcountry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="United States"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/txtheight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="1.80m"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/txtchildren"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="ABC,XYZ"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />
  
</LinearLayout>


Create the Java file in project.

Open app => main => src = MainActivity.java

package com.appified.jsonparsingexample;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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 java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity{
    ListView listView;
    CustomAdapter adapter;
    ArrayList<CustomItem> arrayList;
    DBHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listview);
        handler = new DBHandler(this);
        NetworkUtils utils = new NetworkUtils(MainActivity.this);
        if(handler.getItemCount() == 0 && utils.isConnectingToInternet())
        {
            new DataFetcherTask().execute();
        }
        else
        {
             ArrayList<CustomItem> cityList = handler.getAllItem();
            adapter = new CustomAdapter(MainActivity.this,cityList);
            listView.setAdapter(adapter);
        }
        }
    @SuppressLint("NewApi") class DataFetcherTask extends AsyncTask<Void,Void,Void> {

        @SuppressLint("NewApi") @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @SuppressWarnings("deprecation")
        @Override
        protected Void doInBackground(Void... params) {
            String serverData = null;// String object to store fetched data from server
            // HTTP Request Code start
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                serverData = EntityUtils.toString(httpEntity);
                Log.d("response", serverData);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
             // HTTP Request Code end
            // JSON Parsing Code Start
            try {
                arrayList = new ArrayList<CustomItem>();
                JSONObject jsonObject = new JSONObject(serverData);
                JSONArray jsonArray = jsonObject.getJSONArray("actors");
                for(int i=0;i<jsonArray.length();i++)
                {
                    JSONObject jsonObjectItem = jsonArray.getJSONObject(i);
                    String Name = jsonObjectItem.getString("name");
                    String Desc = jsonObjectItem.getString("description");
                    String DOB = jsonObjectItem.getString("dob");
                    String Country= jsonObjectItem.getString("country");
                    String Height = jsonObjectItem.getString("height");
                    String children=jsonObjectItem.getString("children");
                    CustomItem value = new CustomItem();
                    value.setName(Name);
                    value.setDesc(Desc);
                    value.setDob(DOB);
                    value.setCountry(Country);
                    value.setHeight(Height);
                    value.setchildren(children);
                    handler.addItem(value);  // Inserting into DB
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Json Parsing code end
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ArrayList<CustomItem> itemList = handler.getAllItem();
            adapter = new CustomAdapter(MainActivity.this,itemList);
            listView.setAdapter(adapter);
        }
    }
}

 Create the CustomListener class in project

package com.appified.jsonparsingexample;

import java.util.ArrayList;

public interface CustomListener {

    public void addItem(CustomItem city);
    public ArrayList<CustomItem> getAllItem();
    public int getItemCount();
}


 Create the CustomItem class in project

package com.appified.jsonparsingexample;


public class CustomItem {

    private int id;
    private String name;
    private String Desc;
    private String DOB;
    private String Country;
    private String height;
    private String children;
    private String Image;

    public CustomItem() {
    }

    public CustomItem(String name, String Desc, String DOB, String Country, String height, String children, String Image) {
        this.name = name;
        this.Desc = Desc;
        this.DOB = DOB;
        this.Country = Country;
        this.height = height;
        this.children = children;
        this.Image = Image;
    }

    public CustomItem(int id, String name, String Desc, String DOB, String Country, String height, String children, String Image) {
        this.id = id;
        this.name = name;
        this.Desc = Desc;
        this.DOB = DOB;
        this.Country = Country;
        this.height = height;
        this.children = children;
        this.Image = Image;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getDesc() {
        return Desc;
    }

    public void setDesc(String Desc) {
        this.Desc = Desc;
    }

    public String getDob() {
        return DOB;
    }

    public void setDob(String DOB) {
        this.DOB = DOB;
    }

    public String getCountry() {
        return Country;
    }

    public void setCountry(String Country) {
        this.Country = Country;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getChildren() {
        return children;
    }

    public void setchildren(String children) {
        this.children = children;
    }

    public String getImage() {
        return children;
    }

    public void setImage(String Image) {
        this.Image = Image;
    }
}


Create the CustomAdapter class in project

package com.appified.jsonparsingexample;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class CustomAdapter extends BaseAdapter {

    Context context;
    ArrayList<CustomItem> listData;


    public CustomAdapter(Context context, ArrayList<CustomItem> listData) {
        this.context = context;
        this.listData = listData;
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

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

    class ViewHolder {
        private TextView textViewCityName, txtDesc, txtDob, txtcountry, txtheight, txtchildren;
        ImageView image;

    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.row_item, null);
            viewHolder = new ViewHolder();
            viewHolder.textViewCityName = (TextView) view.findViewById(R.id.txtname);
            viewHolder.txtDesc = (TextView) view.findViewById(R.id.txtdes);
            viewHolder.txtDob = (TextView) view.findViewById(R.id.txtdob);
            viewHolder.txtcountry = (TextView) view.findViewById(R.id.txtcountry);
            viewHolder.txtheight = (TextView) view.findViewById(R.id.txtheight);
            viewHolder.image = (ImageView) view.findViewById(R.id.image);
            viewHolder.txtchildren = (TextView) view.findViewById(R.id.txtchildren);

            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.textViewCityName.setText(listData.get(position).getName());
        viewHolder.txtDesc.setText(listData.get(position).getDesc());
        viewHolder.txtDob.setText(listData.get(position).getDob());
        viewHolder.txtcountry.setText(listData.get(position).getCountry());
        viewHolder.txtheight.setText(listData.get(position).getHeight());
        viewHolder.txtchildren.setText(listData.get(position).getChildren());
        // Picasso.with(context).load(listData.get(position).getImage()).resize(150, 150).into(viewHolder.image);
      
     /*   viewHolder.image.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
          
              
            }
        });*/

        return view;
    }
}


Create the NetworkUtils class in project

package com.appified.jsonparsingexample;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class NetworkUtils {

    private Context context;

    public NetworkUtils(Context context) {
        this.context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }
}


Create the DBHandler class in project


package com.appified.jsonparsingexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;

public class DBHandler extends SQLiteOpenHelper implements CustomListener {
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "Database.db";
    private static final String TABLE_NAME = "item_table";
    private static final String KEY_ID = "_id";
    private static final String KEY_NAME = "_name";
    private static final String KEY_DESC = "_state";
    private static final String KEY_DOB = "_description";
    private static final String KEY_COUNTRY = "_country";
    private static final String KEY_HEIGHT = "_height";
    private static final String KEY_CHILDREN = "_children";

    String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_NAME+" TEXT,"+KEY_DESC+" TEXT,"+KEY_DOB+" TEXT,"+KEY_COUNTRY+" TEXT,"+KEY_HEIGHT+" TEXT,"+KEY_CHILDREN+" TEXT)";
    String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;

    public DBHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_TABLE);
        onCreate(db);
    }

    @Override
    public void addItem(CustomItem item) {
        SQLiteDatabase db = this.getWritableDatabase();
        try{
            ContentValues values = new ContentValues();
            values.put(KEY_NAME, item.getName());
            values.put(KEY_DESC, item.getDesc());
            values.put(KEY_DOB,item.getDob());
            values.put(KEY_COUNTRY, item.getCountry());
            values.put(KEY_HEIGHT, item.getHeight());
            values.put(KEY_CHILDREN, item.getChildren());
            db.insert(TABLE_NAME, null, values);
            db.close();
        }catch (Exception e){
            Log.e("problem",e+"");
        }
    }

    @Override
    public ArrayList<CustomItem> getAllItem() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<CustomItem> itemList = null;
        try{
            itemList = new ArrayList<CustomItem>();
            String QUERY = "SELECT * FROM "+TABLE_NAME;
            Cursor cursor = db.rawQuery(QUERY, null);
            if(!cursor.isLast())
            {
                while (cursor.moveToNext())
                {
                    CustomItem item = new CustomItem();
                    item.setId(cursor.getInt(0));
                    item.setName(cursor.getString(1));
                    item.setDesc(cursor.getString(2));
                    item.setDob(cursor.getString(3));
                    item.setCountry(cursor.getString(4));
                    item.setHeight(cursor.getString(5));
                    item.setchildren(cursor.getString(6));
                    itemList.add(item);
                }
            }
            db.close();
        }catch (Exception e){
            Log.e("error",e+"");
        }
        return itemList;
    }

    @Override
    public int getItemCount() {
        int num = 0;
        SQLiteDatabase db = this.getReadableDatabase();
        try{
            String QUERY = "SELECT * FROM "+TABLE_NAME;
            Cursor cursor = db.rawQuery(QUERY, null);
            num = cursor.getCount();
            db.close();
            return num;
        }catch (Exception e){
            Log.e("error",e+"");
        }
        return 0;
    }
}


Add Internet permission in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>


May this code help you. Thanks!!!!!!

Thursday 21 July 2016

How to Get Key Hashes for Android App Facebook Integration.
Create MainActivity class in project.


import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "laptop.example.com.haskkeygenerate",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash::::", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
    }
}



OutPut:-
 





Monday 4 July 2016

Android FragmentManager and FragmentTransaction.

FragmentManager and FragmentTransaction example in which we will replace Fragment with another Fragment using Button OnClickListener.o achieve it, first we get the instance of FragmentTransaction using FragmentManager, then call replace method which will accept view container id and new fragment instance.

Create the activity.xml in project.
<?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="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/linear" />

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#371931"
        android:orientation="horizontal"
        android:padding="12dp">

        <LinearLayout
            android:id="@+id/newsLinear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:onClick="ID"
            android:orientation="vertical">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/news" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="NEWS"
                android:textColor="#ffffff"
                android:textSize="12dp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/bookLinear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:onClick="ID"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imageView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/book" />


            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="BOOKING"
                android:textColor="#ffffff"
                android:textSize="12dp" />
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


Create fragment_new.xml file in project.  

<?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:background="#33cc88"
    android:orientation="vertical">
</LinearLayout>


Create fragment_book.xml file in project.
 
<?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:background="#ffffff"
    android:orientation="vertical">
</LinearLayout>



Create MainActivity class in project.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import refresh.swipe.com.designdemo.fragment.FragmentBook;
import refresh.swipe.com.designdemo.fragment.FragmentNews;

/**
 * Created by Laptop on 04-07-2016.
 */
public class MainActivity extends AppCompatActivity {
    FragmentManager fragmentManager;
    LinearLayout newLinearLayout,bookLinearLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_pro);
        Init();
        Listener();
    }

    private void Listener() {
        fragmentManager = getSupportFragmentManager();
        newLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentNews fragmentNews = new FragmentNews();
                InflateFragment(fragmentNews);
            }
        });
        bookLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentBook fragmentBook = new FragmentBook();
                InflateFragment(fragmentBook);
            }
        });

    }
    /*********************************
     * inflate fragments
     *****************************/
    public void InflateFragment(Fragment frg) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container, frg);
        //fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
    private void Init() {
        newLinearLayout=(LinearLayout)findViewById(R.id.newsLinear);
        bookLinearLayout=(LinearLayout)findViewById(R.id.bookLinear);
    }
}

Create FragmantNews class in project.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import refresh.swipe.com.designdemo.R;

/**
 * Created by Laptop on 04-07-2016.
 */
public class FragmentNews extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, viewGroup, false);
        return view;
    }
}

Create FragmantBook class in project.


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import refresh.swipe.com.designdemo.R;

/**
 * Created by Laptop on 04-07-2016.
 */
public class FragmentBook extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book, viewGroup, false);
        return view;
    }
}




May this code help you. Thanks!!!!!!