aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/ImageSelectActivity.java
blob: 9d1c1e0a5acfedc3a53a40311ac0505b636ccb73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package cgeo.geocaching;

import butterknife.ButterKnife;
import butterknife.InjectView;

import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.Log;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.Nullable;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class ImageSelectActivity extends AbstractActionBarActivity {

    @InjectView(R.id.caption) protected EditText captionView;
    @InjectView(R.id.description) protected EditText descriptionView;
    @InjectView(R.id.logImageScale) protected Spinner scaleView;
    @InjectView(R.id.camera) protected Button cameraButton;
    @InjectView(R.id.stored) protected Button storedButton;
    @InjectView(R.id.save) protected Button saveButton;
    @InjectView(R.id.cancel) protected Button clearButton;
    @InjectView(R.id.image_preview) protected ImageView imagePreview;

    private static final String SAVED_STATE_IMAGE_CAPTION = "cgeo.geocaching.saved_state_image_caption";
    private static final String SAVED_STATE_IMAGE_DESCRIPTION = "cgeo.geocaching.saved_state_image_description";
    private static final String SAVED_STATE_IMAGE_URI = "cgeo.geocaching.saved_state_image_uri";
    private static final String SAVED_STATE_IMAGE_SCALE = "cgeo.geocaching.saved_state_image_scale";

    private static final int SELECT_NEW_IMAGE = 1;
    private static final int SELECT_STORED_IMAGE = 2;

    // Data to be saved while reconfiguring
    private String imageCaption;
    private String imageDescription;
    private int scaleChoiceIndex;
    private Uri imageUri;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.imageselect_activity);
        ButterKnife.inject(this);

        scaleChoiceIndex = Settings.getLogImageScale();
        imageCaption = "";
        imageDescription = "";
        imageUri = Uri.EMPTY;

        // Get parameters from intent and basic cache information from database
        final Bundle extras = getIntent().getExtras();
        if (extras != null) {
            imageCaption = extras.getString(Intents.EXTRA_CAPTION);
            imageDescription = extras.getString(Intents.EXTRA_DESCRIPTION);
            imageUri = Uri.parse(extras.getString(Intents.EXTRA_URI_AS_STRING));
            scaleChoiceIndex = extras.getInt(Intents.EXTRA_SCALE, scaleChoiceIndex);
        }

        // Restore previous state
        if (savedInstanceState != null) {
            imageCaption = savedInstanceState.getString(SAVED_STATE_IMAGE_CAPTION);
            imageDescription = savedInstanceState.getString(SAVED_STATE_IMAGE_DESCRIPTION);
            imageUri = Uri.parse(savedInstanceState.getString(SAVED_STATE_IMAGE_URI));
            scaleChoiceIndex = savedInstanceState.getInt(SAVED_STATE_IMAGE_SCALE);
        }

        cameraButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View view) {
                selectImageFromCamera();
            }
        });

        storedButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View view) {
                selectImageFromStorage();
            }
        });

        if (StringUtils.isNotBlank(imageCaption)) {
            captionView.setText(imageCaption);
            Dialogs.moveCursorToEnd(captionView);
        }

        if (StringUtils.isNotBlank(imageDescription)) {
            descriptionView.setText(imageDescription);
            Dialogs.moveCursorToEnd(captionView);
        }

        scaleView.setSelection(scaleChoiceIndex);
        scaleView.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(final AdapterView<?> arg0, final View arg1, final int arg2, final long arg3) {
                scaleChoiceIndex = scaleView.getSelectedItemPosition();
                Settings.setLogImageScale(scaleChoiceIndex);
            }

            @Override
            public void onNothingSelected(final AdapterView<?> arg0) {
            }
        });

        saveButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View v) {
                saveImageInfo(true);
            }
        });

        clearButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View v) {
                saveImageInfo(false);
            }
        });

        loadImagePreview();
    }

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        syncEditTexts();
        outState.putString(SAVED_STATE_IMAGE_CAPTION, imageCaption);
        outState.putString(SAVED_STATE_IMAGE_DESCRIPTION, imageDescription);
        outState.putString(SAVED_STATE_IMAGE_URI, imageUri != null ? imageUri.getPath() : StringUtils.EMPTY);
        outState.putInt(SAVED_STATE_IMAGE_SCALE, scaleChoiceIndex);
    }

    public void saveImageInfo(final boolean saveInfo) {
        if (saveInfo) {
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(final Void... params) {
                    return writeScaledImage(imageUri.getPath());
                }

                @Override
                protected void onPostExecute(final String filename) {
                    if (filename != null) {
                        imageUri = Uri.parse(filename);
                        final Intent intent = new Intent();
                        syncEditTexts();
                        intent.putExtra(Intents.EXTRA_CAPTION, imageCaption);
                        intent.putExtra(Intents.EXTRA_DESCRIPTION, imageDescription);
                        intent.putExtra(Intents.EXTRA_URI_AS_STRING, imageUri.toString());
                        intent.putExtra(Intents.EXTRA_SCALE, scaleChoiceIndex);
                        setResult(RESULT_OK, intent);
                    } else {
                        showToast(res.getString(R.string.err_select_logimage_failed));
                        setResult(RESULT_CANCELED);
                    }
                    finish();
                }
            }.execute();
        } else {
            setResult(RESULT_CANCELED);
            finish();
        }
    }

    private void syncEditTexts() {
        imageCaption = captionView.getText().toString();
        imageDescription = descriptionView.getText().toString();
        scaleChoiceIndex = scaleView.getSelectedItemPosition();
    }

    private void selectImageFromCamera() {
        // create Intent to take a picture and return control to the calling application
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        imageUri = ImageUtils.getOutputImageFileUri(); // create a file to save the image
        if (imageUri == null) {
            showFailure();
            return;
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file name

        // start the image capture Intent
        startActivityForResult(intent, SELECT_NEW_IMAGE);
    }

    private void selectImageFromStorage() {
        final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/jpeg");

        startActivityForResult(Intent.createChooser(intent, "Select Image"), SELECT_STORED_IMAGE);
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
            showToast(getResources().getString(R.string.info_select_logimage_cancelled));
            return;
        }

        if (resultCode != RESULT_OK) {
            // Image capture failed, advise user
            showFailure();
            return;
        }

        // null is an acceptable result if the image has been placed in the imageUri file by the
        // camera application.
        if (data != null) {
            final Uri selectedImage = data.getData();
            if (Build.VERSION.SDK_INT < VERSION_CODES.KITKAT) {
                final String[] filePathColumn = { MediaColumns.DATA };

                Cursor cursor = null;
                try {
                    cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    if (cursor == null) {
                        showFailure();
                        return;
                    }
                    cursor.moveToFirst();

                    final int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    final String filePath = cursor.getString(columnIndex);
                    if (StringUtils.isBlank(filePath)) {
                        showFailure();
                        return;
                    }
                    imageUri = Uri.parse(filePath);
                } catch (final Exception e) {
                    Log.e("ImageSelectActivity.onActivityResult", e);
                    showFailure();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }

                Log.d("SELECT IMAGE data = " + data.toString());
            } else {
                InputStream input = null;
                OutputStream output = null;
                try {
                    input = getContentResolver().openInputStream(selectedImage);
                    final File outputFile = ImageUtils.getOutputImageFile();
                    output = new FileOutputStream(outputFile);
                    LocalStorage.copy(input, output);
                    imageUri = Uri.fromFile(outputFile);
                } catch (final FileNotFoundException e) {
                    Log.e("ImageSelectActivity.onStartResult", e);
                } finally {
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(output);
                }
            }
        }

        if (requestCode == SELECT_NEW_IMAGE) {
            showToast(getResources().getString(R.string.info_stored_image) + "\n" + imageUri);
        }

        loadImagePreview();
    }

    /**
     * Scales and writes the scaled image.
     *
     * @return the scaled image path, or <tt>null</tt> if the image cannot be decoded
     */
    @Nullable
    private String writeScaledImage(@Nullable final String filePath) {
        if (filePath == null) {
            return null;
        }
        scaleChoiceIndex = scaleView.getSelectedItemPosition();
        final int maxXY = getResources().getIntArray(R.array.log_image_scale_values)[scaleChoiceIndex];
        return ImageUtils.readScaleAndWriteImage(filePath, maxXY);
    }

    private void showFailure() {
        showToast(getResources().getString(R.string.err_acquire_image_failed));
    }

    private void loadImagePreview() {
        if (imageUri == null || imageUri.getPath() == null) {
            return;
        }
        if (!new File(imageUri.getPath()).exists()) {
            Log.i("Image does not exist");
            return;
        }

        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(final Void... params) {
                return ImageUtils.readAndScaleImageToFitDisplay(imageUri.getPath());
            }

            @Override
            protected void onPostExecute(final Bitmap bitmap) {
                imagePreview.setImageBitmap(bitmap);
                imagePreview.setVisibility(View.VISIBLE);
            }
        }.execute();
    }
}