没有从bundle获取hashmap - Android

时间:2015-12-29 12:57:22

标签: android android-fragments android-intent android-activity android-asynctask

我想从AsyncTask获取正在通过Bundle传递的HashMap。但我得到的是NullPointerException。

流程如下......

FragmentMainActivity -> TableScreenSectionwiseActivity -> GetSectionsAsync

HashMap is passed from GetSectionsAsync to TableScreenSectionwiseActivity through Bundle.

注意:
FragmentMainActivity为 FragmentActivity
TableScreenSectionwiseActivity为 Fragment
GetSectionsAsync为 AsyncTask

我试过的,如下所示。

我得错......

Error Image

TableScreenSectionwiseActivity.java

package com.malaka.ui;

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

import adapters.table_section_adapter;
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.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.malaka.R;
import com.malaka.helper.ActionItem;
import com.malaka.helper.GetSectionsGetterSetter;
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.GetSectionsAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.utils.PreferenceUtils;

public class TableScreenSectionwiseActivity extends Fragment implements
        OnItemClickListener {

    final static String TAG = "TableScreenSectionwiseActivity";
    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_KP = 10;
    private static final int ID_BANER = 20;
    private static final int ID_CITY = 30;

    String[] values = new String[] { "1", "2" };

    public static FragmentActivity activity;

    RelativeLayout rl;
    static PreferenceUtils pref;
    QuickAction quickAction;
    QuickActionLocation quickActionLocation;
    HashMap<String, ArrayList<String>> map1;
    ArrayList<String> ids, names;

    ListView section_list;
    TextView version, malaka;
    ImageView refresh;
    Animation rotation;
    private TextView mDropdownTitle;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.table_screen_sectionwise,
                container, false);
        init(view);
        return view;
    }

    private void init(View view) {

        activity = getActivity();
        pref = new PreferenceUtils(getActivity());

        malaka = (TextView) view
                .findViewById(R.id.txt_malaka_title_table_sectionwise);
        malaka.setText(pref.getLocation());

        if (!pref.getSectionStatus()) {
            GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
                    getActivity());
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("Location_Name", pref.getLocation());
            getSectionsAsync.execute(map);
        }

        Bundle bundle = new Bundle();
        Log.e("Bundle Size: ", bundle.size() + "");

        map1 = (HashMap<String, ArrayList<String>>) getArguments()
                .getSerializable("SECTIONS_HASHMAP");
        GetSectionsGetterSetter.setData(map1);
        ids = map1.get("ID_LIST");
        names = map1.get("NAME_LIST");

        for (int i = 0; i < names.size(); i++) {
            Log.e("Names: ", names.get(i));
        }

        section_list = (ListView) view
                .findViewById(R.id.section_name_list_view);
        table_section_adapter adapter = new table_section_adapter(
                activity.getApplicationContext(), values);
        section_list.setAdapter(adapter);
        section_list.setOnItemClickListener(this);

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

            @Override
            public void onClick(View arg0) {
                quickActionLocation.show(arg0);
            }
        });

        version = (TextView) view.findViewById(R.id.table_version_sectionwise);
        version.setText(pref.getVersion());

        rotation = AnimationUtils.loadAnimation(getActivity(),
                R.anim.refresh_dialog);
        refresh = (ImageView) view
                .findViewById(R.id.img_refresh_table_sectionwise);
        refresh.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                refresh.startAnimation(rotation);
                TableStatusAsync Async = new TableStatusAsync(getActivity());
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("UserId", pref.getUserId());
                map.put("SectionId", "0");
                map.put("Location", pref.getLocation());
                Async.execute(map);
            }
        });

        ActionItem tableItem = new ActionItem(ID_TABLE, "Table Status");
        ActionItem taskItem = new ActionItem(ID_TASK, "My Tasks");
        ActionItem managerItem = new ActionItem(ID_MANAGER, "Manager");
        ActionItem recipeItem = new ActionItem(ID_RECIPE, "Recipes");
        ActionItem instItem = new ActionItem(ID_INSTRUCTION, "Instructions");
        ActionItem searchItem = new ActionItem(ID_SEARCH, "Search");
        ActionItem helpItem = new ActionItem(ID_HELP, "Help");
        ActionItem settingItem = new ActionItem(ID_SETTING, "Settings");
        ActionItem logoutItem = new ActionItem(ID_LOGOUT, "Logout");

        ActionItem kpItem = new ActionItem(ID_KP, "Koregaon Park");
        ActionItem cityItem = new ActionItem(ID_CITY, "Phoneix Market");
        ActionItem banerItem = new ActionItem(ID_BANER, "Baner");

        quickActionLocation = new QuickActionLocation(getActivity(),
                QuickActionLocation.VERTICAL);
        quickActionLocation.addActionItem(kpItem, Color.WHITE);
        quickActionLocation.addActionItem(cityItem, Color.WHITE);
        quickActionLocation.addActionItem(banerItem, Color.WHITE);

        // use setSticky(true) to disable QuickAction dialog being dismissed
        // after an item is clicked
        // tableItem.setSticky(true);

        // create QuickAction. Use QuickAction.VERTICAL or
        // QuickAction.HORIZONTAL param to define layout
        // orientation
        quickAction = new QuickAction(getActivity(), QuickAction.VERTICAL);

        // add action items into QuickAction
        quickAction.addActionItem(tableItem, Color.WHITE);
        quickAction.addActionItem(taskItem, Color.parseColor("#F2A523"));
        if (pref.getUserRole()) {
            quickAction.addActionItem(managerItem, Color.parseColor("#F2A523"));
        }
        if (pref.getRecipeScreenStatus()) {
            quickAction.addActionItem(recipeItem, Color.parseColor("#F2A523"));
        }
        quickAction.addActionItem(instItem, Color.parseColor("#F2A523"));
        quickAction.addActionItem(searchItem, Color.parseColor("#F2A523"));
        quickAction.addActionItem(helpItem, Color.parseColor("#F2A523"));
        quickAction.addActionItem(settingItem, Color.parseColor("#F2A523"));
        quickAction.addActionItem(logoutItem, Color.parseColor("#F2A523"));

        // Set listener for action item clicked
        quickAction
                .setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
                    @Override
                    public void onItemClick(QuickAction source, int pos,
                            int actionId) {
                        ActionItem actionItem = quickAction.getActionItem(pos);
                        quickAction.dismiss();
                        // here we can filter which action item was clicked with
                        // pos or actionId parameter
                        if (actionId == ID_TABLE) {
                            closeDropdown();
                        } else if (actionId == ID_TASK) {
                            closeDropdown();
                            ReplaceFragment.getReplaceFragment(getActivity(),
                                    new TaskLeadingActivity(), "left");
                        } else if (actionId == ID_MANAGER) {
                            closeDropdown();
                            ReplaceFragment.getReplaceFragment(getActivity(),
                                    new ManagerPageActivity(), "left");
                        } else if (actionId == ID_RECIPE) {
                            closeDropdown();
                            ReplaceFragment.getReplaceFragment(getActivity(),
                                    new ReceipiesScreenActivity(), "left");
                        } else if (actionId == ID_INSTRUCTION) {
                            closeDropdown();
                            ReplaceFragment.getReplaceFragment(getActivity(),
                                    new InstructionActivity(), "left");
                        } else if (actionId == ID_SEARCH) {
                            closeDropdown();
                        } else if (actionId == ID_HELP) {
                            closeDropdown();
                        } else if (actionId == ID_SETTING) {
                            closeDropdown();
                            ReplaceFragment.getReplaceFragment(getActivity(),
                                    new SettingScreenActivity(), "left");
                        } else if (actionId == ID_LOGOUT) {
                            closeDropdown();
                            Logout logout = new Logout(getActivity());
                        }
                    }
                });

        // set listnener for on dismiss event, this listener will be called only
        // if QuickAction dialog was dismissed
        // by clicking the area outside the dialog.
        quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
            @Override
            public void onDismiss() {
                // Toast.makeText(getActivity(), "Dismissed",
                // Toast.LENGTH_SHORT).show();
                closeDropdown();
            }
        });

        // Set listener for action item clicked
        quickActionLocation
                .setOnActionItemClickListener(new QuickActionLocation.OnActionItemClickListener() {
                    @Override
                    public void onItemClick(QuickActionLocation source,
                            int pos, int actionId) {
                        ActionItem actionItem = quickActionLocation
                                .getActionItem(pos);
                        quickActionLocation.dismiss();
                        // here we can filter which action item was clicked with
                        // pos or actionId parameter
                        if (actionId == ID_KP) {
                            getTableStatus("Koregaon Park");
                        } else if (actionId == ID_CITY) {
                            getTableStatus("Phoneix Market City");
                        } else if (actionId == ID_BANER) {
                            getTableStatus("Baner");
                        }
                    }
                });

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

            @Override
            public void onClick(View v) {
                if (PopupWindows.mWindow.isShowing()) {
                    closeDropdown();
                } else {
                    openDropdown();
                }
                quickAction.show(v);
            }
        });
    }

    public void getTableStatus(String location) {
        pref.setLocation(location);
        Log.e(TAG, "location : " + pref.getLocation());
        TableStatusAsync Async = new TableStatusAsync(getActivity());
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("UserId", pref.getUserId());
        map.put("SectionId", "0");
        map.put("Location", pref.getLocation());
        Async.execute(map);
    }

    private void openDropdown() {
        mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
                R.drawable.arrow_up, 0);
    }

    private void closeDropdown() {
        mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
                R.drawable.arrow_down, 0);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        Toast.makeText(activity, "Clicked" + position, Toast.LENGTH_SHORT)
                .show();
    }
}

GetSectionsAsync.java

package com.malaka.helper.async;

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

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

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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.CustomerDetailsActivity;
import com.malaka.ui.TableScreenSectionwiseActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;

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

    final static String TAG = "GetSectionsAsync";
    FragmentActivity context;
    String xml;
    HashMap<String, ArrayList<String>> details;
    PreferenceUtils pref;
    int response;
    boolean isConnected;

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

    @Override
    protected void onPreExecute() {
        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.GetSecNAMESPACE,
                    AsyncAttributes.GetSecMETHOD_NAME);

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

            PropertyInfo pi = new PropertyInfo();
            pi.setName("RLocation");
            pi.setValue(map.get("Location_Name"));
            pi.setType(String.class);
            request.addProperty(pi);

            while (iterator.hasNext()) {
                String key = iterator.next();
                request.addProperty(key, map.get(key));
                Log.e(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.GetSecURL);

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

                if (result
                        .toString()
                        .equals("GetSectionsForLocationResponse{GetSectionsForLocationResult=Failur; }")) {
                    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.e(TAG, "xml null");
            } else if (xml.equals("No Table available")) {
                response = 2;
            } else {
                response = 2;
                Log.e(TAG, "Task 1 result " + xml);
                details = TableStatusXmlParser.getSectionsXml(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.setSectionStatus(true);
            goAhead();
        }
    }

    private void goAhead() {
        Bundle bundle = new Bundle();
        bundle.putSerializable("SECTIONS_HASHMAP", details);
        Fragment fragment = new TableScreenSectionwiseActivity();
        fragment.setArguments(bundle);
        ReplaceFragment.getReplaceFragment(context, fragment, "");
    }
}

如果你们想要FragmentMainActivity代码。我可以说。但我不这么认为是必要的。提前谢谢。

1 个答案:

答案 0 :(得分:0)

最后,我通过INTERFACE实现了它。

就像下面这样......

  1. 在名为GetSectionsAsync.java的{​​{1}}中创建界面,并声明名为FragmentInterfaceCallBack的方法。

  2. 现在在名为onTaskCompleted()的{​​{1}}中定义一个方法,该方法将在从GetSectionsAsync.java进行调用时设置界面的对象。

  3. 现在在setFragmentInterfaceCallBack方法中编写以下代码.... TableScreenSectionwiseActivity.java 详细信息是从网络服务收到的数据。

  4. 转到onPostExecute并实施interfaceCallBack.onTaskCompleted(details);,定义它的TableScreenSectionwiseActivity.java方法,并将以下代码添加到您调用AsyncTask的FragmentInterfaceCallBack onTaskCompleted() 1}}其中TableScreenSectionwiseActivity.javagetSectionsAsync.setFragmentInterfaceCallBack(this);的对象。

  5. getSectionsAsync方法中,您可以获得所需数据。

    我在两个文件中都进行了以下更改。

    <强> GetSectionsAsync.java

    制作界面并定义GetSectionsAsync.java方法....

    onTaskCompleted()

    setFragmentInterfaceCallBack()

    在onPostExecute方法....

    private FragmentInterfaceCallBack interfaceCallBack;

    public interface FragmentInterfaceCallBack {
        public void onTaskCompleted(HashMap<String, ArrayList<String>> map);
    }
    
    public void setFragmentInterfaceCallBack(
            FragmentInterfaceCallBack _interfaceCallBack) {
        this.interfaceCallBack = _interfaceCallBack;
    }
    

    <强> TableScreenSectionwiseActivity.java

    实施界面.... protected void onPostExecute(Void result) { super.onPostExecute(result);

    调用AsyncTask .... CommanUtils.getDialogDismiss(); if (!isConnected) { CommanUtils.showAlertDialog("Internet Is Required", context); } else if (response == 1) { CommanUtils.getToast("Server Error", context); } if (response == 2) { pref.setSectionStatus1(true); // goAhead(); } interfaceCallBack.onTaskCompleted(details); }

    定义界面的方法...... public class TableScreenSectionwiseActivity extends Fragment implements OnItemClickListener, FragmentInterfaceCallBack {

    那就是它。希望这会对某人有所帮助..