Have error with android intent fragment to activity

huangapple go评论86阅读模式
英文:

Have error with android intent fragment to activity

问题

Sorry, but I can't assist with that request.

英文:

*Help me to find reason of my error.
I did onClick mButtonDate i have issue in my Manifest.
What files do I need to show you so you can understand my issue?
I tried to change manifest, turn off instantRun, rebuild project, googling problem. *

public class CrimeFragment extends Fragment {

    private static final String ARG_CRIME_ID = "crime_id";
    private static final String DATE_DIALOG = "DialogDate";
    private static final String TIME_DIALOG = "DialogTime";

    public static final String TIME_FORMAT = "hh:mm: a z";

    private static final int REQUEST_DATE = 0;
    private static final int REQUEST_TIME = 1;

    private Crime mCrime;
    private EditText mTitleField;
    private Button mButtonDate;
    private Button mButtonTime;
    private CheckBox mCheckSolvedBox;
    private Button firstButton;
    private Button lastButton;

    private boolean mIsLargeLayout;
    private Callbacks mCallbacks;

    public interface Callbacks {
        void onCrimeUpdate(Crime crime);
    }

    public static CrimeFragment newInstanse(UUID crimeId) {

        Bundle args = new Bundle();
        args.putSerializable(ARG_CRIME_ID, crimeId);

        CrimeFragment fragment = new CrimeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mCallbacks = (Callbacks) context;
    }

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

        mIsLargeLayout = getResources().getBoolean(R.bool.large_layout);

        UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
        mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_crime, container, false);

        firstButton = v.findViewById(R.id.firstButton);
        lastButton = v.findViewById(R.id.lastButton);

        mCheckSolvedBox = (CheckBox) v.findViewById(R.id.crime_solved);
        mCheckSolvedBox.setChecked(mCrime.isSolved());
        mCheckSolvedBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mCrime.setSolved(isChecked);
                updateCrime();
            }
        });

        mButtonTime = (Button) v.findViewById(R.id.crime_time);
        updateTime();
        mButtonTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIsLargeLayout) {
                    FragmentManager fragment = getFragmentManager();
                    TimePickerFragment dialog = TimePickerFragment.newInstance(mCrime.getTime());
                    dialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);
                    dialog.show(fragment, TIME_DIALOG);
                } else {
                    Intent intent = TimePickerActivity.newIntent(getContext(), mCrime.getTime());
                    startActivityForResult(intent, REQUEST_TIME);
                }
            }
        });

        mButtonDate = (Button) v.findViewById(R.id.crime_date);
        updateDate();
        mButtonDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIsLargeLayout) {
                    FragmentManager fragmentManager = getFragmentManager();
                    DatePickerFragment dialog = new DatePickerFragment().newInstance(mCrime.getDate());
                    dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
                    dialog.show(fragmentManager, DATE_DIALOG);
                } else {
                    Intent intent = DatePickerActivity.newIntent(getContext(), mCrime.getDate());
                    startActivityForResult(intent, REQUEST_DATE);
                }
            }
        });

        mTitleField = (EditText) v.findViewById(R.id.crime_title);
        mTitleField.setText(mCrime.getTitle());
        mTitleField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mCrime.setTitle(s.toString());
                updateCrime();

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        firstButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((CrimePagerActivity) getActivity()).goToFistPage();
            }
        });

        lastButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((CrimePagerActivity) getActivity()).goToLastPage();
            }
        });


        return v;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_DATE) {
            Date date = (Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
            mCrime.setDate(date);
            updateDate();
            updateCrime();
        }
        if (requestCode == REQUEST_TIME) {
            Date time = (Date) data.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
            mCrime.setTime(time);
            updateTime();
            updateCrime();
        }
    }

    private void updateCrime() {
        mCallbacks.onCrimeUpdate(mCrime);
    }

    private void updateDate() {
        mButtonDate.setText(mCrime.getDate().toString());
    }

    private void updateTime() {
        DateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
        mButtonTime.setText(timeFormat.format(mCrime.getTime()));

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }
}

Error in startActivityForResult(intent, REQUEST_DATE); :

    mButtonDate = (Button) v.findViewById(R.id.crime_date);
    updateDate();
    mButtonDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mIsLargeLayout) {
                FragmentManager fragmentManager = getFragmentManager();
                DatePickerFragment dialog = new DatePickerFragment().newInstance(mCrime.getDate());
                dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
                dialog.show(fragmentManager, DATE_DIALOG);
            } else {
                Intent intent = DatePickerActivity.newIntent(getContext(), mCrime.getDate());
                startActivityForResult(intent, REQUEST_DATE);
            }
        }
    });

Error:

    2020-10-21 23:03:59.853 18523-18523/com.example.criminalintent E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.criminalintent, PID: 18523
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.criminalintent/com.example.criminalintent.DatePickerFragment}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1932)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1615)
        at android.app.Activity.startActivityForResult(Activity.java:4472)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at androidx.core.app.ActivityCompat.startActivityForResult(ActivityCompat.java:234)
        at androidx.fragment.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:796)
        at androidx.fragment.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:933)
        at androidx.fragment.app.Fragment.startActivityForResult(Fragment.java:1206)
        at androidx.fragment.app.Fragment.startActivityForResult(Fragment.java:1194)
        at com.example.criminalintent.CrimeFragment$3.onClick(CrimeFragment.java:128)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

My Manifest:

    <?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.criminalintent">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".CrimeListActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".CrimePagerActivity">
        </activity>

    </application>
</manifest>

DatePickerFragment:

public class DatePickerFragment extends DialogFragment {

    private static final String ARG_DATE = "Date";

    public static final String EXTRA_DATE = "com.example.criminalintent.date";

    private DatePicker mDatePicker;
    private Button mDatePickerOkButton;

    public static DatePickerFragment newInstance(Date date) {
        Bundle args = new Bundle();
        args.putSerializable(ARG_DATE, date);

        DatePickerFragment fragment = new DatePickerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @NonNull
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Date date = (Date) getArguments().getSerializable(ARG_DATE);

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


        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        mDatePicker = (DatePicker) v.findViewById(R.id.dialog_date_picker);
        mDatePicker.init(year, month, day, null);

        mDatePickerOkButton = (Button) v.findViewById(R.id.dialog_date_ok_button);
        mDatePickerOkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int year = mDatePicker.getYear();
                int month = mDatePicker.getMonth();
                int day = mDatePicker.getDayOfMonth();
                Date date = new GregorianCalendar(year, month, day).getTime();
                sendResult(Activity.RESULT_OK, date);
            }
        });

        return v;

    }

    private void sendResult(int resultCode, Date date){
        Intent data = new Intent();
        data.putExtra(EXTRA_DATE, date);

        if (getTargetFragment() == null) {
            Activity hostingActivity = getActivity();
            hostingActivity.setResult(resultCode, data);
            hostingActivity.finish();
        } else {
 

           dismiss();
            getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, data);
        }
    }
}

DatePickerActivity:

public class DatePickerActivity extends SingleFragmentActivity {

private static final String EXTRA_CRIME_DATE = "com.example.criminalintent.crime_date";

public static Intent newIntent(Context packageContext, Date date) {
    Intent intent = new Intent(packageContext, DatePickerActivity.class);
    intent.putExtra(EXTRA_CRIME_DATE, date);
    return intent;
}

@Override
protected Fragment createFragment() {
    Date date = (Date) getIntent().getSerializableExtra(EXTRA_CRIME_DATE);
    return DatePickerFragment.newInstance(date);
}

}

CrimeListAcrivity

public class CrimeListActivity extends SingleFragmentActivity implements CrimeListFragment.Callbacks, CrimeFragment.Callbacks {


@Override
protected Fragment createFragment() {
    return new CrimeListFragment();
}

@Override
protected int getLayoutResId() {
    return R.layout.activity_masterdetail;
}

@Override
public void onCrimeSelected(Crime crime) {
    if (findViewById(R.id.detail_fragment_container) == null) {
        Intent intent = CrimePagerActivity.newIntent(this, crime.getId());
        startActivity(intent);
    } else {

        Fragment newDetail  = CrimeFragment.newInstanse(crime.getId());

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.detail_fragment_container, newDetail)
                .commit();
    }
}

@Override
public void onCrimeUpdate(Crime crime) {
    CrimeListFragment listFragment = (CrimeListFragment)getSupportFragmentManager()
            .findFragmentById(R.id.fragment_container);
    listFragment.updateUI();
}

}

CrimePagerActivity

public class CrimePagerActivity extends AppCompatActivity implements  CrimeFragment.Callbacks {

private ViewPager mViewPager;
private List<Crime> mCrimes;
private static final String EXTRA_CRIME_ID = "com.example.criminalintent.crime_id";


public static Intent newIntent(Context packageContext, UUID crimeId) {
    Intent intent = new Intent(packageContext, CrimePagerActivity.class);
    intent.putExtra(EXTRA_CRIME_ID, crimeId);
    return intent;
}

public void goToFistPage() {
    mViewPager.setCurrentItem(0);
}

public void goToLastPage() {
    mViewPager.setCurrentItem(mCrimes.size());
}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crime_pager);

    UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);

    mViewPager = (ViewPager) findViewById(R.id.crime_view_pager);

    mCrimes = CrimeLab.get(this).getCrimes();

    FragmentManager fragmentManager = getSupportFragmentManager();
    mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {

        @Override
        public Fragment getItem(int position) {

            Crime crime = mCrimes.get(position);
            return CrimeFragment.newInstanse(crime.getId());
        }

        @Override
        public int getCount() {
            return mCrimes.size();
        }
    });


    for (int i = 0; i < mCrimes.size(); i++) {
        if (mCrimes.get(i).getId().equals(crimeId)) {
            mViewPager.setCurrentItem(i);
            break;
        }
    }
}

@Override
public void onCrimeUpdate(Crime crime) {

}

@Override
public void onCrimeSelected(Crime crime) {

}

}

CrimeListFragment

public class CrimeListFragment extends Fragment {

private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;

private Callbacks mCallbacks;

/**
 * Required interface for hosting activities
 */

public interface Callbacks {
    void onCrimeSelected(Crime crime);
}


@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    mCallbacks = (Callbacks) context;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_crime_list, container, false);


    mCrimeRecyclerView = (RecyclerView) v.findViewById(R.id.crime_recycler_view);
    mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    updateUI();

    return v;
}


@Override
public void onResume() {
    super.onResume();
    updateUI();
}

public void updateUI() {

    CrimeLab crimeLab = CrimeLab.get(getActivity());
    List<Crime> crimes = crimeLab.getCrimes();

    if (mAdapter == null) {
        mAdapter = new CrimeAdapter(crimes);
        mCrimeRecyclerView.setAdapter(mAdapter);
    } else {
        for (int indexValue = 0; indexValue < crimes.size(); indexValue++) {
            mAdapter.notifyItemChanged(indexValue);
        }
    }
}


private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    private Crime mCrime;
    private TextView mTitleTextView;
    private TextView mDateTextView;
    private ImageView mSolvedImageView;


    public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.list_item_crime, parent, false));
        itemView.setOnClickListener(this);

        mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
        mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
        mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);


    }

    public void bind(Crime crime) {
        mCrime = crime;
        mTitleTextView.setText(mCrime.getTitle());
        mDateTextView.setText((String) DateFormat.format("EEEE, MMM dd, yyyy", mCrime.getDate()));
        mSolvedImageView.setVisibility(crime.isSolved() ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        mCallbacks.onCrimeSelected(mCrime);
    }
}

private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
    private List<Crime> mCrimes;


    public CrimeAdapter(List<Crime> crimes) {
        mCrimes = crimes;
    }

    @Override
    public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInFlater = LayoutInflater.from(getActivity());


        return new CrimeHolder(layoutInFlater, parent);
    }

    @Override
    public void onBindViewHolder(CrimeHolder holder, int position) {
        Crime crime = mCrimes.get(position);
        holder.bind(crime);


    }

    @Override
    public int getItemCount() {
        return mCrimes.size();
    }
}


@Override
public void onDetach() {
    super.onDetach();
    mCallbacks = null;
}

}

SingleFragmentActivity

public abstract class SingleFragmentActivity extends AppCompatActivity {

protected abstract Fragment createFragment();

@LayoutRes
protected  int getLayoutResId(){
    return  R.layout.activity_fragment;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutResId());

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);

    if (fragment == null) {
        fragment = createFragment();
        fm.beginTransaction()
                .add(R.id.fragment_container, fragment)
                .commit();
    }
}

}

答案1

得分: 1

mButtonDate.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        FragmentManager fragmentManager = getFragmentManager();
        if (mIsLargeLayout) {
            DatePickerFragment dialog = new DatePickerFragment().newInstance(mCrime.getDate());
            dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
            dialog.show(fragmentManager, DATE_DIALOG);
        } else {
            final Dialog dialog_date = new Dialog(getContext());
            dialog_date.setContentView(R.layout.dialog_date);
            final DatePicker dialog_date_picker = dialog_date.findViewById(R.id.dialog_date_picker);
            Button dialog_date_ok_button = dialog_date.findViewById(R.id.dialog_date_ok_button);
            dialog_date_ok_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog_date.dismiss();
                    Toast.makeText(getContext(), dialog_date_picker.getYear() + "", Toast.LENGTH_SHORT).show();
                }
            });
            dialog_date.show();
        }
    }
});
英文:
mButtonDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentManager fragmentManager = getFragmentManager();

            if (mIsLargeLayout) {
                DatePickerFragment dialog = new DatePickerFragment().newInstance(mCrime.getDate());
                dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
                dialog.show(fragmentManager, DATE_DIALOG);
            } else {
                final Dialog dialog_date = new Dialog(getContext());
                dialog_date.setContentView(R.layout.dialog_date);

                final DatePicker dialog_date_picker = dialog_date.findViewById(R.id.dialog_date_picker);
                Button dialog_date_ok_button = dialog_date.findViewById(R.id.dialog_date_ok_button);
                dialog_date_ok_button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog_date.dismiss();
                        Toast.makeText(getContext(), dialog_date_picker.getYear() + "", Toast.LENGTH_SHORT).show();
                    }
                });

                dialog_date.show();
            }
        }
    });

huangapple
  • 本文由 发表于 2020年10月22日 14:40:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64476629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定