应用程序从日期选择器对话框中选择日期并从库中选择图像时停止

时间:2015-10-05 13:02:08

标签: java android-activity android-image android-datepicker

我是Android新手,我需要一些帮助。我目前正在开发应用程序。从“日期选择器”对话框中选择日期后,应用程序已停止。 此外,图像视图无法替换为我通过相机捕获的图像,当我从图库中选择图像时,它会返回消息,"不幸的是,应用已停止。" 有人可以帮我解决吗?非常感谢。

Android Manifest

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".SplashScreen"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainItemList"
        android:label="@string/title_activity_main_item_list"></activity>
    <activity
        android:name=".SmartPantry"
        android:label="@string/title_activity_smart_pantry"></activity>
    <activity
        android:name=".Information"
        android:label="@string/title_activity_information"></activity>
    <activity
        android:name=".AddItem"
        android:label="@string/title_activity_add_item"></activity>
</application>

Additem.java

public class AddItem extends ActionBarActivity implements View.OnClickListener {
    private ImageView viewImage;
    private Button btnImg;
    private TextView txtPhoto, txtName, txtCategory,
        txtExpDate, txtNotification, txtRemark;
    private EditText editName, editDate, editRemark;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_item);
        Button btnImg = (Button) findViewById(R.id.btnImg);
        ImageView viewImage = (ImageView) findViewById(R.id.viewImage);
        EditText editName = (EditText) findViewById(R.id.etItemName);
        EditText editDate = (EditText) findViewById(R.id.etExpDate);
        EditText editRemark = (EditText) findViewById(R.id.etRemark);
        btnImg.setOnClickListener(this);
        editDate.setOnClickListener(this); 
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_add_item, menu);
        CreateMenu(menu);

        return true;
    }

    public void onClick(View v) {
        if (v.getId() == R.id.btnImg) {
            selectImage();
        }
        if (v.getId() == R.id.etExpDate) {
            setExpDate();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        //return super.onOptionsItemSelected(item);
        return MenuChoice(item);
    }

    private void CreateMenu(Menu menu) {
        MenuItem menu1 = menu.add(0, 0, 0, "Item 1");
        {
            menu1.setIcon(R.drawable.save);
            menu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
        MenuItem menu2 = menu.add(0, 1, 1, "Item 2");
        {
            menu2.setIcon(R.drawable.info);
            menu2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
    }

    public boolean MenuChoice(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                Toast.makeText(this, "Save this into your list", Toast.LENGTH_LONG).show();

                return true;

            case 1:
                Intent intent2 = new Intent(this, Information.class);
                startActivity(intent2);
                return true;
        }
        return false;
    }

    /**
     * *********************insert Image's detail******************************
     */

    private void selectImage() {
        final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};

        AlertDialog.Builder builder = new AlertDialog.Builder(AddItem.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);
                } else if (options[item].equals("Choose from Gallery")) {
                           Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                           startActivityForResult(intent, 2);
                       } else if (options[item].equals("Cancel")) {
                                  dialog.dismiss();
                              }
                   }
            });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);

                    viewImage.setImageBitmap(bitmap);

                    String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePath = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                //Log.w("path of image from gallery......******************.........", picturePath + "");
                viewImage.setImageBitmap(thumbnail);
            }
        }
    }


    /**
     * ************************ set expiry date ******************************
     */

    public void setExpDate() {

        //To show current date in the datepicker
        Calendar cld = Calendar.getInstance();
        int mYear = cld.get(Calendar.YEAR);
        int mMonth = cld.get(Calendar.MONTH);
        int mDay = cld.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog mDatePicker;
        mDatePicker = new DatePickerDialog(AddItem.this, new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker datepicker, int syear, int smonth, int sday) {
                editDate.setText("" + sday + "/" + (smonth + 1) + "/" + syear);
            }
        }, mYear, mMonth, mDay);
        mDatePicker.setTitle("Select Date");
        mDatePicker.show();

    }//);
}

activity_add_item.xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="2"
android:padding="10dp">

<!--Photo-->
<TableRow
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <TextView
        android:id="@+id/txtPhoto"
        android:layout_margin="10dp"
        android:layout_column="1"
        android:text="Photo"
        android:textSize="18sp"
        android:gravity="left"
        android:width="50dp" />

    <ImageView
        android:id="@+id/viewImage"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/camera"
        android:layout_height="100dp"
        android:layout_width="100dp"
        android:scaleType="fitXY"
        android:layout_gravity="left" />
</TableRow>

<TableRow
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button
        android:id="@+id/btnImg"
        android:text="Add Photo"
        android:layout_column="2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</TableRow>

<!--Name-->
<TableRow
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <TextView
        android:id="@+id/txtItemName"
        android:text="Name"
        android:layout_margin="10dp"
        android:layout_column="1"
        android:textSize="18sp"
        android:gravity="left" />

    <EditText
        android:id="@+id/etItemName"
        android:layout_column="2"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_span="2"
        android:hint="Name"
        android:inputType="textCapWords"

        />
</TableRow>

<!--Category-->
<TableRow
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <TextView
        android:id="@+id/txtCategory"
        android:text="Category"
        android:layout_margin="10dp"
        android:layout_column="1"
        android:textSize="18sp"
        android:gravity="left" />

    <EditText
        android:layout_column="2"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_span="2" />
</TableRow>

<!--Expiry Date-->
<TableRow
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <TextView
        android:id="@+id/txtExpDate"
        android:text="Expiry Date"
        android:layout_margin="10dp"
        android:layout_column="1"
        android:textSize="18sp"
        android:gravity="left" />

    <EditText
        android:id="@+id/etExpDate"
        android:layout_column="2"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_span="2" />
</TableRow>

<!--Notification-->
<TableRow
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <TextView
        android:id="@+id/txtNotification"
        android:text="Notification"
        android:layout_margin="10dp"
        android:layout_column="1"
        android:textSize="18sp"
        android:gravity="left" />

    <ToggleButton
        android:id="@+id/toggleNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_span="1" />
</TableRow>

<!--Remark-->
<TableRow
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <TextView
        android:id="@+id/txtRemark"
        android:text="Remark"
        android:layout_margin="10dp"
        android:layout_column="1"
        android:textSize="18sp"
        android:gravity="left" />

    <EditText
        android:id="@+id/etRemark"
        android:layout_column="2"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_span="2"
        android:hint="Remark"
        android:inputType="textMultiLine"/>
</TableRow>

0 个答案:

没有答案