Android PHP MySQL - HTTP GET - Fill ListView

November 16, 2017 Oclemy Android MySQL, Android HttpURLConnection, Android ListView 6 minutes, 7 seconds

Hi guys.How do you do?Android PHP MySQL Retrieve- HTTP GET tutorial here. In this tutorial we are covering how to retrieve data from MySql database via PHP using HttpUrlConnection.Then we show the data in a simple ListView.

HttpURLConnection

  • Subclasses java.net.URLConnection
  • Directly Superclasses HttpsURLConnection

OverView

  • UrlConnection for HTTP used to send as well receive data over the web.Data may be of any type and length.
  • Can also be used to send and receive streams whose length isn’t known in advance.
  • To be used,we obtain a new HttpUrlconnection object by calling url.openConnection() and casting to HttpUrlConnection.
  • If we open a connction to a url with “https” scheme,this returns HttpsUrlConnection.

Sending Data

  • First the HttpUrlConnetions’s setDoOutput(true) to allow connection.
  • HTTP POST allows sending data.

Receiving Response

  • First the HttpUrlConnetions’s setDoInput(true) to allow connection.
  • HTTP POST allows receiving data.

NB/= For demo,PHP code and more explanations please have a look at our video tutorial below : [embedyt] http://www.youtube.com/watch?v=7G2gL6Yl-mA[/embedyt]

The Main Points

This android php mysql listview tutorial.We are using HttpURLConnection to make a HTTP GET request.

Section 1 : Our Connector Class

  • Has a static connect method that takes a URL Address string and returns a HttpURLConnection object.
  • Simply establishes connection to our server.
  • We set connection properties like Request method which is "GET",as we are making a HTTP GET request.
package com.tutorials.hp.mysqlhttpgetlistview.m_MySQL;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * ROLE : ESTABLISH CONNECTION TO SERVER
 */
public class Connector {

    public static Object connect(String urlAddress)
    {
        try
        {
            URL url=new URL(urlAddress);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();

            //SET CON PROPERTIES
            con.setRequestMethod("GET");
            con.setConnectTimeout(15000);
            con.setReadTimeout(15000);
            con.setDoInput(true);

            return con;

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();

        } catch (IOException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();

        }
    }

}

Section 2 : Our Downloader Class

  • Basically,we download data here.
  • We do this in AsyncTask.
  • Through a BufferedInputStream.
  • Then read using a BufferedReader.
  • We then call DataParser class to parse our data.
package com.tutorials.hp.mysqlhttpgetlistview.m_MySQL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

public class Downloader extends AsyncTask<Void,Void,String>{
    Context c;
    String urlAddess;
    ListView lv;

    ProgressDialog pd;

    public Downloader(Context c, String urlAddess, ListView lv) {
        this.c = c;
        this.urlAddess = urlAddess;
        this.lv = lv;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pd=new ProgressDialog(c);
        pd.setTitle("Retrieve");
        pd.setMessage("Retrieving..Please wait");
        pd.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        return this.downloadData();
    }

    @Override
    protected void onPostExecute(String jsonData) {
        super.onPostExecute(jsonData);

        pd.dismiss();
        if(jsonData.startsWith("Error"))
        {
            Toast.makeText(c,"Unsuccessful "+jsonData,Toast.LENGTH_SHORT).show();
        }else
        {
            //PARSE
            new DataParser(c,jsonData,lv).execute();
        }

    }

    private String downloadData()
    {
        Object connection=Connector.connect(urlAddess);
        if(connection.toString().startsWith("Error"))
        {
            return connection.toString();
        }

        try {
            HttpURLConnection con= (HttpURLConnection) connection;

            InputStream is=new BufferedInputStream(con.getInputStream());
            BufferedReader br=new BufferedReader(new InputStreamReader(is));

            String line;
            StringBuffer jsonData=new StringBuffer();

            while ((line=br.readLine()) != null)
            {
                jsonData.append(line+"n");

            }

            br.close();
            is.close();

            return jsonData.toString();

        } catch (IOException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();
        }

    }
}

Section 3 : Our DataParser Class

  • Yes,its DataParser class.
  • To parse our data.
  • We use the native org.JSON classes to parse.Using JSONArray and JSONObect.
  • We then fill a simple ArrayList with data we have parsed.
  • Then pass the arraylist to our ArrayAdapter.
  • And bind the adapter to the ListView.
  • Then simple ItemClickListener.
package com.tutorials.hp.mysqlhttpgetlistview.m_MySQL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

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

import java.util.ArrayList;

public class DataParser extends AsyncTask<Void,Void,Boolean> {

    Context c;
    String jsonData;
    ListView lv;

    ProgressDialog pd;
    ArrayList<String> spacecrafts=new ArrayList<>();

    public DataParser(Context c, String jsonData, ListView lv) {
        this.c = c;
        this.jsonData = jsonData;
        this.lv = lv;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pd=new ProgressDialog(c);
        pd.setTitle("Parse");
        pd.setMessage("Pasring..Please wait");
        pd.show();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        return this.parseData();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        pd.dismiss();
        if(result)
        {
            ArrayAdapter adapter=new ArrayAdapter(c,android.R.layout.simple_list_item_1,spacecrafts);
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(c, spacecrafts.get(position), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private Boolean parseData()
    {
        try
        {
            JSONArray ja = new JSONArray(jsonData);
            JSONObject jo;

            spacecrafts.clear();

            for (int i = 0; i < ja.length(); i++) {

                jo = ja.getJSONObject(i);

                String name = jo.getString("name");

                spacecrafts.add(name);
            }

            return true;

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }
}

Section 4 : Our MainActivity

  • Launcher activity.
  • Initialize UI like ListView.
  • Executes the sender AsyncTask on button click,passing on ListView,Context and URL.
package com.tutorials.hp.mysqlhttpgetlistview;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.tutorials.hp.mysqlhttpgetlistview.m_MySQL.Downloader;

public class MainActivity extends AppCompatActivity {

    final static String urlAddress="http://10.0.2.2/android/spacecraft_select_images.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ListView lv= (ListView) findViewById(R.id.lv);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Downloader(MainActivity.this,urlAddress,lv).execute();
            }
        });
    }

}

Section 6 : Our Layouts

ContentMain.xml

  • With a simple ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.mysqlhttpgetlistview.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />
</RelativeLayout>

Section 7 : Reminders

  • Remember to add permission for internet in your manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorials.hp.mysqlhttpgetlistview">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Cheers.

Comments