Search code examples
androidandroid-fragmentsgridviewandroid-arrayadapternotifydatasetchanged

NotifyDataSetChanged on gridview not working - Android


I am working with GridView. I want to update GridView on some basis. But notifyDataSetChanged() method is not working.

I am selecting tables on basis of section name. When I select section name very first time than I got tables of that section. But when I go to sections fragment again and select diff. section than I get previously selected tables only. That means notifyDataSetChanged() is not working.

What I have tried is like below.

TableScreenActivity.java

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

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.malaka.R;
import com.malaka.db.DBAdapter;
import com.malaka.helper.ActionItem;
import com.malaka.helper.AssignGetterSetter;
import com.malaka.helper.Attributes;
import com.malaka.helper.CategoryAdapter;
import com.malaka.helper.DialogAdapter;
import com.malaka.helper.JoinTableAdapter;
import com.malaka.helper.ListSwipeDetector;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.AddNewCustomerAsync;
import com.malaka.helper.async.CustomerPhotoAsync;
import com.malaka.helper.async.GetValetNoAsync;
import com.malaka.helper.async.ReAssignTableAsync;
import com.malaka.helper.async.SetTableStatusAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.helper.async.UnAttendedAsync;
import com.malaka.helper.async.ValetAsync;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.PreferenceUtils;

public class TableScreenActivity extends Fragment {

    final static String TAG = "TableScreenActivity";
    Button btnBarCode, btnFeedBack, btnLogOut;
    GridView gridView;
    private TextView mDropdownTitle;
    static DBAdapter dbAdapter;
    TextView malaka, version;
    ImageView refresh;
    Animation rotation;
    boolean isOpen = false;
    RelativeLayout rl;
    public static FragmentActivity activity;
    LinearLayout mDropdownFoldOutNewCust;
    TextView dropDownTextViewNewCust, alt0NewCust, alt1NewCust,
            mDropdownTitleNewCust;
    LinearLayout ll;
    static Dialog dialogAddCust, joinDialog;
    ListSwipeDetector detector;
    static PreferenceUtils pref;
    ArrayList<String> tableName, tableId, sectionId, tableDescriptionId,
            tableDescription, custName, custId, custNo, parentId, isManager,
            parentName;
    ArrayList<String> isVale, isInquired;
    ArrayList<Integer> tableColors;
    Bundle bundle;
    String name = "", no = "", custType = "", tableIds, tableDesc;
    static String tableDescId;
    static EditText edtName, edtNo;
    int pos;
    QuickAction quickAction;
    QuickActionLocation quickActionLocation;

    private static final int ID_TABLE = 1;
    private static final int ID_TASK = 2;
    private static final int ID_MANAGER = 3;
    private static final int ID_RECIPE = 4;
    private static final int ID_INSTRUCTION = 5;
    private static final int ID_SEARCH = 6;
    private static final int ID_HELP = 7;
    private static final int ID_SETTING = 8;
    private static final int ID_LOGOUT = 9;
    private static final int ID_SECTIONS = 11;

    private static final int ID_KP = 10;
    private static final int ID_BANER = 20;
    private static final int ID_CITY = 30;

    static ArrayList<String> o_name, o_id, e_id, mTableIdList;

    private CategoryAdapter categoryAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        System.out.println("TestTag: savedInstanceState " + savedInstanceState
                + " container: " + container);
        System.out.println("TestTag: o_name " + o_name + " mTableIdList: "
                + mTableIdList);
        View view = inflater.inflate(R.layout.table_screen, container, false);
        init(view);
        return view;
    }

    private void init(View view) {
        System.out.println("TestTag: Time1: " + System.currentTimeMillis());
        // getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        activity = getActivity();
        o_id = new ArrayList<String>();
        o_name = new ArrayList<String>();
        e_id = new ArrayList<String>();
        mTableIdList = new ArrayList<String>();
        TextView textView = (TextView) view.findViewById(R.id.txt_table_status);
        textView.setVisibility(View.GONE);
        refresh = (ImageView) view.findViewById(R.id.img_refresh_table);
        rotation = AnimationUtils.loadAnimation(getActivity(),
                R.anim.refresh_dialog);
        pref = new PreferenceUtils(getActivity());
        version = (TextView) view.findViewById(R.id.table_version);
        version.setText(pref.getVersion());

        if (!pref.getTableStatus()) {
            TableStatusAsync Async = new TableStatusAsync(getActivity());
            HashMap<String, String> map = new HashMap<String, String>();
            Log.e(TAG,
                    "user id : " + pref.getUserId() + "location : "
                            + pref.getLocation() + "SectionId: "
                            + pref.getSectionId());
            map.put("UserId", pref.getUserId());
            map.put("SectionId", pref.getSectionId());
            map.put("Location", pref.getLocation());
            Async.execute(map);
        }

        dbAdapter = new DBAdapter(getActivity());
        dbAdapter.open();
        tableId = dbAdapter.getTableId();
        tableName = dbAdapter.getTableName();
        sectionId = dbAdapter.getTableSectionId();
        tableDescriptionId = dbAdapter.getTableDescriptionId();
        tableDescription = dbAdapter.getTableDescription();
        custName = dbAdapter.getTableCustName();
        custId = dbAdapter.getTableCustID();
        custNo = dbAdapter.getTableCustNo();
        parentId = dbAdapter.getTableParentId();
        parentName = dbAdapter.getTableParentName();

        isVale = dbAdapter.getTableIsValeStatus();
        isManager = dbAdapter.getTableIsManagerStatus();
        isInquired = dbAdapter.getTableIsInquiredStatus();
        dbAdapter.close();
        Log.d(TAG, "Table length ==" + tableId.size());
        tableColors = new ArrayList<Integer>();
        for (int i = 0; i < tableDescriptionId.size(); i++) {
            tableColors.add(Attributes.getColors(tableDescriptionId.get(i),
                    getActivity()));
        }

        ll = (LinearLayout) view.findViewById(R.id.table_ll);

        rl = (RelativeLayout) view.findViewById(R.id.ll);
        if (pref.getUserRole()) {
            rl.setVisibility(View.VISIBLE);
        } else {
            rl.setVisibility(View.GONE);
        }
        rl.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                quickActionLocation.show(arg0);
            }
        });

        detector = new ListSwipeDetector();

        malaka = (TextView) view.findViewById(R.id.txt_malaka_title_table);
        malaka.setText(pref.getLocation());
        gridView = (GridView) view.findViewById(R.id.gridView_table);
        if (tableId.size() <= 0) {
            gridView.setVisibility(View.GONE);
            textView.setVisibility(View.VISIBLE);
        } else {
            gridView.setVisibility(View.VISIBLE);
            textView.setVisibility(View.GONE);
        }

        dbAdapter = new DBAdapter(getActivity());

        // CategoryAdapter categoryAdapter = new CategoryAdapter(getActivity(),
        // 0,
        // tableName, tableColors, isInquired, custName,
        // tableDescriptionId, parentId, parentName, isManager);
        // gridView.setAdapter(categoryAdapter);
        // categoryAdapter.notifyDataSetChanged();

        //tableName.clear();
        //tableName = dbAdapter.getTableName();

        categoryAdapter = new CategoryAdapter(getActivity(), 0, tableName,
                tableColors, isInquired, custName, tableDescriptionId,
                parentId, parentName, isManager);
        gridView.setAdapter(categoryAdapter);
        categoryAdapter.notifyDataSetChanged();

        mDropdownTitle = ((TextView) view
                .findViewById(R.id.dropdown_textview_table));
        mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
                .substring(0, 1).toUpperCase()
                + pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
                + "   ");
        final TextView dropDownTextView = (TextView) view
                .findViewById(R.id.dropdown_textview_table);
        dropDownTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (PopupWindows.mWindow.isShowing()) {
                    closeDropdown();
                } else {
                    openDropdown();
                }
                quickAction.show(v);
            }
        });
        gridView.setOnTouchListener(detector);

gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
    ....
    ....
    }
    gridView.setOnItemClickListener(new OnItemClickListener() {
    ....
    ....
    }
}// init() method closes

    @Override
    public void onAttach(Activity activity) {
        Log.d(TAG, "TestTag::: onAttach()");
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "TestTag::: onCreate() savedInstanceState: "
                + savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        Log.d(TAG, "TestTag::: onStart()");
        super.onStart();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.d(TAG, "TestTag::: onActivityCreated(): savedInstanceState "
                + savedInstanceState);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        Log.d(TAG, "TestTag::: onResume()");
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.d(TAG, "TestTag::: onPause()");
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        Log.d(TAG, "TestTag::: onDestroyView()");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "TestTag::: onDestroy()");
        super.onDestroy();
    }

    @Override
    public void onStop() {
        Log.d(TAG, "TestTag::: onStop()");
        super.onStop();
    }

    @Override
    public void onDetach() {
        Log.d(TAG, "TestTag::: onDetach()");
        super.onDetach();
    }
}

Please, Help. I got stuck in. Thanks advance.

EDIT

TableStatusAsync.java

package com.malaka.helper.async;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.TableScreenActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;

public class TableStatusAsync extends
        AsyncTask<Map<String, String>, Void, Void> {

    final static String TAG = "TableStatusAsync";
    FragmentActivity context;
    String xml;
    PreferenceUtils pref;
    int response;
    boolean isConnected;

    public TableStatusAsync(FragmentActivity context) {
        this.context = context;
        pref = new PreferenceUtils(context);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        CommanUtils.getDialogShow(context, "Please Wait...");
    }

    @Override
    protected Void doInBackground(Map<String, String>... params) {

        if (NetworkUtils.isConnectedToInternet(context)) {
            isConnected = true;
            HashMap<String, String> map = (HashMap<String, String>) params[0];
            SoapObject request = new SoapObject(
                    AsyncAttributes.TableStatusNAMESPACE,
                    AsyncAttributes.TableStatusMETHOD_NAME);

            Iterator<String> iterator = map.keySet().iterator();

            // PropertyInfo pi1 = new PropertyInfo();
            // pi1.setName("UserId");
            // pi1.setValue(map.get("UserId"));
            // pi1.setType(String.class);
            //
            // PropertyInfo pi2 = new PropertyInfo();
            // pi2.setName("SectionId");
            // pi2.setValue(map.get("SectionId"));
            // pi2.setType(String.class);
            //
            // PropertyInfo pi3 = new PropertyInfo();
            // pi3.setName("Location");
            // pi3.setValue(map.get("Location"));
            // pi3.setType(String.class);
            //
            // request.addProperty(pi1);
            // request.addProperty(pi2);
            // request.addProperty(pi3);

            Log.e(TAG,
                    "user id : " + map.get("UserId") + "\nsection id : "
                            + map.get("SectionId") + "\nlocation : "
                            + map.get("Location"));

            while (iterator.hasNext()) {
                String key = iterator.next();
                request.addProperty(key, map.get(key));
                Log.d(TAG, "user id key: " + key + " value: " + map.get(key));
            }

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(
                    AsyncAttributes.TableStatusURL);

            try {
                androidHttpTransport.call(
                        AsyncAttributes.TableStatusSOAP_ACTION, envelope);
                SoapObject result = (SoapObject) envelope.bodyIn;

                if (result
                        .toString()
                        .equals("GetTableStatusResponse{GetTableStatusResult=No Table available; }")) {
                    String xmltemp = String.valueOf(result).split("=")[1];
                    xml = xmltemp.split(";")[0];
                } else {
                    String xmltemp = "<NewDataSet>\n"
                            + String.valueOf(result).split("<NewDataSet>")[1];
                    xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
                }

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

            if (xml == null) {
                response = 1;
                Log.d(TAG, "xml null");
            } else if (xml.equals("No Table available")) {
                response = 2;
            } else {
                response = 2;
                Log.d(TAG, "Task 1 result " + xml);
                TableStatusXmlParser.getTableStatusXmlParseData(xml, context);
            }
        } else {
            isConnected = false;
        }
        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        CommanUtils.getDialogDismiss();
        if (!isConnected) {
            CommanUtils.showAlertDialog("Internet Is Required", context);
        } else if (response == 1) {
            CommanUtils.getToast("Server Error", context);
        }
        if (response == 2) {
            pref.setTableStatus(true);
            ReplaceFragment.getReplaceFragment(context,
                    new TableScreenActivity(), "");
        }
    }
}

EDIT - 2

CategoryAdapter.java

package com.malaka.helper;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.malaka.R;
import com.malaka.utils.PreferenceUtils;

public class CategoryAdapter extends ArrayAdapter<String> {
    ArrayList<String> table, custName, isInquired, isManager, sectionId,
            parentId, parentname;
    ArrayList<Integer> tableColors;
    FragmentActivity context;
    ArrayList<Boolean> status;
    View view;
    PreferenceUtils pref;
    int posision;
    final static String TAG = "CategoryAdapter";

    public CategoryAdapter(FragmentActivity context, int textViewResourceId,
            List<String> objects, List<Integer> colors,
            List<String> isInquired, List<String> custName,
            List<String> sectionId, List<String> parentId,
            List<String> parentname, List<String> ismanager) {
        super(context, textViewResourceId, objects);
        // TODO Auto-generated constructor stub
        table = (ArrayList<String>) objects;
        this.parentId = (ArrayList<String>) parentId;
        this.parentname = (ArrayList<String>) parentname;
        pref = new PreferenceUtils(context);
        this.custName = (ArrayList<String>) custName;
        tableColors = (ArrayList<Integer>) colors;
        this.isManager = (ArrayList<String>) ismanager;
        this.isInquired = (ArrayList<String>) isInquired;
        this.sectionId = (ArrayList<String>) sectionId;
        status = new ArrayList<Boolean>();
        Log.i(TAG, "\nisInquired == " + isInquired);
        this.context = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        view = convertView;
        ViewHolder holder = new ViewHolder();
        if (convertView == null) {
            Display display = context.getWindowManager().getDefaultDisplay();
            int height = display.getHeight() / 8;
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.table_screen_row, null);
            holder.textView = (TextView) convertView
                    .findViewById(R.id.txt_category_seat);
            holder.txtName = (TextView) convertView
                    .findViewById(R.id.txt_customer_name);
            holder.imageViewManager = (ImageView) convertView
                    .findViewById(R.id.imageView_table_manager);
            holder.textViewValet = (TextView) convertView
                    .findViewById(R.id.text_table_valley);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, height);

            holder.rl = (RelativeLayout) convertView
                    .findViewById(R.id.category_seat);
            holder.rl.setLayoutParams(params);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        // if(isVale.get(position).equals("0")){
        // holder.textViewValet.setText("");
        // }else{
        // if(parentId.get(position).equals("0")){
        // holder.textViewValet.setText(isVale.get(position));
        // }
        // }

        Log.d(TAG, "custName == " + custName.get(position) + "\nlength == "
                + custName.get(position).length());
        if (custName.get(position).length() > 9) {
            if (parentId.get(position).equals("0")) {
                holder.txtName.setText(custName.get(position).substring(0, 8)
                        + "...");
                holder.textView.setText(table.get(position));
            } else {
                // we have to use parent table Name when Parent id is not 0
                holder.txtName.setText(parentname.get(position));
                holder.textView.setText("");
            }
        } else {
            if (parentId.get(position).equals("0")) {
                holder.txtName.setText(custName.get(position));
                holder.textView.setText(table.get(position));
            } else {
                holder.txtName.setText(parentname.get(position));
                holder.textView.setText("");
            }
        }

        if (isManager.get(position).equals("true")) {
            holder.imageViewManager
                    .setBackgroundResource(R.drawable.manager_icon);
        } else {
            holder.imageViewManager.setBackgroundResource(0);
        }

        holder.rl.setBackgroundColor(tableColors.get(position));
        return convertView;
    }

    private class ViewHolder {
        TextView textView, txtName;
        ImageView imageViewManager;
        TextView textViewValet;
        RelativeLayout rl;
    }
}

Solution

  • At last I got the solution.

    I have done like below...

    I was maintaining a FLAG called getTableStatus to get the tables of particular section. If the value of getTableStatus is FALSE than only TableStatusAsync is called. At first selection of section, tables are coming from web service and those tables are being inserted in DB.

    On second time, selecting of SECTION, tables are coming from DB not from web service. And tables are coming from DB are of previously selected SECTION. So, there is nothing to do with notifyDataSetChanged().

    I have just change the FLAG value to FALSE by calling pref.setTableStatus(false); on selection of SECTION. Now, TableStatusAsync is called every time when you change your selection of SECTION.

    Modified Code...

    TableScreenSectionwiseActivity.java

    @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { pref.setSectionId(view.getTag().toString()); pref.setTableStatus(false); pref.setTableServiceStatus(false); Fragment fragment = new TableScreenActivity(); ReplaceFragment.getReplaceFragment(getActivity(), fragment, ""); }