26/06/2014

28/02/2014

Android Simple JsonListView

JsonMainActivity.Java

package com.example.json;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;

public class JsonMainActivity extends Activity
{
    public static String url="http://products.p41techdev.net/muthushomedelivery/category.php";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json_main);
        setContentView(R.id.listView1);
        parser ss = new parser();
        ss.execute(url);
    }

    public class parser extends AsyncTask<String,String, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            // TODO Auto-generated method stub
            String uu = params[0];
            InputStream is;
            String page = null;
            HttpClient ht = new DefaultHttpClient();
            HttpPost hp = new HttpPost(uu);
      
            try
            {
                HttpResponse res = ht.execute(hp);
                HttpEntity en = res.getEntity();
                is = en.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder("");
                String line;
                while((line = reader.readLine())!= null)
                {
                    sb.append(line);
                  
                }
             page = sb.toString();
              
             System.out.println("value"+page.toString());
              
            }
            catch (ClientProtocolException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }          
            return page;
          
        }

        @Override
        protected void onPostExecute(String result)
        {                  
            super.onPostExecute(result);
            ArrayList<ItemDTO> obj = new ArrayList<ItemDTO>();
            try {
                JSONArray jars = new JSONArray(result);
                for(int i=0;i<jars.length();i++)
                {
                    JSONObject jso =  jars.getJSONObject(i);
                    ItemDTO nn = new ItemDTO();
                    nn.setId(jso.getString("id"));
                    nn.setCategory(jso.getString("category"));
                    obj.add(nn);          
                  
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }  
  }
}


package com.example.json;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;

public class JsonMainActivity extends Activity
{
    public static String url="http://products.p41techdev.net/muthushomedelivery/category.php";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json_main);
        setContentView(R.id.listView1);
        parser ss = new parser();
        ss.execute(url);
    }

    public class parser extends AsyncTask<String,String, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            // TODO Auto-generated method stub
            String uu = params[0];
            InputStream is;
            String page = null;
            HttpClient ht = new DefaultHttpClient();
            HttpPost hp = new HttpPost(uu);
       
            try
            {
                HttpResponse res = ht.execute(hp);
                HttpEntity en = res.getEntity();
                is = en.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder("");
                String line;
                while((line = reader.readLine())!= null)
                {
                    sb.append(line);
                   
                }
             page = sb.toString();
               
             System.out.println("value"+page.toString());
               
            }
            catch (ClientProtocolException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
            return page;
           
        }

        @Override
        protected void onPostExecute(String result)
        {                   
            super.onPostExecute(result);
            ArrayList<ItemDTO> obj = new ArrayList<ItemDTO>();
            try {
                JSONArray jars = new JSONArray(result);
                for(int i=0;i<jars.length();i++)
                {
                    JSONObject jso =  jars.getJSONObject(i);
                    ItemDTO nn = new ItemDTO();
                    nn.setId(jso.getString("id"));
                    nn.setCategory(jso.getString("category"));
                    obj.add(nn);           
                   
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }   
  }
}

package com.example.json;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;

public class JsonMainActivity extends Activity
{
    public static String url="http://products.p41techdev.net/muthushomedelivery/category.php";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json_main);
        setContentView(R.id.listView1);
        parser ss = new parser();
        ss.execute(url);
    }

    public class parser extends AsyncTask<String,String, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            // TODO Auto-generated method stub
            String uu = params[0];
            InputStream is;
            String page = null;
            HttpClient ht = new DefaultHttpClient();
            HttpPost hp = new HttpPost(uu);
       
            try
            {
                HttpResponse res = ht.execute(hp);
                HttpEntity en = res.getEntity();
                is = en.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder("");
                String line;
                while((line = reader.readLine())!= null)
                {
                    sb.append(line);
                   
                }
             page = sb.toString();
               
             System.out.println("value"+page.toString());
               
            }
            catch (ClientProtocolException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
            return page;
           
        }

        @Override
        protected void onPostExecute(String result)
        {                   
            super.onPostExecute(result);
            ArrayList<ItemDTO> obj = new ArrayList<ItemDTO>();
            try {
                JSONArray jars = new JSONArray(result);
                for(int i=0;i<jars.length();i++)
                {
                    JSONObject jso =  jars.getJSONObject(i);
                    ItemDTO nn = new ItemDTO();
                    nn.setId(jso.getString("id"));
                    nn.setCategory(jso.getString("category"));
                    obj.add(nn);           
                   
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }   
  }
}



AdapterClass.Java
package com.example.json;



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.TextView;

public class Adapterclass extends BaseAdapter {
ArrayList<ItemDTO> opj = new ArrayList<ItemDTO>();
LayoutInflater inflater;
Context context;

public Adapterclass(Context c, ArrayList<ItemDTO> obj) {
this.opj = obj;
this.context = c;
inflater = LayoutInflater.from(c);

}


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


public Object getItem(int position) {
// TODO Auto-generated method stub
return opj.get(position);
}


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


public View getView(int position, View convertview, ViewGroup parent) {
Holder ho = new Holder();

if (convertview == null) {
    convertview = inflater.inflate(R.layout.newlist, null);
    ho.txt1 = (TextView) convertview.findViewById(R.id.textView1);
    ho.txt2 = (TextView) convertview.findViewById(R.id.textView2);
    convertview.setTag(ho);

} else {
    ho = (Holder) convertview.getTag();

}
ho.txt1.setText(opj.get(position).getId());
ho.txt2.setText(opj.get(position).getCategory());

return convertview;
}

public class Holder {
TextView txt1, txt2;

}

}
ItemDTO.Java
package com.example.json;

public class ItemDTO {
String id,category;

public String getId() {
    return id;
}

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

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

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

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="19dp" >
    </ListView>

</RelativeLayout>

newlist.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:orientation="horizontal" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Listview Value Stored in Sqlite


activity_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"  
    tools:context=".MainActivity"
    android:background="#f610">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:textStyle="bold"
        android:textColor="#ffffff"
        android:textSize="15dp"
        />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"></ListView>


</RelativeLayout>

MainActivity.Java

package com.example.insertjsonlistdb;

import java.util.ArrayList;

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

import android.app.Activity;
import android.os.Bundle;

import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

   String ParsingDta= "{\"Employee\":[{\"id\":\"101\",\"name\":\"gobi\",\"salary\":\"90000\"},{\"id\":\"102\",\"name\":\"hari\",\"salary\":\"700000\"},{\"id\":\"103\",\"name\":\"raj\",\"salary\":\"600000\"}]}";
   TextView textView1;
   ArrayList arrayList;
   String str="";
   ListView listView;
   Database database;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        database=new Database(this);
        this.deleteDatabase("EmployeeDatabase.db");
       
        database.getWritableDatabase();
       
        textView1=(TextView)findViewById(R.id.textView1);
       
        listView=(ListView)findViewById(R.id.listView);
       
        try
        {
          JSONObject jsonObject=new JSONObject(ParsingDta);
          JSONArray jsonArray= jsonObject.getJSONArray("Employee");
          for(int i=0;i<jsonArray.length();i++)
          {
              JSONObject jsonObject1=jsonArray.getJSONObject(i);
              String id=jsonObject1.getString("id").toString();
              String name=jsonObject1.getString("name").toString();
              String salary=jsonObject1.getString("salary").toString();
              database.insertData(id,name,salary);
             str+="\n Employee"+i+ "\n name:"+name+"\n id:"+id+"\n salary:" +salary+"\n";
             System.out.println("\n Employee"+i+ "\n name:"+name+"\n id:"+id+"\n salary:" +salary+"\n");             
           
          }
        }
        catch(JSONException e)
        {
                e.printStackTrace();
        }
       
        arrayList=database.fetchData();
        ArrayAdapter adapter=new ArrayAdapter(getApplicationContext(),android.R.layout.activity_list_item,android.R.id.text1,arrayList);
       listView.setAdapter(adapter);
    }
}



Database.Java

package com.example.insertjsonlistdb;

import java.util.ArrayList;

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

public class Database extends SQLiteOpenHelper {

    public Database(Context context)
    {
        super(context, "EmployeeDatabase.db", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db)
    {
        String tableEmp="create table emp(id text,name text,salary text)";
        db.execSQL(tableEmp);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
    }
    public void insertData(String id,String name, String salary)
    {
        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("id",id);
        values.put("name",name);
        values.put("salary",salary);
        sqLiteDatabase.insert("emp",null,values);
    }
    public ArrayList<String> fetchData()
    {
        ArrayList<String>stringArrayList=new ArrayList<String>();
        String fetchdata="select * from emp";
        SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
        Cursor cursor=sqLiteDatabase.rawQuery(fetchdata, null);
        if(cursor.moveToFirst()){
           do
            {
                stringArrayList.add(cursor.getString(1));
                //stringArrayList.add(cursor.getString(1));
                //stringArrayList.add(cursor.getString(2));
             } while (cursor.moveToNext());
        }
    return stringArrayList;
    }
}