没有从捆绑包中获取哈希图 - Android

Posted

技术标签:

【中文标题】没有从捆绑包中获取哈希图 - Android【英文标题】:Not getting hashmap from bundle - Android 【发布时间】:2016-04-03 08:50:00 【问题描述】:

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

流程如下...

FragmentMainActivity -> TableScreenSectionwiseActivity -> GetSectionsAsync

HashMap is passed from GetSectionsAsync to TableScreenSectionwiseActivity through Bundle.

注意:FragmentMainActivity 是 FragmentActivity。TableScreenSectionwiseActivity 是 Fragment。GetSectionsAsync 是 AsyncTask。 H3>

我已经尝试过,如下所示。

我得到的错误...

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("GetSectionsForLocationResponseGetSectionsForLocationResult=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 代码。我可以放。但我不认为这是必需的。提前致谢。

【问题讨论】:

您的布局中有 TableScreenSectionwiseActivity 吗? 从布局中删除它。仅使用运行时事务 那么,改写什么。 View view = inflater.inflate(R.layout.table_screen_sectionwise, container, false); 你的活动布局中有&lt;fragment吗? 是的。我有 fragment_main_activity.xml,其中包括 &lt;fragment 【参考方案1】:

最后我通过INTERFACE实现了。

只需像下面这样......

    GetSectionsAsync.java 中创建名为FragmentInterfaceCallBack 的接口并声明一个名为onTaskCompleted() 的方法。

    现在在GetSectionsAsync.java 中定义一个名为setFragmentInterfaceCallBack 的方法,该方法将在从TableScreenSectionwiseActivity.java 调用时设置接口的对象。

    现在在onPostExecute 方法中编写下面的代码....interfaceCallBack.onTaskCompleted(details); details 是从网络服务接收到的数据。

    转到TableScreenSectionwiseActivity.java 并实现FragmentInterfaceCallBack,定义它的onTaskCompleted() 方法并将下面的代码添加到TableScreenSectionwiseActivity.java,您正在调用AsyncTask getSectionsAsync.setFragmentInterfaceCallBack(this);,其中getSectionsAsyncGetSectionsAsync.java 的对象.

onTaskCompleted() 方法中,您可以获得所需的数据。

我对我的两个文件进行了以下更改。

GetSectionsAsync.java

制作接口并定义setFragmentInterfaceCallBack()方法....

private FragmentInterfaceCallBack interfaceCallBack;

public interface FragmentInterfaceCallBack 
    public void onTaskCompleted(HashMap<String, ArrayList<String>> map);


public void setFragmentInterfaceCallBack(
        FragmentInterfaceCallBack _interfaceCallBack) 
    this.interfaceCallBack = _interfaceCallBack;

在 onPostExecute 方法中......

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.setSectionStatus1(true);
        // goAhead();
    
    interfaceCallBack.onTaskCompleted(details);

TableScreenSectionwiseActivity.java

实现接口.... public class TableScreenSectionwiseActivity extends Fragment implements OnItemClickListener, FragmentInterfaceCallBack

正在调用 AsyncTask.... if (!pref.getSectionStatus1()) Log.e("Once Again in TableScreenSectionwiseActivity: ", "hmm...."); GetSectionsAsync getSectionsAsync = new GetSectionsAsync( getActivity()); getSectionsAsync.setFragmentInterfaceCallBack(this); HashMap<String, String> map = new HashMap<String, String>(); map.put("Location_Name", pref.getLocation()); getSectionsAsync.execute(map);

定义接口的方法.... @Override public void onTaskCompleted(HashMap<String, ArrayList<String>> hashMap) ids = hashMap.get("ID_LIST"); names = hashMap.get("NAME_LIST"); table_section_adapter adapter = new table_section_adapter( activity.getApplicationContext(), names, ids); section_list.setAdapter(adapter); section_list.setOnItemClickListener(this);

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

【讨论】:

以上是关于没有从捆绑包中获取哈希图 - Android的主要内容,如果未能解决你的问题,请参考以下文章

如何从它们插入哈希图中的顺序打印哈希图值

树图还是哈希图? [复制]

等待哈希图更改的调用函数

CORBA IDL 哈希图

如何从捆绑包中获取课程

如何使用意图将哈希图值发送到另一个活动