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