Display data & image from mysql to android ListView

15/04/2017   03:50:39 PM
Hello in this android article i will explain how to display data with image from mysql data base to android ListView using PHP.in this example we add some test images in folder and images path in to mysql table manually then display it on Listview.So let's start the example.
 
1. Create a folder for project and a folder for images in to wamp/test/Images  
    Add images in to Images folder
 
2. Create a database sampleDB & create a table androidosnames on wamp localhost.if you want to fetch data from remote or from server then you need to upload database to your hosting panel.and for images path like this http://your domain name/images folder name/image name
 
display data & image from mysql android
 

3. Create a Php page, getandroidosnames.php to connect to android  

<?php
require_once('dbConnect.php');
$sql = "SELECT * FROM androidosnames";
$r = mysqli_query($con,$sql);
$result = array();
while($res = mysqli_fetch_array($r)){
array_push($result,array(
"AndroidNames"=>$res['AndroidNames'],
"ImagePath"=>$res['ImagePath']
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
 
4. Create a project in android studio
 
5. Add following code in to activity_main.xml file
 
<?xml version="1.0" encoding="utf-8"?>
<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="com.xperiaitinnovations.listviewandimgmysql.MainActivity">
    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lst"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />
</RelativeLayout>
 
 
6. Create xml layout file  
 
<?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">
    <ImageView
        android:layout_width="80dp"
        android:layout_height="100dp"
        android:id="@+id/imgvw"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="0dp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/tvandroidosnames" />
</LinearLayout>

 

7. Create a java class Getjson.java

package com.xperiaitinnovations.listviewandimgmysql;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * Created by Shree on 10/25/2016.
 */
public class Getjson {
     public static String[] Image_Url;
    public static Bitmap[] bitmaps;
    public static String[] Android_Name;
    public static final String JSON_ARRAY="result";
    public static final String IMAGEURL = "ImagePath";
    public static final String AndroidName = "AndroidNames";
    private String json;
    private JSONArray urls;
    public Getjson(String json){
        this.json = json;
        try {
            JSONObject jsonObject = new JSONObject(json);
            urls = jsonObject.getJSONArray(JSON_ARRAY);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private Bitmap getImage(JSONObject jo){
        URL url = null;
        Bitmap image = null;
        try {
            url = new URL(jo.getString(IMAGEURL));
            image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return image;
    }
    public void getAllImages() throws JSONException {
        Android_Name = new String[urls.length()];
        Image_Url = new String[urls.length()];
        bitmaps = new Bitmap[urls.length()];
        for(int i=0;i<urls.length();i++)
        { Android_Name[i]= urls.getJSONObject(i).getString(AndroidName);
            Image_Url[i] = urls.getJSONObject(i).getString(IMAGEURL);
            JSONObject jsonObject = urls.getJSONObject(i);
            bitmaps[i]=getImage(jsonObject);
        }
    }
}
 
8. Create a class Customadapter.java
 
package com.xperiaitinnovations.listviewandimgmysql;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
 * Created by Shree on 10/25/2016.
 */
public class Customadapter extends ArrayAdapter<String> {
    private String[] androidosnames;
    private String[] urls;
    private Bitmap[] bitmaps;
    private Activity context;
    public Customadapter(Activity context,    String[] androidosnames,  Bitmap[] bitmaps  ) {
        super(context, R.layout.layout, androidosnames);
        this.context = context;
      // this.urls = urls;
        this.bitmaps = bitmaps;
        this.androidosnames = androidosnames;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View listViewItem = inflater.inflate(R.layout.layout, null, true);
        TextView  androidos = (TextView) listViewItem.findViewById(R.id.tvandroidosnames);
       // TextView textView = (TextView) listViewItem.findViewById(R.id.tvurl);
      //  textView.setText(urls[position] );
        androidos.setText(androidosnames[position] );
        ImageView image = (ImageView) listViewItem.findViewById(R.id.imgvw);
          image.setImageBitmap(Bitmap.createScaledBitmap(bitmaps[position], 100, 50, false));
        return  listViewItem;
    }
}
 
9. Add the following Code in MainActivity.java
 
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
    ListView listView;
    private static final String newurl = "http://192.168.0.6/RegistrationLogin/getandroidosnames.php";
    private String json;
    private JSONArray urls;
    public  Getjson getjsonobj;
    Customadapter customadapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.lst);
        getURLs();
    }
    //Get FoodTYpe
    private void getImages() {
        class GetImages extends AsyncTask<Void, Void, Void> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this, "Loading Menu", "Please wait...", false, false);
            }
            @Override
            protected void onPostExecute(Void v) {
                super.onPostExecute(v);
                loading.dismiss();
                customadapter = new Customadapter(MainActivity.this, getjsonobj.Android_Name ,getjsonobj.bitmaps );
                listView.setAdapter(customadapter);
        }
            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    getjsonobj.getAllImages();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        GetImages getImages = new GetImages();
        getImages.execute();
    }
    private void getURLs() {
        class GetURLs extends AsyncTask<String, Void, String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this, "Loading...", "Please Wait...", true, true);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                getjsonobj = new Getjson(s);
                getImages();
            }
            @Override
            protected String doInBackground(String... strings) {
                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(strings[0]);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetURLs gu = new GetURLs();
            gu.execute(newurl);
    }
}
 
10. Add internet uses permission in manifest.xml
<uses-permission android:name="android.permission.INTERNET" />

 

OUTPUT

 

display data & image from mysql android listview

>

 


Output

                   

Support us by Sharing