0

I have an activity 1 which send intent to activity 2 as bellow:

activity 1

periodDatetv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent i = new Intent(Settings.this, SettingsPeriodDate.class);
                startActivityForResult(i, 100);
            }
        });

activity 2

@Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        todayCalendar = new GregorianCalendar();
        pickedDateCalendar = new GregorianCalendar();
        final Dialog dialog = new Dialog(SettingsPeriodDate.this);
        dialog.setContentView(R.layout.perioddatesettings);

        datePicker = (DatePicker) dialog.findViewById(R.id.DataPickerDate);

        dialog.show();

        Button okDialogButton = (Button) dialog
                .findViewById(R.id.dialogButtonOK);

        // if button is clicked, close the custom dialog
        okDialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar c = Calendar.getInstance();
                int currentYear = c.get(Calendar.YEAR);
                int currentMonth = c.get(Calendar.MONTH) + 1;
                int currentDay = c.get(Calendar.DAY_OF_MONTH);

                Day = datePicker.getDayOfMonth();
                Month = datePicker.getMonth() + 1;
                Year = datePicker.getYear();

                todayCalendar.set(currentYear, currentMonth, currentDay);
                pickedDateCalendar.set(Year, Month, Day);

                System.err.println("Choseon date = " + Day + "/" + Month + "/"
                        + Year);
                System.err.println("Today date = " + currentDay + "/"
                        + currentMonth + "/" + currentYear);

                int Days = daysBetween(todayCalendar.getTime(),
                        pickedDateCalendar.getTime());

                System.err.println("Daaaaays === " + Days);

                if (pickedDateCalendar.after(todayCalendar) || Days >= 1) {
                    System.err.println("Inside if pop it");
                    PopIt("Error ", "Please check the date again");

                }

                else {

                    periodDateSharedPreferences(Year, Month, Day);

                }
                dialog.dismiss();
                System.err.println("befor back");
                Intent saved2 = new Intent(SettingsPeriodDate.this,
                        Settings.class);
                startActivityForResult(saved2, 100);


            }

        });

        Button cancelDialogButton = (Button) dialog
                .findViewById(R.id.dialogButtonCancel);
        // if button is clicked, close the custom dialog
        cancelDialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent i = new Intent(SettingsPeriodDate.this,Settings.class);
                startActivity(i);
            }
        });

    }

    public int daysBetween(Date d1, Date d2) {
        return (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
    }

    public void periodDateSharedPreferences(int calculatedPeriodYear,
            int calculatedPeriodMonth, int calculatedPeriodDay) {
        SharedPreferences periodDatePreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = periodDatePreferences.edit();
        editor.putInt("periodChosenDay", calculatedPeriodDay);
        editor.putInt("periodChosenMonth", calculatedPeriodMonth);
        editor.putInt("periodChosenYear", calculatedPeriodYear);
        editor.commit();

        System.err.println("periodChosenDay preferences"
                + periodDatePreferences.getInt("periodChosenDay", 0));
        System.err.println("periodChosenMonth preferences"
                + periodDatePreferences.getInt("periodChosenMonth", 0));
        System.err.println("periodChosenYear preferences"
                + periodDatePreferences.getInt("periodChosenYear", 0));
        Toast.makeText(SettingsPeriodDate.this, "The date was saved",
                Toast.LENGTH_LONG).show();

        finish();
    }

    public void PopIt(String title, String message) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Error");
        builder.setMessage("Please check again");
        builder.setCancelable(true);

        final AlertDialog dlg = builder.create();

        dlg.show();

        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {
                dlg.dismiss();
                t.cancel();
            }
        }, 100000);
    }

and I get the result in activity 1 as bellow :

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        case 100:
            System.err.println("after intent back 111111=== ");

             if (resultCode == Activity.RESULT_OK) {
            System.err.println("after intent back if=== ");

            int day = data.getIntExtra("Day", 0);
            int month = data.getIntExtra("Month", 0);
            int year = data.getIntExtra("Year", 0);
            System.err.println("after intent back =///== " + day + "-" + month
                    + "-" + year);
            Toast.makeText(Settings.this,day+"?"+month+"?"+year,Toast.LENGTH_SHORT).show();
            periodDatetv.setText(day + "/" + month + "/" + year);
            break;

         }

        }
    }

But it never runs the onActivityResult method ! what is the wrong in my code ? please tell me .. and thanks in advance

Android Developer
  • 1,039
  • 1
  • 9
  • 33

4 Answers4

2

use setResult(RESULT_OK); before finish() method from second activity

from the second activity which you want should return some result to first activity

Abhinav Singh Maurya
  • 3,313
  • 8
  • 33
  • 51
  • 1
    is this you code to return from first activity to second activity? Intent saved2 = new Intent(SettingsPeriodDate.this, Settings.class); startActivityForResult(saved2, 100); – Abhinav Singh Maurya Jan 16 '13 at 08:40
  • 1
    just use setResult(RESULT_OK); and there after finish(); method your code will run as charm instead of that code – Abhinav Singh Maurya Jan 16 '13 at 08:41
  • setResult() return to the place where the intent was sent ? – Android Developer Jan 16 '13 at 08:49
  • 1
    yes actually when you do startActivityForResult(INTENT, REQUEST_CODE); from activity A it waits for the result to catch in onActivityResult method in A and in B when you work is over and you want to return back a result to A just use setResult(RESULT_OK); if you work is done properly else use setResult(CANCLED); if your work is not done in B. this indicates A that I am getting result from B or not and it will catch in onActivityResult method – Abhinav Singh Maurya Jan 16 '13 at 08:50
  • Ok but I want to use the data that was saved in shared prefernces in activity 2, I want to use them in activity 1 because of that I used on activity result, how can I use them now ? – Android Developer Jan 16 '13 at 08:54
  • Just put them into intent.putExtra(key, value)(String data, int data or anyting) and pass it as setResult(RESULT_OK, intent); and in activity A access that data from the Intent data parameter of onActivityResult method – Abhinav Singh Maurya Jan 16 '13 at 08:56
2

You commented out your setResult() call in activity 2.

In case you are starting your activity with startActivityForResult(), the activity you start (activity 2 in your case) needs to call setResult() each time it is about to be finished.

See this example:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blablabla)

    //we do this here to make sure result is set even if user leaves
    //activity, for example, by pressing back/home buttons
    //result we set here will be overridden by any latter calls if they occur
    setResult(RESULT_CANCELED);         

    //do some processing here
    Intent intent=new Intent();
    //now let's send the result back
    intent.putExtra(result);
    setResult(RESULT_OK, intent);
    finish();
}

private void another_method() {
    //do some processing here too
    Intent intent=new Intent();
    //sending the result back
    intent.putExtra(result);
    //need to call setResult() here too
    setResult(RESULT_OK, intent);
    finish();
}
Andrii Chernenko
  • 9,873
  • 7
  • 71
  • 89
  • I'm scanning the code and I still can't see setResult, even commented out! :) – Simon Jan 16 '13 at 08:22
  • at first it was commented out, and then after one of the edits it just disappeared :) – Andrii Chernenko Jan 16 '13 at 08:25
  • Ok but I want to use the data that was saved in shared prefernces in activity 2, I want to use them in activity 1 because of that I used on activity result, how can I use them now ? – Android Developer Jan 16 '13 at 08:55
  • @AndroidDeveloper put any data you want as extra to the intent you set as result, and then get it from extras in `onActivityResult()`, don't forget that you need to use the same key – Andrii Chernenko Jan 16 '13 at 09:01
1

The issue here is you start SettingsPeriodDate from Settings and then Settings from SettingsPeriodDate.

You should not be starting Settings again. Just setResult() and finish() when your work with SettingsPeriodDate is done

njzk2
  • 38,969
  • 7
  • 69
  • 107
  • Does setResult() activate onActivityResult() ? – Android Developer Jan 16 '13 at 08:45
  • that's not the issue. setResult is not mandatory, it will just give you data that you fetch using `data.getIntExtras` for instance. The important part is that you start Settings when you should not – njzk2 Jan 16 '13 at 09:01
0

before finish activity to call setResult(RESULT_OK). I can't find it in your code. Instead of setting result you are call the activity one again. So it will create new activity. Don't call new activity with activity 1 intent.

ilango j
  • 5,967
  • 2
  • 28
  • 25