简体   繁体   English

全局变量在 activityResult 方法外显示为空

[英]global variables show null outside activityResult method

I have two activities(one fragment and other activtiy) one to set alarm and the other to select tones.我有两个活动(一个片段和其他活动),一个用于设置闹钟,另一个用于选择音调。 I'm using startActivityForResult() method but.我正在使用startActivityForResult()方法但是。 in the main activity when I access the result it shows the expected result like this:在主要活动中,当我访问结果时,它显示了这样的预期结果:

@Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1){
            if (resultCode == RESULT_OK){
                songPath = data.getStringExtra("SongName");
                Log.d("Okay","song path :"+songPath);
            }
        }
    }


but when I access the same stored in a global "songPath" variable then it shows null.但是当我访问存储在全局“songPath”变量中的相同内容时,它显示为空。

Log.d("Okay",""+songPath);

here's the code.这是代码。

public class HomeFragment extends Fragment implements AlarmRecyclerViewListener,TimePickerDialog.OnTimeSetListener{

    private String songPath;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home,container,false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //Getting a writable reference of the Database.
        db = mAlarmsDBhelperClass.getWritableDatabase();

        //Retrieving values from the database and storing them in custom ArrayLists
        boolean isDataEmpty = getAlarm(db);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1){
            if (resultCode == RESULT_OK){
                songPath = data.getStringExtra("SongName");
                Log.d("Okay","song path :"+songPath);
            }
        }
    }
    public void startAlarm(Calendar c,int position,boolean isQuick,int requestCode){
        if (!isQuick) {
            //Getting a System service for the alarm to check the current time with the Alarm set time.
            AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
            //Creating an intent to invoke the onReceive method  in the custom receiver class, just to display notifications.
            Log.d("Okay",""+modeArrayList.get(position)+" "+songPath);
            Intent intent = new Intent(getContext(), AlarmReceiver.class);
            intent.putExtra("mode",modeArrayList.get(position));
            intent.putExtra("songPath",songPath);
            //A pending intent is used to execute some work in the future with our applications permissions.
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(),requestCodes.get(position),intent,0);
            //Now RTC_WAKEUP means if the device is Switched off turn it on.
            //getTimeInMillis() will get get the time in Milliseconds
            //Schedule an alarm to be delivered precisely at the stated time.In my case it's the calendar's getTimeMillis() method. which is providing the correct time in milliseconds.
            alarmManager.setExact(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
        } else {
            AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(getContext(), AlarmReceiver.class);
            Log.d("Okay",""+modeArrayList.get(position)+" "+songPath);
            intent.putExtra("mode","quick");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(),requestCode,intent,0);
            alarmManager.setExact(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
        }
    }
}
@Override
    public void onTimeSet(TimePicker timePicker, int hour, int minute) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        if (c.getTimeInMillis() < System.currentTimeMillis())
            c.add(Calendar.DAY_OF_YEAR, 1);
        Intent intent = new Intent(getContext(), RingtoneSelector.class);
        startActivityForResult(intent,FRAGMENT_HOME_REQUEST_CODE);
        mAlarmsDBhelperClass.insertAlarm("","⚡","",songPath,hour,minute,"ON",0,db);
        startAlarm(c,0,true,quickHour+quickMin+1);
        alarmAdapter.notifyDataSetChanged();
    }

I'm getting null in the log cat when I access the songPath variable in the startAlarm() and onTimeSet() 's Log.d() .当我访问startAlarm()onTimeSet()Log.d()的 songPath 变量时,我在日志猫中得到了空值。

startActivityForResult is not a blocking call. startActivityForResult 不是阻塞调用。

@Override
    public void onTimeSet(TimePicker timePicker, int hour, int minute) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        if (c.getTimeInMillis() < System.currentTimeMillis())
            c.add(Calendar.DAY_OF_YEAR, 1);
        Intent intent = new Intent(getContext(), RingtoneSelector.class);
        startActivityForResult(intent,FRAGMENT_HOME_REQUEST_CODE); // THIS LINE DOES NOT BLOCK
        mAlarmsDBhelperClass.insertAlarm("","⚡","",songPath,hour,minute,"ON",0,db);
        startAlarm(c,0,true,quickHour+quickMin+1);
        alarmAdapter.notifyDataSetChanged();
    }

These three lines:这三行:

mAlarmsDBhelperClass.insertAlarm("","⚡","",songPath,hour,minute,"ON",0,db);
startAlarm(c,0,true,quickHour+quickMin+1);
alarmAdapter.notifyDataSetChanged();

Will still be executed straight after startAtivityForResult .仍然会在startAtivityForResult之后直接执行。 Therefore songPath will be null.因此, songPath将为空。

You should call startAlarm etc inside of the onActivityResult method.您应该在onActivityResult方法内调用startAlarm等。

Is the value of your FRAGMENT_HOME_REQUEST_CODE = 1 .是你的FRAGMENT_HOME_REQUEST_CODE = 1的值。 In your onActivityResult method you check if (requestCode == 1) , which should properly be在您的onActivityResult方法中,您检查if (requestCode == 1) ,这应该正确

if (requestCode == FRAGMENT_HOME_REQUEST_CODE)

Be sure to use the same value you used for startActivityForResult method.请务必使用与用于startActivityForResult方法的值相同的值。 See if this was the issue.看看是不是这个问题。 Provided you are managing everything else correctly in the other activity.前提是您在其他活动中正确管理了其他所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM