Dear Daniweb friends,
I created adapter like this:

public class PromotionAdapter {
    String code = null;
    String name = null;
    String continent = null;
    String region = null;

    public PromotionAdapter(String code, String name, String continent, String region) {
        super();
        this.code = code;
        this.name = name;
        this.continent = continent;
        this.region = region;
    }

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContinent() {
        return continent;
    }
    public void setContinent(String continent) {
        this.continent = continent;
    }
    public String getRegion() {
        return region;
    }
    public void setRegion(String region) {
        this.region = region;
    }

    @Override
    public String toString() {
        return  code + " " + name + " "
                + continent + " " + region;
    }
}

and created listview like this :

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" > <LinearLayout
        android:id="@+id/promotion_saja"
        android:layout_width="150dp"
        android:layout_height="160dp"
        android:orientation="vertical"> <ImageView
            android:id="@+id/image_promotion"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/promo_1"/> </LinearLayout> <RelativeLayout
        android:id="@+id/detail_country"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:layout_toRightOf="@+id/promotion_saja"
        android:layout_toEndOf="@+id/promotion_saja"
        android:orientation="vertical"
        android:layout_marginLeft="4dp"> <TextView
            android:id="@+id/code"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="TextView"
            android:textSize="24sp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_marginBottom="4dp"/> <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/code"
            android:layout_below="@+id/code"
            android:text="TextView"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_marginBottom="4dp"/> <TextView
            android:id="@+id/continent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/name"
            android:layout_below="@+id/name"
            android:text="TextView"
            android:textSize="14sp"
            android:textColor="@android:color/black"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_marginBottom="4dp"/> <TextView
            android:id="@+id/region"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/continent"
            android:layout_below="@+id/continent"
            android:text="TextView"
            android:textSize="14sp"
            android:textColor="@android:color/black"
            android:textAppearance="?android:attr/textAppearanceMedium"/> </RelativeLayout> </RelativeLayout>

and in the fragment I put static array like this:

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

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

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

public class promotionfragment extends Fragment {
    MyCustomAdapter dataAdapter = null;
    Button btnHome, btnOrder, btnCart, btnStore, btnMore;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_promotion, container, false);
        Bundle extras = getActivity().getIntent().getExtras();
        final String region= extras.getString("REGION");
        // URL to get contacts JSON
        final String url = Constant.URI_BASE_API
                + "Promotions?region=" + region;
        //Array list of countries
        ArrayList<PromotionAdapter> countryList = new ArrayList<PromotionAdapter>();
        PromotionAdapter country = new PromotionAdapter("Original Cheese & Tomato","Rp 25.000", "Topped with 100% mozzarella cheese & Tomato sauce",
                "183 kcal/ large slice");
        countryList.add(country);
        country = new PromotionAdapter("New York Deli","Rp 35.000","Ground beef, ham, pork frankfurter","145 kcal/ large slice");
        countryList.add(country);
        country = new PromotionAdapter("The Carolina","Rp 45.000","BBQ sauce, chicken breast strips, smoked bacon rashers","200 kcal/ large slice");
        countryList.add(country);
        country = new PromotionAdapter("Create Your Own","Rp 55.000","Create your own pizza by adding selection of toppings to our original cheese and tomato pizza","around 150 kcal/ large slice");
        countryList.add(country);
        country = new PromotionAdapter("Denpasar Pizza","Rp 65.000","Ground beef, ham, pork frankfurter","198 kcal/ large slice");
        countryList.add(country);
        country = new PromotionAdapter("Jakarta Pizza","Rp 75.000","Ground beef, ham, pork frankfurter","255 kcal/ large slice");
        countryList.add(country);
        country = new PromotionAdapter("Bandung Pizza","Rp 85.000","Ground beef, ham, pork frankfurter","177 kcal/ large slice");
        countryList.add(country);

        //create an ArrayAdaptar from the String Array
        dataAdapter = new MyCustomAdapter(rootView.getContext(),
                R.layout.promotion_info, countryList);
        ListView listView = (ListView) rootView.findViewById(R.id.listView1);
        // Assign adapter to ListView
        listView.setAdapter(dataAdapter);

        //enables filtering for the contents of the given ListView
        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // When clicked, show a toast with the TextView text
                PromotionAdapter country = (PromotionAdapter) parent.getItemAtPosition(position);
                Toast.makeText(rootView.getContext().getApplicationContext(),
                        country.getCode(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), ChoosePizza.class);
                intent.putExtra("REGION", region);
                intent.putExtra("PIZZA_NAME", country.getCode());
                intent.putExtra("PIZZA_PRICE", country.getName());
                intent.putExtra("PIZZA_DESC", country.getContinent());
                startActivity(intent);
            }
        });
        EditText myFilter = (EditText) rootView.findViewById(R.id.myFilter);
        myFilter.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                dataAdapter.getFilter().filter(s.toString());
            }
        });
        btnHome = (Button) rootView.findViewById(R.id.btnHome);
        btnOrder = (Button) rootView.findViewById(R.id.btnOrder);
        btnCart = (Button) rootView.findViewById(R.id.btnCart);
        btnStore = (Button) rootView.findViewById(R.id.btnStore);
        btnMore = (Button) rootView.findViewById(R.id.btnMore);
        btnOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //Intent intent = new Intent(getActivity(), FavouritePizza.class);
                //startActivity(intent);
                Toast.makeText(getActivity(), "Please choose domino pizza offer first", Toast.LENGTH_SHORT)
                        .show();
            }
        });
        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), Cart.class);
                intent.putExtra("REGION", region);
                startActivity(intent);
            }
        });
        btnStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), StoreLocation.class);
                intent.putExtra("REGION", region);
                startActivity(intent);
            }
        });
        btnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), More.class);
                intent.putExtra("REGION", region);
                startActivity(intent);
            }
        });
        return rootView;
    }
    public void addListenerOnButton() {

    }
    private class MyCustomAdapter extends ArrayAdapter<PromotionAdapter> {

        private ArrayList<PromotionAdapter> originalList;
        private ArrayList<PromotionAdapter> countryList;
        private CountryFilter filter;

        public MyCustomAdapter(Context context, int textViewResourceId,
                               ArrayList<PromotionAdapter> countryList) {
            super(context, textViewResourceId, countryList);
            this.countryList = new ArrayList<PromotionAdapter>();
            this.countryList.addAll(countryList);
            this.originalList = new ArrayList<PromotionAdapter>();
            this.originalList.addAll(countryList);
        }

        @Override
        public Filter getFilter() {
            if (filter == null){
                filter  = new CountryFilter();
            }
            return filter;
        }


        private class ViewHolder {
            TextView code;
            TextView name;
            TextView continent;
            TextView region;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            Log.v("ConvertView", String.valueOf(position));
            if (convertView == null) {

                LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.promotion_info, null);

                holder = new ViewHolder();
                holder.code = (TextView) convertView.findViewById(R.id.code);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.continent = (TextView) convertView.findViewById(R.id.continent);
                holder.region = (TextView) convertView.findViewById(R.id.region);

                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            PromotionAdapter country = countryList.get(position);
            holder.code.setText(country.getCode());
            holder.name.setText(country.getName());
            holder.continent.setText(country.getContinent());
            holder.region.setText(country.getRegion());

            return convertView;

        }

        private class CountryFilter extends Filter
        {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                constraint = constraint.toString().toLowerCase();
                FilterResults result = new FilterResults();
                if(constraint != null && constraint.toString().length() > 0)
                {
                    ArrayList<PromotionAdapter> filteredItems = new ArrayList<PromotionAdapter>();

                    for(int i = 0, l = originalList.size(); i < l; i++)
                    {
                        PromotionAdapter country = originalList.get(i);
                        if(country.toString().toLowerCase().contains(constraint))
                            filteredItems.add(country);
                    }
                    result.count = filteredItems.size();
                    result.values = filteredItems;
                }
                else
                {
                    synchronized(this)
                    {
                        result.values = originalList;
                        result.count = originalList.size();
                    }
                }
                return result;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {

                countryList = (ArrayList<PromotionAdapter>)results.values;
                notifyDataSetChanged();
                clear();
                for(int i = 0, l = countryList.size(); i < l; i++)
                    add(countryList.get(i));
                notifyDataSetInvalidated();
            }
        }
    }
}

I want to change static to dynamic array list from http://dev.onlinedominosid.com/newApi/Promotions?region=JKT (JSON). How to change it use looping?

So this static change to dynamic from JSON :

PromotionAdapter country = new PromotionAdapter("Original Cheese & Tomato","Rp 25.000", "Topped with 100% mozzarella cheese & Tomato sauce",
                    "183 kcal/ large slice");
            countryList.add(country);
            country = new PromotionAdapter("New York Deli","Rp 35.000","Ground beef, ham, pork frankfurter","145 kcal/ large slice");
            countryList.add(country);
            country = new PromotionAdapter("The Carolina","Rp 45.000","BBQ sauce, chicken breast strips, smoked bacon rashers","200 kcal/ large slice");
            countryList.add(country);
            country = new PromotionAdapter("Create Your Own","Rp 55.000","Create your own pizza by adding selection of toppings to our original cheese and tomato pizza","around 150 kcal/ large slice");
            countryList.add(country);
            country = new PromotionAdapter("Denpasar Pizza","Rp 65.000","Ground beef, ham, pork frankfurter","198 kcal/ large slice");
            countryList.add(country);
            country = new PromotionAdapter("Jakarta Pizza","Rp 75.000","Ground beef, ham, pork frankfurter","255 kcal/ large slice");
            countryList.add(country);
            country = new PromotionAdapter("Bandung Pizza","Rp 85.000","Ground beef, ham, pork frankfurter","177 kcal/ large slice");
            countryList.add(country);

Please help.
Regards,
Silent Lover

Recommended Answers

All 3 Replies

Gson and Jackson are most commonly used JSON parsing libraries.

You will create your POJO classes, as you did for PromotionAdapter, fetch JSON and then use either of the libraries to parse it based on your POJO class. Then you only provide collection (List, Array) to your adapter and let it do its job

In PromotionAdapter

  • The variables should be made private (also instantiating them to null is pointless, Objects will be null by default)
  • On line 7 you're calling super() for no reason.

In promotionfragment

  • According to convention, classes should start with an upper case letter and be camel cased: PromotionFragment.

Also keep in mind that variable names should be meaningful and represent their purpose or content. Things like PromotionAdapter country = are rather confusing to a reader. For instance, name the class Country or the variable promotionAdapter. However, since it's neither a country nor adapting anything (it's merely a POJO) it would be far less confusing if you named it PizzaCoupon, PizzaPromotion or even Pizza. You can easily rename variables/classes etc. by right clicking on it in your IDE and choosing refactor -> rename.

Now, on to the question.

You could use a library like gson for that.

Then, you could solve it with something like:

public class Parser {

    public List<PromotionAdapter> parseJson(final String jsonString) {

        // promotion adapters to be returned
        List<PromotionAdapter> promotionAdapterList = new ArrayList<>();

        // input is a generic json array
        JsonArray jsonArray = new JsonParser()
                .parse(jsonString)
                .getAsJsonArray();

        // for each element
        for (JsonElement jsonElement : jsonArray) {

            // create a new promotion
            PromotionAdapter adapter = new PromotionAdapter();

            // turn into a jsonObject for easy retrieval of values
            JsonObject jsonObject = jsonElement.getAsJsonObject();

            // retrieve value for key "coupon_code"
            adapter.setCode(jsonObject.get("coupon_code").toString());

            // TODO implement other PromotionAdapter fields

            // add promotion to list
            promotionAdapterList.add(adapter);

        }

        // return the list
        return promotionAdapterList;
    }

}

Also (since I love the fancy image upload feature) here's a reference for the json you're fetching:

2015-10-13--1444739651_1010x652_scrot.png

Keep in mind that when writing code that depends on a(n external) source of information (in this case Domino's json) you have to think about how your application will react when the source is unavailable, or changes (or even turns up empty which might happen with promotions).

I called gson-2.4.jar with compile from libs jar (in gradle), compile fileTree(dir: 'libs', include: ['.jar']), *I put it in libs folder.
and then What should I do in promotionfragment extends Fragment with that Parser class?
@ Traevel, How to called it to listview?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.