如何在onActivityResult中获取上下文?

时间:2014-11-05 03:59:53

标签: java android listview android-context onactivityresult

我有DialogFragment,可以选择使用startActivityForResult选择文件。然后我使用onActivityResult来接收数据和请求代码。使用filemanager选择文件后,我从onActivityResult访问它。现在选择的实际文件没有做太多,因为主要的问题是当文件进来时我可以得到它的名字,其他的东西。现在我将其添加到HashMap<String, Object>中,然后将其添加到ArrayList<HashMap<String, Object>>。然后,我想使用带有自定义xml布局的SimpleAdapter来填充列表视图。问题是SimpleAdapter需要上下文作为参数。我怎样才能在onActivityResult()中接收上下文?

一些代码可以更好地了解我正在做的事情:

    public class MyFragment extends DialogFragment {
    ...
    ...
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    ...
    //here I want to get the context
    SimpleAdapter simpleAdapter = new SimpleAdapter(thecontext, attachments_list, R.layout.mycustomlayout, keys, ids);
    ...
    }
    }

更新:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SimpleAdapter.notifyDataSetChanged()' on a null object reference

更新完整代码:

public class MyFragment extends DialogFragment {

    //code for whole activity
    public static final String NEW_NOTE_CARD_FRAGMENT_CODE = "1";

    //codes for each menu button
    public static final String PICK_FILE_REQ_CODE = "2";
    public static final String PICK_NEW_IMAGE_CODE = "3";


    //attachment keys
    public static final String KEY_ATTACHMENT_NAME = "a_name";
    public static final String KEY_ATTACHMENT_DATE_ADDED = "a_date_added";
    public static final String KEY_ATTACHMENT_ICON = "a_icon";

    ArrayList<HashMap<String, Object>> attachmentsListArray = new ArrayList<HashMap<String, Object>>();

    //listview
    ListView attachmentsListView;

    SimpleAdapter simpleAdapter;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.newnotecard, container, false);

        //dialog customizations
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        // set color transparent
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));


        final ImageButton addNewAttachment = (ImageButton) v.findViewById(R.id.addNewAttachment);



        //addNewAttachment
        addNewAttachment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //this adds the an xml layout to a linearlayout which is the layout of this dialog
                //new attachment window
                LayoutInflater thismenulayoutinflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View newnoteattachment_window = thismenulayoutinflater.inflate(R.layout.newnotenewattachment, newnotewindowextras, false);
                newnotewindowextras.addView(newnoteattachment_window);

                //listview for attachment files
                attachmentsListView = (ListView) newnoteattachment_window.findViewById(R.id.attachmentsListView);

                String attachmentName = "My test file ";
                String attachmentDateAdded = "Added: Nov ";

                //create random data
                for (int i = 0; i < 3; i++) {
                    HashMap<String, Object> singleAttachment = new HashMap<String, Object>();

                    singleAttachment.put(KEY_ATTACHMENT_NAME, attachmentName + i);
                    singleAttachment.put(KEY_ATTACHMENT_DATE_ADDED, attachmentDateAdded + (i + 1));

                    attachmentsListArray.add(singleAttachment);
                }


                String[] keys = {KEY_ATTACHMENT_NAME, KEY_ATTACHMENT_DATE_ADDED};
                int[] ids = {R.id.attachment_name, R.id.attachment_date_added};

                simpleAdapter = new SimpleAdapter(getActivity().getApplicationContext(), attachmentsListArray, R.layout.individualattachmentlayout, keys, ids);
                attachmentsListView.setAdapter(simpleAdapter);




                //the actual action for this button
                Intent openFileExplorerIntent = new Intent(Intent.ACTION_GET_CONTENT);
                openFileExplorerIntent.setType("*/*");
                getActivity().startActivityForResult(openFileExplorerIntent, Integer.parseInt(NEW_NOTE_CARD_FRAGMENT_CODE + PICK_FILE_REQ_CODE));
            }
        });

        return v;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        int reqCode_l = Character.getNumericValue(Integer.toString(requestCode).charAt(1));


        if (reqCode_l == Integer.parseInt(PICK_FILE_REQ_CODE)) {//do file pick stuff
            //new individual file window
            Log.i("MENU ACTION", "FILE PICK: " + data.getData());

            String attachmentName = "Title ";
            String attachmentDateAdded = "Edited: Nov ";

            for (int i = 0; i < 6; i++) {
                HashMap<String, Object> singleAttachment = new HashMap<String, Object>();

                singleAttachment.put(KEY_ATTACHMENT_NAME, attachmentName + (i+1));
                singleAttachment.put(KEY_ATTACHMENT_DATE_ADDED, attachmentDateAdded + (i + 1));
                //singleAttachment.put(KEY_ATTACHMENT_ICON, tmp_attachmentIcon);

                attachmentsListArray.add(singleAttachment);
            }

            simpleAdapter.notifyDataSetChanged();
        }


    }
}

我在这里看到的一个大问题是在startActivityOnResult完成后我们回到对话框的活动中,变量设置为null,我初始化按钮点击。

NEW UPDATE

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        Log.i("LIFECYCLE", "onCreate");
    }

@Override
    public void onDestroyView() {

        Log.i("LIFECYCLE", "Fragment onDestroyView");

        if (getDialog() != null && getRetainInstance())
            getDialog().setDismissMessage(null);
        super.onDestroyView();
    }

同样,当startActivtiyForResult被调用时onPause()onStop(),但onDestroyView()永远不会被调用。

它仍然无法运作。

最终更新

我想为我正在做的愚蠢的高度道歉。在我Activity的托管MainActivity.java中,当Activity调用onActivityResult()时,我会创建一个对话框片段的新实例:new MyDialogFragment().onActivityResult()这就是为什么你们这些人的方法都没有工作的原因onCreateView这次没有被调用。我已将new MyDialogFragment()更改为我实际显示的先前初始化的对话框片段,现在一切正常。我将结束这个问题。

2 个答案:

答案 0 :(得分:1)

<强>更新

如果DialogFragment没有添加到后台堆栈,那么您可以在第一次创建时尝试使用 setRetainInstance (boolean retain)

原始回答

我认为您需要稍微修改一下程序流程。

简而言之,您应该为数据设置ListViewArrayList,并在onActivityCreated设置Adapter

这样,在您的用户可以从DialogFragment中选择一个文件之前,您将准备好ListView及其适配器以接收新数据。

然后在onActivityResult块中,只需将数据添加到ArrayList并在适配器上调用notifyDatasetChanged

答案 1 :(得分:0)

ohkay试试这个,先生..假设你的活动课是Gurinderhans;

static Gurinderhans ellt; // lol

然后仍在您的活动课程中。

static Gurinderhans getGurinderhans(){
    return ellt;        
}

然后在你的活动onCreate()

Gurinderhans.ellt = this; //or ellt = this;

然后在你的dialogfragment onActivityResult中执行此操作

Gurinderhans.getGurinderhans() // this is my class, activity and context..

所以看起来应该是这样的

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
...
//here I want to get the context
SimpleAdapter simpleAdapter = new SimpleAdapter(Gurinderhans.getGurinderhans(), attachments_list, R.layout.mycustomlayout, keys, ids);
...
}

如果有帮助,请告诉我..