0

i create an app in android to displaying value of table, then i create database in hosting,

and this is the link for displaying my table,

and this script for select an output of my table,

send_data.php

<?php
header('Content-type:application/json;charset=utf-8');
include 'dbconfig.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "select id,ask from pertanyaan";
$result = mysqli_query($con, $query);
while ($r = mysqli_fetch_array($result)) {
   extract($r);
$rows[] = array(
    "id"    => $id,
    "ask"   => $ask
  );
}
echo json_encode($rows);
mysqli_close($con);
?>

but when i change the value in table, my application does not automatically update when I reopen the app, However, its application can be updated when I visit the link to display,

additional information :

this is my android code

MainActivity.java

package flix.yudi.okhttp1;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

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

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;
    RatingBar rb1;

    // URL to get contacts JSON
//    private static String url = "http://www.mocky.io/v2/580dd704120000b70a078702";
    private static String url = "http://zxccvvv.netne.net/send_data.php";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        contactList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONArray jsonObj = new JSONArray(jsonStr);

                    // looping through All Contacts
                    for (int i = 0; i < jsonObj.length(); i++) {
                        JSONObject c = jsonObj.getJSONObject(i);

                        String id = c.getString("id");
                        String ask = c.getString("ask");

                        HashMap<String, String> pertanyaans = new HashMap<>();

                        pertanyaans.put("id", id);
                        pertanyaans.put("ask", ask);

                        contactList.add(pertanyaans);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }
//        public class MainActivity extends Activity implements OnRatingBarChangeListener {
//        RatingBar ratingBar;
//
//        @Override
//        protected void onCreate(Bundle savedInstanceState) {
//            super.onCreate(savedInstanceState);
//            setContentView(R.layout.activity_main);
//            ((RatingBar) findViewById(R.id.ratingBar1)).setOnRatingBarChangeListener(this);
//        }
//
//        @Override
//        public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromTouch) {
//            final int numStars = ratingBar.getNumStars();
//            // set here your link
//            String serverlink = "";
//            if(numStars == 4)
//            {
//                serverlink = "http://www.example.com/4star.php";
//            }
//            else if(numStars == 5)
//            {
//                serverlink = "http://www.example.com/5star.php";
//            }
//
//            // now send link to server which is stored in serverlink object
//        }
//    }
//
//        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"ask"}, new int[]{R.id.ask});

            lv.setAdapter(adapter);
        }

    }
}

HttpHandler.java

package flix.yudi.okhttp1;

import android.util.Log;

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

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(7000);
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
            e.printStackTrace();
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
               e.printStackTrace();
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
Flix
  • 444
  • 8
  • 20
  • See [Activity Lifecycle](https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle). – simon Oct 27 '16 at 11:56
  • 1
    ***Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).*** [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Oct 27 '16 at 12:02
  • @simon but every time i tried to forcestop the app and reopen again, its still display an old value, until i did something like refreshing the link manually. So the app can update the value, @Jay yep i know if that `mysql_` function has been removed in PHP7, but i still using PHP 5.x.x, still not interesting for new update, hahaha – Flix Oct 27 '16 at 12:34
  • 1
    What do you mean with "forcestop"? It is probably better to put your `GetContacts()` call in `onResume()` if you want to load the values each time the user opens the app. And even if you still are on PHP 5.x you should urgently switch to mysqli oder PDO. See [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – simon Oct 27 '16 at 14:00
  • just for make sure that app didn't open in background, i did force stop the app from app list (in setting) so it can be ensured that the application is not running, but everytime i try to open the app after "force stop", screen displaying an old value. unless i refresh the link, thanks for the suggest, ill try it – Flix Oct 27 '16 at 15:55

0 Answers0