Android DatePicker fails on android 2.3.3

2019-07-16 04:17发布

问题:

As I am new to Android development I am trying to display DatePicker dialog on Android 2.3.3 emulator,but while it is crashing. I am followed what am I missing to include in my code? But this code is working in Android 4.0. DatePickerFragment class

public class DatePickerFragment extends DialogFragment implements OnDateSetListener{

 @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }

}

The activity class that starts the DatePicker Dialog:

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;

import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


@SuppressLint({ "NewApi", "NewApi", "NewApi" })
public class FormAnalysis extends FragmentActivity{

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fanalysis);
    //getActionBar().setDisplayHomeAsUpEnabled(true);


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.fanalysis, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    //switch (item.getItemId()) {
      //  case android.R.id.home:
        //    NavUtils.navigateUpFromSameTask(this);
            return true;
    //}
    //return super.onOptionsItemSelected(item);
}

public void generate(View view){


}
  public void startDialog(View view){
  DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");} }

Update Here is the Stack Trace


[2012-11-16 00:31:55 - Food Security] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=kz.bimash.food.security/.Starter }
[2012-11-16 00:31:55 - Food Security] ActivityManager: Warning: Activity not started, its current task has been brought to the front

回答1:

Your DialogFragment import is for the incorrect version of the class. It needs to be android.support.v4.app.DialogFragment instead of android.app.DialogFragment, otherwise it will not work correctly on 2.3.