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.


No comments:

Post a Comment