-1

I am new to Android.

I want to get the values of drk_image or TAG_DRK_IMAGE from the HashMap and store it to private String[ ] drinkImages. Is this possible?

Code:

Lazy_ListItem.java

public class Lazy_ListItem extends Activity {

ListView list;
Lazy_Adapter adapter;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> drinksList;

// url to get all drinks list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_DRK_IMAGE = "drk_image";

// drinks JSONArray
JSONArray drinks = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_item);

    list = (ListView) findViewById(R.id.list);
    adapter = new Lazy_Adapter(this, drinkImages);
    list.setAdapter(adapter);

}

@Override
public void onDestroy() {
    list.setAdapter(null);
    super.onDestroy();
}

/**
 * Background Async Task to Load all drinks by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * getting All drinks from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
                params);

        // Check your log cat for JSON response
        Log.d("All Drinks: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // drinks found
                // Getting Array of Drinks
                drinks = json.getJSONArray(TAG_DRINKS);

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

                    // Storing each json item in variable
                    String drk_image = c.getString(TAG_DRK_IMAGE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_DRK_IMAGE, drk_image);

                    // adding HashList to ArrayList
                    drinksList.add(map);

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

        return null;
    }
}

private String[] drinkImages = {
        "http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
        "http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
        "http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
        "http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
        "http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" }; }

The value of String[ ] drinkImages must be replaced with values from the HashMap (from the database) and so I can pass it to Lazy_Adapter.

I want to get the values from the database instead of just declaring it like this:

private String[] drinkImages = {
        "http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
        "http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
        "http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
        "http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
        "http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" };

Lazy_Adapter.java

public class Lazy_Adapter extends BaseAdapter {

String drk_name, drk_desc, drk_price, drk_avail;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> drinksList;

// url to get all drinks list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";

// drinks JSONArray
JSONArray drinks = null;

private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public Lazy_ImageLoader imageLoader;

public Lazy_Adapter(Activity a, String[] d) {
    activity = a;
    data = d;
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader = new Lazy_ImageLoader(activity.getApplicationContext());

    // Hashmap for ListView
    drinksList = new ArrayList<HashMap<String, String>>();

    // Loading drinks in Background Thread
    new LoadAllProducts().execute();
}

public int getCount() {
    return data.length;
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

// ///

/**
 * Background Async Task to Load all drinks by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * getting All drinks from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
                params);

        // Check your log cat for JSON response
        Log.d("All Drinks: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // drinks found
                // Getting Array of Drinks
                drinks = json.getJSONArray(TAG_DRINKS);

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

                    // Storing each json item in variable
                    drk_name = c.getString(TAG_DRK_NAME);
                    drk_desc = c.getString(TAG_DRK_DESC);
                    drk_price = c.getString(TAG_DRK_PRICE);
                    drk_avail = c.getString(TAG_DRK_AVAIL);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value

                    map.put(TAG_DRK_NAME, drk_name);
                    map.put(TAG_DRK_DESC, drk_desc);
                    map.put(TAG_DRK_PRICE, drk_price);
                    map.put(TAG_DRK_AVAIL, drk_avail);

                    // adding HashList to ArrayList
                    drinksList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

}

@SuppressWarnings("unused")
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.item, null);

    for (Map<String, String> menuItem : drinksList) {
        ImageView image = (ImageView) vi.findViewById(R.id.image);
        imageLoader.DisplayImage(data[position], image);
        TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
        tvMenuName.setText(drinksList.get(position).get(TAG_DRK_NAME));
        TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
        tvMenuDesc.setText(drinksList.get(position).get(TAG_DRK_DESC));
        TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
        tvMenuPrice.setText("P"
                + drinksList.get(position).get(TAG_DRK_PRICE));
        TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
        tvMenuAvail.setText(drinksList.get(position).get(TAG_DRK_AVAIL));

    }

    return vi;
}}

EDIT:

Output:

This is the output if I have declared private String[] drinkImages. I am hoping to get the same output when getting it from the database.

Emulator Screenshot

Database Screenshot


I am doing this for my thesis. Really appreciate any help.

Thanks a lot~

serendipochi
  • 25
  • 10
  • Why are you using `HashMap` instead of a regular `List`? – vinitius Jan 30 '15 at 17:25
  • @vinitius I haven't tried using `List`. Been using `HashMap` following my professor's lessons. Sorry. Can you enlighten me how to implement it using `List` please? – serendipochi Jan 30 '15 at 17:33
  • Please check this tutorial --> http://www.learn2crack.com/2013/11/listview-from-json-example.html – Farshad Kazemi Jan 30 '15 at 17:45
  • @FarshadKazemi If I am using `private String[] drinkImages = { "http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg", "http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg", "http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg", "http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg", "http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" };` I'm getting the listview correctly. So what I am trying to do is just to replace it with data from db but with the same output. – serendipochi Jan 30 '15 at 17:49
  • @serendipochi, Which database is your mean ?1 SQLite(in your project) or MySQL (from server) ?! – Farshad Kazemi Jan 30 '15 at 17:57
  • @FarshadKazemi I am using MySQL. I don't have problem retrieving from MySQL database using JSON - my logcat's output is correct. I just want to replace the values of `String[ ] drinkImages from the values (still URLs) I retrieved from MySQL. – serendipochi Jan 30 '15 at 18:01
  • What's the `url image` attribute in your json? – vinitius Jan 30 '15 at 18:06
  • @vinitius This? `String drk_image = c.getString(TAG_DRK_IMAGE);` – serendipochi Jan 30 '15 at 18:08
  • @serendipochi, In your **LazyAdapter**, you didn't get **TAG_DRK_IMAGE**! Also in **Lazy_ListItem**, you didn't add this line in **onCreate** method --> new LoadAllProducts().execute(); – Farshad Kazemi Jan 30 '15 at 18:15
  • @serendipochi but you're not using it in `doInBackground()` – vinitius Jan 30 '15 at 18:16
  • @vinitius I did use it in `map.put(TAG_DRK_IMAGE, drk_image);`. – serendipochi Jan 30 '15 at 18:33
  • This post may provide same help .... http://stackoverflow.com/questions/541966/lazy-load-of-images-in-listview?rq=1 – aksdch11 Jan 30 '15 at 18:36
  • @FarshadKazemi Oh yes, I forgot to add `new LoadAllProducts().execute();` - Thank you for pointing that out. But what do you mean I didn't get `TAG_DRK_IMAGE` in **Lazy_Adapter**? My **Lazy_Adapter** parameter is `Lazy_Adapter(Activity a, String[] d)` where `String[] d` is `String[] drinkImages` from **Lazy_ListItem**. That's why I need to pass the value from the `HashMap` to `String[] drinkImages`. – serendipochi Jan 30 '15 at 18:46

1 Answers1

0

Because you are using AsyncTask, maybe your task isn't finished yet. So, you should add your adapter instance and assign it to your listview in onPostExecute method.

Please change your LazyListItem.java looklike below code:

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.widget.ListView;

public class Lazy_ListItem extends Activity {

ListView list;
Lazy_Adapter adapter;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all drinks list
private static String url_all_drinks =  "http://10.0.2.2/restosnapp/get_all_products.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_DRK_IMAGE = "drk_image";

// Your Images Array
private String[] drinkImages;

// drinks JSONArray
JSONArray drinks = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);

list = (ListView) findViewById(R.id.list);
new LoadAllProducts().execute();

}

@Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}

/**
* Background Async Task to Load all drinks by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {

/**
 * getting All drinks from url
 * */
protected String doInBackground(String... args) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // getting JSON string from URL
    JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
            params);

    // Check your log cat for JSON response
    Log.d("All Drinks: ", json.toString());

    try {
        // Checking for SUCCESS TAG
        int success = json.getInt(TAG_SUCCESS);

        if (success == 1) {
            // drinks found
            // Getting Array of Drinks
            drinks = json.getJSONArray(TAG_DRINKS);

            // Define Lenght for Images Array
            drinkImages = new String[drinks.length()];

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

                // Storing each json item in variable
                String drk_image = c.getString(TAG_DRK_IMAGE);

                // Add image into Array
                drinkImages[i] = drk_image;
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_DRK_IMAGE, drk_image);

                // adding HashList to ArrayList
                drinksList.add(map);

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

    return null;
}

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    adapter = new Lazy_Adapter(this, drinkImages);
    list.setAdapter(adapter);
    super.onPostExecute(result);
}
}
Farshad Kazemi
  • 358
  • 1
  • 4
  • 16
  • I am getting "The constructor Lazy_Adapter(Lazy_ListItem.LoadAllProducts, String[]) is undefined" on line `adapter = new Lazy_Adapter(this, drinkImages);` on **onPostExecute**. :/ – serendipochi Jan 30 '15 at 21:11
  • Sorry, Please change **this** to **Lazy_ListItem.this** – Farshad Kazemi Jan 30 '15 at 21:29
  • You forgot to add `drinksList = new ArrayList>();` on **onCreate**, but it's working now. Yay! Thank you so much for your help, especially for your patience. I really appreciate it! – serendipochi Jan 30 '15 at 21:41
  • @serendipochi, your welcome. hope you catch top score from professor's lessons ... – Farshad Kazemi Jan 30 '15 at 21:47
  • *crossfingers* I hope you keep on sharing your knowledge to others who are in need, too. Thank you again! – serendipochi Jan 30 '15 at 21:52