0

I have a DialogFragment which gives an option to pick a file using startActivityForResult. I then use onActivityResult to recieve the data and request code. After the file is chosen using the filemanager I access it from onActivityResult. Not doing much with the actual file being chosen right now as the main problem is when the file comes in I can get its name, other stuff. Now I add this into a HashMap<String, Object> which is then added to ArrayList<HashMap<String, Object>>. I then want to use a SimpleAdapter with a custom xml layout to populate the listview. The problem is SimpleAdapter requires the context as a parameter. How can I recieve the context in onActivityResult()?

Some Code to get a better picture of what I am doing:

    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);
    ...
    }
    }

UPDATE:

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

UPDATE FULL CODE:

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();
        }


    }
}

The big problem I am seeing here is after the startActivityOnResult finishes and we come back into our activity to the dialog, the variables are set to null, the ones I initialize onbutton click.

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();
    }

Also when the startActivtiyForResult is called the onPause() and onStop() but onDestroyView() is never called.

It still doesn't work.

FINAL UPDATE

I would like to apologize to for the height of stupidity that I was making. In my hosting Activity which is MainActivity.java, when this Activity would call onActivityResult() I would create a new instance of the dialog fragment as such: new MyDialogFragment().onActivityResult() and obviously this is why none of your guys methods worked as onCreateView wasn't called this time. I have change new MyDialogFragment() to the previously initialized dialog fragment that I am actually displaying and everything works now. And I will close this question.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
someguy234
  • 559
  • 4
  • 17
  • 1
    you need the context for the activity? `Context context` lol.. then in your `onResume()` you instantiate it `context = this` now call it there `SimpleAdapter simpleAdapter = new SimpleAdapter(context, attachments_list, R.layout.mycustomlayout, keys, ids);` are you okay? – Elltz Nov 05 '14 at 04:05
  • Nope. This does not work either. In the Fragment onCreateView() I can use that, but not in onActivityResult() – someguy234 Nov 05 '14 at 04:08
  • Just to make sure, is the DialogFragment calling startActivityForResult? – Endor Nov 05 '14 at 04:10
  • Yes and I can recieve all the data as written above in the question. I will try moving it outside and call `adapter.notifyDatasetChanged();` here – someguy234 Nov 05 '14 at 04:10
  • to get context anywhere http://stackoverflow.com/questions/4391720/how-can-i-get-a-resource-content-from-a-static-context – Conn Nov 05 '14 at 04:17
  • I suggest Conn's URL http://stackoverflow.com/questions/4391720/how-can-i-get-a-resource-content-from-a-static-context – harsha.cs Nov 05 '14 at 05:26
  • I just tried that too. It doesn't work. And after when I pick a file the SimpleAdapter is set to null thus I cant call notifyDataSetChanged() – someguy234 Nov 05 '14 at 05:27
  • I tried the same method in an Activity and everything works as expected. Not in dialog fragment :( – someguy234 Nov 05 '14 at 06:05

2 Answers2

1

UPDATE

If the DialogFragment is not added to the back stack, then you can try using setRetainInstance (boolean retain) when you first create it.

ORIGINAL ANSWER

I think you need to modify your program flow a little.

Simply put, you should set up your ListView, the ArrayList for the data, and the Adapter in onActivityCreated.

This way, before your user can go pick a file from your DialogFragment, you will have your ListView and its Adapter ready to receive new data.

Then in the onActivityResult block, just add the data to the ArrayList and call notifyDatasetChanged on your Adapter.

Endor
  • 404
  • 3
  • 14
  • I was thinking this too. I will try and tell – someguy234 Nov 05 '14 at 04:22
  • I try but I get an error which I have pasted in question under UPATE. – someguy234 Nov 05 '14 at 04:54
  • My guess is that when you call startActivityForResult, your existing Activity is paused and DialogFragment detached/destroyed. After user picks a file, onActivityResult is called before onCreateView, which gives you a null pointer (Adapter). Maybe you can add some log to see if it is the order of execution that is causing the error. – Endor Nov 05 '14 at 07:00
  • http://stackoverflow.com/questions/26751103/values-are-set-to-null-after-onactivityresult i put that question here the values are set toq null but as you'll read my comments of the first attempted answer an image view created the same way isn't set to null and i have logged that as well – someguy234 Nov 05 '14 at 07:03
0

ohkay try this, Sir.. suppose your activity class is Gurinderhans;

static Gurinderhans ellt; // lol

then still in your activity class.

static Gurinderhans getGurinderhans(){
    return ellt;        
}

then in your activity onCreate()

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

then in your dialogfragment onActivityResult do this

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

so should look like this

 @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);
...
}

let me if it helps..

Elltz
  • 10,730
  • 4
  • 31
  • 59
  • Sir? Bro? it should work..i am putting this in comment because ur question does not specify it == do this please.. remove your codes that call the startactivity and all that from the oncreatView to the onActivitycreated method.. and i am sure there would not be a null pointer exception..This is a wild guess thou.. and also do you get the same error when you use this?? @gurinderhans – Elltz Nov 05 '14 at 08:53
  • I will try soon and let you know – someguy234 Nov 05 '14 at 17:06