Saturday, June 4, 2016

Populate GridView with ImageView and TextView from Mysql database In Android

1.First Activity Class for GrideView Main
public class New_GridView_Activity extends AppCompatActivity {

    //Web api url
    public static final String DATA_URL = "http://172.107.10.20/SSS/sss/New_Retrive_Image_Non_Encode_Direct_From_Server.php";

    //Tag values to read from json
    public static final String TAG_IMAGE_Name = "PO_Image";
    public static final String TAG_NAME = "PO_Name";

    //GridView Object
    private GridView gridView;

    //ArrayList for Storing image urls and titles
    private static ArrayList<String> images;
    private static ArrayList<String> names;
    private ProgressDialog pDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_gridview_layout);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarzoommm);
        toolbar.setLogo(R.drawable.logo);
        setSupportActionBar(toolbar);
       // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        gridView = (GridView) findViewById(R.id.gridView1);

        images = new ArrayList<>();
        names = new ArrayList<>();
        //Calling the getData method
        getData();

    }

    public void getData() {

        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        client.post(DATA_URL, params, new AsyncHttpResponseHandler() {

            @Override
            public void onStart() {
                pDialog = new ProgressDialog(New_GridView_Activity.this);
                pDialog.setMessage("Sending Request..");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                pDialog.dismiss();
            }

            @Override
            public void onSuccess(String response) {
                //  super.onSuccess(response);
                Log.d("Rs service_ReloadSqlDB res ", response);
                try {
                    JSONArray jsonArray = new JSONArray(response);

                    if (jsonArray.length() > 0) {

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);

                            String img = jsonObject.getString(TAG_IMAGE_Name);

                            images.add(img);
                            names.add(jsonObject.getString(TAG_NAME));

                        }
                        MainFragment_CustomAdapter_Gridview gridViewAdapter = new MainFragment_CustomAdapter_Gridview(New_GridView_Activity.this, images, names);

                        gridView.setAdapter(gridViewAdapter);

                    } else {
                        Toast.makeText(New_GridView_Activity.this, "No Data Found", Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    Log.d("Response Data Status:", e.getLocalizedMessage());
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                super.onFailure(throwable);
                Log.d(" RS onFailure ", throwable.toString());
            }
        });
    }

}
2.Adapter Class for Grid-view Main
I get Image And Text from Server as a String using JSON with PHP Web API From MySQL Database. 
NB: I Use "android-async-http-1.3.1.jar" Jar file in libs folder for  web request .
 ( AsyncHttpClient ). use build.gradle = compile files('libs/<android-async-http-1.3.1.jar>')

public class MainFragment_CustomAdapter_Gridview extends BaseAdapter {
    private Context context;
    //Array List that would contain the urls and the titles for the images
    private ArrayList<String> images;
    private ArrayList<String> names;

    public MainFragment_CustomAdapter_Gridview(Context context, ArrayList<String> images, ArrayList<String> names) {
        //Getting all the values
        this.context = context;
        this.images = images;
        this.names = names;
    }
    @Override
    public int getCount() {
        return images.size();
    }
    @Override
    public Object getItem(int position) {
        return images.get(position);
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //Creating a linear layout
        View grid;
        if (convertView == null) {
            grid = new View(context);
            LayoutInflater inflater = LayoutInflater.from(context);
            grid = inflater.inflate(R.layout.mainfragment_customeadapter_layout, parent, false);
        } else {
            grid = (View) convertView;
        }

        ImageView imageView = (ImageView) grid.findViewById(R.id.imageView_Im);
        TextView textView = (TextView) grid.findViewById(R.id.textView_Name);

        final String getImage = images.get(position);

        InputStream stream = new ByteArrayInputStream(Base64.decode(getImage.getBytes(), Base64.DEFAULT));

        Bitmap theImage = BitmapFactory.decodeStream(stream);

        imageView.setImageBitmap(theImage);

        textView.setText(names.get(position));

        final String name = names.get(position);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(context, Product_Details_Activity.class);
                //  Pass image index
                i.putExtra("id", getImage);
                i.putExtra("text", name);
                context.startActivity(i);
            }
        });
        return grid;
    }
}
3.Use this layout class in Adapter class

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imageView_Im"
        android:layout_width="88dp"
        android:layout_height="88dp"
        android:src="@drawable/sp1"
        android:layout_below="@+id/textView_pName"
        android:layout_gravity="center_horizontal" />
    <TextView
        android:id="@+id/textView_Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="22dp"
        android:text="TextView"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

4.3.Use this layout class in Main class
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include
        android:id="@+id/toolbarzoommm"
        layout="@layout/tool_bar"
        />
    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_marginTop="50dp"
        android:weightSum="1"
        >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25dp"
            android:layout_marginTop="0dp"
            android:layout_gravity="center"
            android:textStyle="bold"
            android:text="Products Item List..."
            android:layout_centerHorizontal="true" />
        <GridView
            android:id="@+id/gridView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView1"
            android:numColumns="2" >
        </GridView>
    </LinearLayout>

</RelativeLayout>
5.Use Internet Permission in Manifest class
 <uses-permission android:name="android.permission.INTERNET" />
NB: Store Image in MySQL Database BLOB type/ Formate.

Run your Application. Please comment any Query.


Wednesday, April 6, 2016

Android Populate ListView from JSON – Example

Creating Layout:

The Main layout for our project is “activity_main” which has a ListView to display the array.
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"
    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=".MainActivity" >
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/getdata" />
    <Button
        android:id="@+id/getdata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="23dp"
        android:text="Get Data" />
</RelativeLayout>
Next step is to create a layout for the list item that is to be displayed in ListView. Create the layout as list_v.xml which has three TextView’s to display the Array in each list item. Here I have created the TextView’s in LinearLayout.
list_v.xml

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- android help -->
<ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-1495591458562636"
     data-ad-slot="2543043308"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});

</script>
<?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="vertical" >
    <TextView
        android:id="@+id/vers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/api"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Creating Activity:

Before creating the MainActivity we need to create a JSON Parser class which gets the JSON data from the URL and returns JSON Object.
In your Project create a new folder library in the src folder such that the package is “learn2crack.listview.library”. Create the JSONParser.java in the library folder.
JSONParser.java
package smr.listview.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}
Next step is to create MainActivity.The Button “Get Data” is used to trigger the AsyncTask which process the backgroung Data. Here we are defining the array “oslist” which is displayed as text in ListView. The JSONArray is “android” which we got from the URL. It is then stored in a string. We are using ListAdapter is generate ListView. Finally we are using OnItemClickListener to display the OS in Toast when it is clicked.
MainActivity.java
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
    ListView list;
    TextView ver;
    TextView name;
    TextView api;
    Button Btngetdata;
    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
    //URL to get JSON Array
    private static String url = "http://api.learn2crack.com/android/jsonos/";
    //JSON Node Names
    private static final String TAG_OS = "android";
    private static final String TAG_VER = "ver";
    private static final String TAG_NAME = "name";
    private static final String TAG_API = "api";
    JSONArray android = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        oslist = new ArrayList<HashMap<String, String>>();
        Btngetdata = (Button)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 new JSONParse().execute();
            }
        });
    }
    private class JSONParse extends AsyncTask<String, String, JSONObject> {
         private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
             ver = (TextView)findViewById(R.id.vers);
             name = (TextView)findViewById(R.id.name);
             api = (TextView)findViewById(R.id.api);
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();
            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
        }
         @Override
         protected void onPostExecute(JSONObject json) {
             pDialog.dismiss();
             try {
                    // Getting JSON Array from URL
                    android = json.getJSONArray(TAG_OS);
                    for(int i = 0; i < android.length(); i++){
                    JSONObject c = android.getJSONObject(i);
                    // Storing  JSON item in a Variable
                    String ver = c.getString(TAG_VER);
                    String name = c.getString(TAG_NAME);
                    String api = c.getString(TAG_API);
                    // Adding value HashMap key => value
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_VER, ver);
                    map.put(TAG_NAME, name);
                    map.put(TAG_API, api);
                    oslist.add(map);
                    list=(ListView)findViewById(R.id.list);
                    ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
                            R.layout.list_v,
                            new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
                                    R.id.vers,R.id.name, R.id.api});
                    list.setAdapter(adapter);
                    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {
                            Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
                        }
                    });
                    }
            } catch (JSONException e) {
                e.printStackTrace();
            }
         }
    }
}

Creating Manifest:

Add the permision “android.permission.INTERNET” to the Manifest file as we need to access external Address.No other special Permissions are required for our project.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="learn2crack.listview"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="learn2crack.listview.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>
Finally run the project in the Emulator.
listview json parsing
Project Running in Emulator