Search code examples
androidjsonandroid-asynctaskandroid-sharedpreferences

using shared preferences on AsyncTask class for display data


I'm stuck here.The problem is i have to access a SharedPreferences value and need it in an AsyncTask class. How i can access it in My AsyncTask ?. I need it for display data in JSON. When I try to acces it, "JSON parsing error : No Value lokasi" This is my code to take shared preferences. I wan't to display with the following code :

private String email = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        dataList = new ArrayList<>();
        //lv = (ListView) findViewById(R.id.list);

        //Fetching email from shared preferences
        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF,"Not Available");
        //new GetEmail(email);
        new GetContacts().execute(email);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.

This is my code to get data JSON. I wan't to display with the following code :

 private class GetContacts extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... params) {
            HttpHandler sh = new HttpHandler();
            String email = params[0]; //WHAT NOW ?

            // Making a request to url and getting response
            String url = "http://192.168.43.176/GOLearn/lokasi.php?imei="+email;
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("lokasi");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        String id = c.getString("id");
                        String name = c.getString("name");
                        String latitude = c.getString("latitude");
                        String longitude = c.getString("longitude");


                        // tmp hash map for single contact
                        HashMap<String, String> map = new HashMap<>();

                        // adding each child node to HashMap key => value
                        map.put("id", id);
                        map.put("name", name);
                        map.put("latitude", latitude);
                        map.put("longitude", longitude);
                        //contact.put("mobile", mobile);

                        // adding contact to contact list
                        dataList.add(map);
                    }
                } 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;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(MapsActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
        }

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

            for (int x = 0; x < dataList.size(); x = x + 1) {
                double latasal = Double.parseDouble(dataList.get(x).get("latitude"));
                double longasal = Double.parseDouble(dataList.get(x).get("longitude"));
                LatLng posisi = new LatLng(latasal, longasal);
                String nama = dataList.get(x).get("name");

                mMap.addMarker(new MarkerOptions()
                        .position(posisi)
                        .title(nama)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.min_marker))
                );

                mMap.moveCamera(CameraUpdateFactory.newLatLng(posisi));

            }
        }
    }

This my php code :

<?php
mysql_connect("localhost","root","");
mysql_select_db("db_golearn");

$id = $_REQUEST['imei'];

$query="select * from lokasi where id='$id'";
$hasil=mysql_query($query);
if(mysql_num_rows($hasil) > 0) {

    $response = array();
    $response["lokasi"] = array();

    while ($data = mysql_fetch_array($hasil)) {
        $h['id']= $data['id'];
        $h['name']= $data['name'];
        $h['latitude']= $data['latitude'];
        $h['longitude']= $data['longitude'];
        $h['imei']= $data['imei'];

        array_push($response["lokasi"], $h);
    }

    $response["success"] = "1";
    echo json_encode($response);
}
else {
    $response["success"]=0;
    $response["message"]="Tidak ada data";

    echo json_encode($response);
}
?>

Please help


Solution

  • I cant comment on your question.So i am asking here. @Intan Iryanti:-where is your problem?.Where you want to use shared preference?

    add the following constructor in your async task

    private class GetContacts extends AsyncTask<String, Void, Void> {
    SharedPreferences sharedPreferences;
          public GetContacts(SharedPreferences sharedPreferences)
    {
    this.sharedPreferences= sharedPreferences;
    }
    

    @Override

    protected Void doInBackground(String... params) { HttpHandler sh = new HttpHandler(); String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF,"Not Available");

        // Making a request to url and getting response
        String url = "http://192.168.43.176/GOLearn/lokasi.php?imei="+email;
        String jsonStr = sh.makeServiceCall(url);
    

    ...

    ... }

    call async task as follow

    GetContacts getContacts=new getContacts(sharedPreferences);
    getContacts.execute();