Friday 5 July 2019

Develop a Multiple Horizontal Scroll with Vertical Scroll Within Single Screen Like Google Play Store

Hi guys after long time I comeback with a new post I hope it will be helpful for beginners and experienced android developers. Generally Android Developers got app requirement to develop multiple horizontal scroll view in single screen with vertical scroll like Google Play Store. Now a days it becomes trend to develop video streaming songs and movies apps like Netflix so, it's become popular view now. Now i'm going to explain how to develop view like Google Play Store. Also I will share the complete code in this app. In this blog I created a local JSON file in assets folder which stores all data in JSON formate latter which I parse in file MainActivity.java so, that developer no need worry to how to display parsed data through network call. If you want to display data from string array in string.xml then there is a blog (Create a Vertical Scroll and Horizontal Scroll App like Google Play Store) is already exist. I also follow this blog to create this blog. First create an android project in android studio. After create project add two dependencies of RecyclerView and CardView in build.gradle file which will be implemented later in the project.
build.gradle

compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
After adding dependencies never forgot to sync your project to avoid error. After that create two folder for model and adapter class within package. Create two model class in model folder SectionDataModel.java and SingleItemModel and generate Getter and Setter method.

SingleItemModel.java


package com.kit.googleplaystoresample.model;

import java.io.Serializable;

public class SingleItemModel implements Serializable {
    public String getSubcategory_id() {
        return subcategory_id;
    }

    public void setSubcategory_id(String subcategory_id) {
        this.subcategory_id = subcategory_id;
    }

    public String getSubcategory_name() {
        return subcategory_name;
    }

    public void setSubcategory_name(String subcategory_name) {
        this.subcategory_name = subcategory_name;
    }

    public SingleItemModel(String subcategory_id, String subcategory_name) {
        this.subcategory_id = subcategory_id;
        this.subcategory_name = subcategory_name;
    }

    private String subcategory_id, subcategory_name;

    public SingleItemModel() {

    }


}

SectionDataModel.java


package com.kit.googleplaystoresample.model;

import java.io.Serializable;
import java.util.ArrayList;

public class SectionDataModel implements Serializable {
    private String headerTitle;
    private ArrayList allItemInSection;

    public SectionDataModel() {
    }

    public SectionDataModel(String headerTitle, ArrayList allItemInSection) {
        this.headerTitle = headerTitle;
        this.allItemInSection = allItemInSection;
    }

    public String getHeaderTitle() {
        return headerTitle;
    }

    public void setHeaderTitle(String headerTitle) {
        this.headerTitle = headerTitle;
    }

    public ArrayList getAllItemInSection() {
        return allItemInSection;
    }

    public void setAllItemInSection(ArrayList allItemInSection) {
        this.allItemInSection = allItemInSection;
    }
}

After that create two adapter RecyclerViewDataAdapter.java and SectionListDataAdapter.java in adapter folder.

RecyclerViewDataAdapter.java


package com.kit.googleplaystoresample.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.github.rubensousa.gravitysnaphelper.GravitySnapHelper;
import com.kit.googleplaystoresample.MoreItemActivity;
import com.kit.googleplaystoresample.R;
import com.kit.googleplaystoresample.model.SectionDataModel;

import java.io.Serializable;
import java.util.ArrayList;

public class RecyclerViewDataAdapter extends RecyclerView.Adapter{

    private ArrayList dataList;
    private Context mContext;
    private RecyclerView.RecycledViewPool recycledViewPool;
    private SnapHelper snapHelper;

    public RecyclerViewDataAdapter(ArrayList dataList, Context mContext) {
        this.dataList = dataList;
        this.mContext = mContext;
        recycledViewPool = new RecyclerView.RecycledViewPool();
    }

    @Override
    public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, null);
        ItemRowHolder rowHolder = new ItemRowHolder(v);
        snapHelper = new GravitySnapHelper(Gravity.START);
        return rowHolder;
    }

    @Override
    public void onBindViewHolder(ItemRowHolder holder, final int position) {
        final String sectionName = dataList.get(position).getHeaderTitle();
     final    ArrayList singleSectionItems = dataList.get(position).getAllItemInSection();
        holder.itemTitle.setText(sectionName);
        SectionListDataAdapter adapter = new SectionListDataAdapter(singleSectionItems, mContext);
        holder.recyclerView.setHasFixedSize(true);
        holder.recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        holder.recyclerView.setAdapter(adapter);
        holder.recyclerView.setRecycledViewPool(recycledViewPool);
        snapHelper.attachToRecyclerView(holder.recyclerView);
        holder.btnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Bundle args = new Bundle();
                args.putSerializable("ARRAYLIST",(Serializable)singleSectionItems);

                Intent intent=new Intent(mContext, MoreItemActivity.class);
                intent.putExtra("sectionname",sectionName);
                intent.putExtra("BUNDLE",args);
               mContext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return (null != dataList ? dataList.size() : 0);
    }

    public class ItemRowHolder extends RecyclerView.ViewHolder {
        protected TextView itemTitle;
        protected RecyclerView recyclerView;
        protected Button btnMore;

        public ItemRowHolder(View itemView) {
            super(itemView);
            this.itemTitle = itemView.findViewById(R.id.itemTitle);
            this.recyclerView = itemView.findViewById(R.id.recycler_view_list);
            this.btnMore = itemView.findViewById(R.id.btnMore);
        }
    }
}

SectionListDataAdapter.java

package com.kit.googleplaystoresample.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kit.googleplaystoresample.R;
import com.kit.googleplaystoresample.model.SingleItemModel;

import java.util.ArrayList;

public class SectionListDataAdapter extends RecyclerView.Adapter{

    private ArrayList itemModels;
    private Context mContext;

    public SectionListDataAdapter(ArrayList itemModels, Context mContext) {
        this.itemModels = itemModels;
        this.mContext = mContext;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_single_card, null);
        SingleItemRowHolder singleItemRowHolder = new SingleItemRowHolder(v);
        return singleItemRowHolder;
    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int position) {
        SingleItemModel itemModel = itemModels.get(position);
        holder.tvTitle.setText(itemModel.getSubcategory_name());
    }

    @Override
    public int getItemCount() {
        return (null != itemModels ? itemModels.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;
        protected ImageView itemImage;

        public SingleItemRowHolder(View itemView) {
            super(itemView);
            this.tvTitle = itemView.findViewById(R.id.tvTitle);
            this.itemImage = itemView.findViewById(R.id.itemImage);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(view.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}


SectionMoreListDataAdapter.java


package com.kit.googleplaystoresample.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kit.googleplaystoresample.R;
import com.kit.googleplaystoresample.model.SingleItemModel;

import java.util.ArrayList;

public class SectionMoreListDataAdapter extends RecyclerView.Adapter{

    private ArrayList itemModels;
    private Context mContext;

    public SectionMoreListDataAdapter(ArrayList itemModels, Context mContext) {
        this.itemModels = itemModels;
        this.mContext = mContext;
    }

    @Override
    public SectionMoreListDataAdapter.SingleItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.more_list_data, null);
        SectionMoreListDataAdapter.SingleItemRowHolder singleItemRowHolder = new SectionMoreListDataAdapter.SingleItemRowHolder(v);
        return singleItemRowHolder;
    }

    @Override
    public void onBindViewHolder(SectionMoreListDataAdapter.SingleItemRowHolder holder, int position) {
        SingleItemModel itemModel = itemModels.get(position);
        holder.tvTitle.setText(itemModel.getSubcategory_name());
    }

    @Override
    public int getItemCount() {
        return (null != itemModels ? itemModels.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;
        protected ImageView itemImage;

        public SingleItemRowHolder(View itemView) {
            super(itemView);
            this.tvTitle = itemView.findViewById(R.id.tvTitle);
            this.itemImage = itemView.findViewById(R.id.itemImage);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(view.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}


MainActivity.java


package com.kit.googleplaystoresample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.kit.googleplaystoresample.adapter.RecyclerViewDataAdapter;
import com.kit.googleplaystoresample.model.SectionDataModel;
import com.kit.googleplaystoresample.model.SingleItemModel;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private ArrayList allSampleData;

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

        allSampleData = new ArrayList<>();

        getJsonData();

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerViewDataAdapter adapter = new RecyclerViewDataAdapter(allSampleData, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }


    private void getJsonData() {


        try {
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray m_jArry = obj.getJSONArray("category_list");
            ArrayList> formList = new ArrayList>();
            HashMap m_li;

            for (int i = 0; i < m_jArry.length(); i++) {
                JSONObject jo_inside = m_jArry.getJSONObject(i);

                String category_name = jo_inside.getString("category_name");
                JSONArray subcat_jArry = jo_inside.getJSONArray("subcategory");
                SectionDataModel dm = new SectionDataModel();
                dm.setHeaderTitle(category_name);


                ArrayList singleItemModels = new ArrayList<>();
                for (int j = 0; j 

MoreItemActivity.java


package com.kit.googleplaystoresample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;


import com.kit.googleplaystoresample.adapter.SectionMoreListDataAdapter;
import com.kit.googleplaystoresample.model.SingleItemModel;

import java.util.ArrayList;

public class MoreItemActivity extends AppCompatActivity {

    RecyclerView recycler_view_morelist;
    String itemname;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more_item);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        recycler_view_morelist=(RecyclerView)findViewById(R.id.recycler_view_morelist);

        Intent intent=getIntent();
        itemname=intent.getExtras().getString("sectionname");
        Bundle args = intent.getBundleExtra("BUNDLE");
        ArrayList singleSectionItems = (ArrayList) args.getSerializable("ARRAYLIST");
        setTitle(itemname);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
        recycler_view_morelist.setLayoutManager(mLayoutManager);
        SectionMoreListDataAdapter adapter = new SectionMoreListDataAdapter(singleSectionItems, this);
        recycler_view_morelist.setHasFixedSize(true);
        recycler_view_morelist.setAdapter(adapter);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // todo: goto back activity from here
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}


activity_main.xml


    


list_item.xml


    

        

            

            

        

    


list_single_item.xml


    

        

        

    


activity_more_item.xml


    

more_list_data.xml

    

    

        

        

    
    



Sunday 14 June 2015

JSON Parsing Using Fragment with Implementation of AsyncTask ViewHolder and ListView

Toady i am posting a blog about json parsing using fragment and AsyncTask which display data using ViewHolder in Listview. I have googled more and more such type of article  but not get any one so, i decide to post it.
Below is the complete code of this article.

JSONParsingFragment.java


package com.rakesht.androidpracticeappdemo;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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 android.app.ProgressDialog;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class JSONParsingFragment extends Fragment{
ListView lv;
ArrayList<Actors> actorsList;

ActorAdapter adapter;



Thursday 11 December 2014

Complete JSON parsing in Android Application for Beginners


JSONHandler.java

package com.rakesht.json;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

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

import android.util.Log;

/**
 * Adds the ability to JSON Lib (in Android) to parse JSON data into Bean Class. It
 * is based on Android's (org.json.*)
 *
 * @author
 *
 */
public class JSONHandler {

    String TAG = "My App";
   

Database CRUD Operation in Android Application Development

SQliteDataBaseActivity.java

package com.rakesh.tiwari.sqlitedatabase;

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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SQliteDataBaseActivity extends Activity {
    Contact contact;
    ListView listView;

    ArrayList<HashMap<String, String>> contactList;
    AyArrayAdapter ayArrayAdapter;

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

        contactList = new ArrayList<HashMap<String, String>>();

        final Button btnInsert = (Button) findViewById(R.id.btn_insert);
        final Button btnSelect = (Button) findViewById(R.id.btn_select);
        final Button btnSelectall = (Button) findViewById(R.id.btn_selectall);
        final Button btnUpdate = (Button) findViewById(R.id.btn_update);
        final Button btnDelete = (Button) findViewById(R.id.btn_delete);

        final EditText edtId = (EditText) findViewById(R.id.editTextId);
        final EditText edtName = (EditText) findViewById(R.id.editTextName);
        final EditText edtEmail = (EditText) findViewById(R.id.editTextEmail);

        final DBAdapter dba = new DBAdapter(this);

        // Insert
        // Contact------------------------------------------------------------------------

        btnInsert.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dba.open();
                contact = new Contact();
                contact.setName(edtName.getText().toString());
                contact.setAddress(edtEmail.getText().toString());
                dba.insertContact(contact);
                dba.close();
                edtName.setText("");
                edtEmail.setText("");
                Toast.makeText(getApplicationContext(), "Inserted",
                        Toast.LENGTH_LONG).show();
                Intent i = new Intent(SQliteDataBaseActivity.this,
                        SQliteDataBaseActivity.class);
                startActivity(i);
            }
        });
        // Select all
        // contacts----------------------------------------------------------------------------

        btnSelectall.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                getData();
                /*
                 * dba.open(); Cursor c=dba.getAllContacts();
                 * if(c.moveToFirst()){ do{ DisplayContact(c);
                 * }while(c.moveToNext()); } dba.close();
                 */
            }

            /*
             * private void DisplayContact(Cursor c){
             * Toast.makeText(getApplicationContext(),
             * "id: "+c.getString(0)+"\n"+"Name: "+c.getString(1)+"\n"+
             * "Email: "+c.getString(2), Toast.LENGTH_LONG).show();
             *
             * }
             */

            /*
             * private void DisplayContact(Cursor c){
             * Toast.makeText(getApplicationContext(),
             * "Name: "+c.getString(0)+"\n"+ "Email: "+c.getString(1),
             * Toast.LENGTH_LONG).show();
             *
             * }
             */
        });

        // Select a
        // contact----------------------------------------------------------------------

        btnSelect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dba.open();
                Cursor c = dba.getContact(Integer.parseInt(edtId.getText()
                        .toString()));
                if (c.moveToFirst()) {
                    DisplayContact(c);
                } else {
                    Toast.makeText(getApplicationContext(), "No contact found",
                            Toast.LENGTH_LONG).show();
                }
                dba.close();

            }

            private void DisplayContact(Cursor c) {
                Toast.makeText(
                        getApplicationContext(),
                        "id: " + c.getString(0) + "\n" + "Name: "
                                + c.getString(1) + "\n" + "Email: "
                                + c.getString(2), Toast.LENGTH_LONG).show();
            }
        });

        // Update a
        // contact----------------------------------------------------------------------

        btnUpdate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dba.open();
                if (dba.updateContact(Integer.parseInt(edtId.getText()
                        .toString()), edtName.getText().toString(), edtEmail
                        .getText().toString()))
                    Toast.makeText(getApplicationContext(),
                            "Update successful", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(getApplicationContext(), "Update failed",
                            Toast.LENGTH_LONG).show();
                dba.close();
                Intent i = new Intent(SQliteDataBaseActivity.this,
                        SQliteDataBaseActivity.class);
                startActivity(i);
            }
        });

        // Delete
        // contact------------------------------------------------------------------------------

        btnDelete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dba.open();
                dba.deleteContact(Integer.parseInt(edtId.getText().toString()));
                dba.close();
            }
        });
    }

    public void getData() {

        DBAdapter dbAdapter = new DBAdapter(SQliteDataBaseActivity.this);
        dbAdapter.open();

        Cursor c = dbAdapter.getAllContacts();
        c.moveToFirst();

        while (!c.isAfterLast()) {
            HashMap<String, String> map = new HashMap<String, String>();

            map.put("name", c.getString(c.getColumnIndex(DBAdapter.KEY_NAME)));
            map.put("address",
                    c.getString(c.getColumnIndex(DBAdapter.KEY_EMAIL)));

            c.moveToNext();

            contactList.add(map);
        }

        c.close();
        dbAdapter.close();

        listView = (ListView) findViewById(R.id.Listview);
        ayArrayAdapter = new AyArrayAdapter(SQliteDataBaseActivity.this,
                R.layout.name_list, contactList);
        listView.setAdapter(ayArrayAdapter);
    }

    public class AyArrayAdapter extends ArrayAdapter<HashMap<String, String>> {
        public AyArrayAdapter(Context handler, int textViewResourceId,
                ArrayList<HashMap<String, String>> contactList) {
            super(handler, textViewResourceId, contactList);
        }

        public View getView(final int position, View convertView,
                ViewGroup parent) {

            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(R.layout.name_list, null);

            TextView name = (TextView) rowView.findViewById(R.id.textViewname);
            name.setText(contactList.get(position).get("name"));

            TextView modelenumber = (TextView) rowView
                    .findViewById(R.id.textViewaddresas);
            modelenumber.setText(contactList.get(position).get("address"));

            return rowView;
        }
    }

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

}


Contact.java

package com.rakesh.tiwari.sqlitedatabase;

import java.io.Serializable;

@SuppressWarnings("serial")
public class Contact implements Serializable {
    private String name, address;

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

DBAdapter.java

package com.rakesh.tiwari.sqlitedatabase;

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

public class DBAdapter {

    public static final String KEY_ROWID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_EMAIL = "email";
    private static final String TAG = "DBAdapter";
    private static final String DATABASE_NAME = "myDB";
    private static final String DATABASE_TABLE = "contacts";
    private static final int DATABASE_VERSION = 1;
    /*public static final String DATABASE_CREATE = "create table contacts(id integer primary key autoincrement,"
            + "" + " name text not null,email text not null);";*/
    private static final String DATABASE_CREATE = "create table contacts(id integer primary key autoincrement, name text not null, email text not null);";

    private final Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    // Create construstor...............

    public DBAdapter(Context cntx) {
        this.context = cntx;
        DBHelper = new DatabaseHelper(context);

    }

    private static class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(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
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading Database from version" + oldVersion + "to"
                    + newVersion + ",which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }

    }

    // --- open the database----------------

    public DBAdapter open() throws SQLException {

        db = DBHelper.getWritableDatabase();
        return this;

    }

    // --- close database---------------------------------------------------

    public void close() {
        DBHelper.close();
    }

    // ----- Insert a contact into the
    // database---------------------------------------
    public long insertContact(Contact contact) {

        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, contact.getName());
        initialValues.put(KEY_EMAIL, contact.getAddress());
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a particular
    // contact--------------------------------------------------------------

    public boolean deleteContact(long rowId) {

        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    // Retrieve all
    // contacts.....................................................................

    public Cursor getAllContacts() {
        /*return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME ,KEY_EMAIL
                }, null, null, null, null, null);*/
        return db.query(DATABASE_TABLE, new String[] { KEY_NAME ,KEY_EMAIL
        }, null, null, null, null, null);


    }

    // retrieve a particular
    // contact.........................................................................

    public Cursor getContact(long rowId) throws SQLException {

        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                KEY_ROWID, KEY_NAME, KEY_EMAIL }, KEY_ROWID + "=" + rowId,
                null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();

        }
        return mCursor;
    }

    // Update a
    // contact-----------------------------------------------------------------------------------

    public boolean updateContact(long rowID, String name, String email) {
        ContentValues cValue = new ContentValues();
        cValue.put(KEY_NAME, name);
        cValue.put(KEY_EMAIL, email);
        return db.update(DATABASE_TABLE, cValue, KEY_ROWID + "=+rowId", null) > 0;

    }

}

main.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SQliteDataBaseActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="SQLite DataBase"
        android:textColor="#336633"
        android:textSize="20dp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/editTextId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="10dp"
       android:inputType="number"
       android:hint="ID"
        android:ems="5" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="10dp"
        android:inputType="textPersonName"
        android:hint="Name"
        android:ems="5" />

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:inputType="textEmailAddress"
        android:hint="Email"
        android:ems="8" />

    <Button
        android:id="@+id/btn_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editTextEmail"
        android:layout_marginTop="22dp"
        android:text="Insert" />
    <ListView
        android:id="@+id/Listview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/btn_insert"
        >
    </ListView>

    <Button
        android:id="@+id/btn_select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/btn_insert"
        android:layout_alignBottom="@+id/btn_insert"
        android:layout_alignLeft="@+id/editTextName"
        android:text="Select" />

    <Button
        android:id="@+id/btn_selectall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/btn_insert"
        android:layout_below="@+id/btn_insert"
        android:layout_marginTop="58dp"
        android:textSize="15sp"
        android:text="Select All" />
  

    <Button
        android:id="@+id/btn_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/btn_selectall"
        android:layout_alignLeft="@+id/btn_select"
        android:text="Update" />

    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_update"
        android:layout_marginTop="34dp"
        android:layout_toLeftOf="@+id/btn_update"
        android:text="Delete" />

</RelativeLayout>

name_list.xml


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

    <TextView
        android:id="@+id/textViewname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

    <TextView
        android:id="@+id/textViewaddresas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dp"
        android:text="" />

</LinearLayout>

Monday 8 December 2014

Custom ListView and ListItem Detail with Text and Image Example in Android Apps

 Custom ListView and List Item Detail

MainActivity.java

package com.rakesht.customlistview;

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

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

Sunday 21 September 2014

How to Integrate AdMob in Android Application

What is Admob?
AdMob is the Google product which is featured with display advertisement on mobile Apps by integrating with applications like Google AdSense for websites. It's not only for Android apps also featured for iOS and Windows Phone 8.

For more details follow below link.
Guide for AdMobe

For android go through Android Quick Start .
Develop using Eclipse IDE follow https://developer.android.com/training/monetization/ads-and-ux.html

Develop using Android Studio follow https://developer.android.com/training/monetization/ads-and-ux.html

To integrate AdMob in android applications first of all you need to update GooglePlayService through follow below steps.
Step-1:
Open your Eclipse IDE Window->open "Android SDK Manager"-> Extras and install Google Play Services

Step-2:
import "google play service"  which will be in android SDK (android-sdk-windows\extras\google\google_play_services).

Step-3:
 Integrate android AdMob SDK using "add external JAR" Right Click on project click on properties->Java Build Path->Libraries->click on "Add External JARs" using this path "android-sdk-windows\extras\google\admob_ads_sdk".


Thursday 10 April 2014

ViewAnimator Creation in Android Application



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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="View Animator"
        android:textColor="#336633"
        android:textSize="20sp"
        android:textStyle="bold" />