I'm using google sheets API with which I am creating new google sheets using sheets API, But this is using the account in which the sheet's API is enabled, If I give my app to another user he cannot create a new sheet using his Gmail. I have the API key, Is it possible to create sheets without selecting Gmail accounts
GoogleAccountCredential mCredential;
private static final String BUTTON_TEXT = "Call Google Sheets API";
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
private void getResultsFromApi() {
Log.d(TAG, "getResultsFromApi: ");
if (!isGooglePlayServicesAvailable()) {
Log.d(TAG, "getResultsFromApi: 1");
acquireGooglePlayServices();
} else if (mCredential.getSelectedAccountName() == null) {
Log.d(TAG, "getResultsFromApi: 2");
chooseAccount();
} else if (!isDeviceOnline()) {
Log.d(TAG, "getResultsFromApi: No network connection available.");
} else {
// x();
try {
new MakeRequestTask(mCredential).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
#AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void chooseAccount() {
if (EasyPermissions.hasPermissions(
this, Manifest.permission.GET_ACCOUNTS)) {
String accountName = getPreferences(Context.MODE_PRIVATE)
.getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
Log.d(TAG, "chooseAccount: 1");
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
} else {
Log.d(TAG, "chooseAccount: 2");
// Start a dialog from which the user can choose an account
startActivityForResult(
mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
} else {
// Request the GET_ACCOUNTS permission via a user dialog
EasyPermissions.requestPermissions(
this,
"This app needs to access your Google account (via Contacts).",
REQUEST_PERMISSION_GET_ACCOUNTS,
Manifest.permission.GET_ACCOUNTS);
}
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private com.google.api.services.sheets.v4.Sheets mService = null;
private Exception mLastError = null;
public MakeRequestTask(GoogleAccountCredential credential) throws IOException {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new com.google.api.services.sheets.v4.Sheets.Builder(
transport, jsonFactory, credential)
.setApplicationName("Google Sheets API Android Quickstart")
.build();
new Thread() {
#Override
public void run() {
try {
if (consurEtSurname.getText().toString().isEmpty()) {
consurEtSurname.setError("Please provide survey name!");
consurEtSurname.requestFocus();
} else {
Spreadsheet spreadsheet = new Spreadsheet()
.setProperties(new SpreadsheetProperties()
.setTitle(consurEtSurname.getText().toString()));
spreadsheet = mService.spreadsheets().create(spreadsheet)
.setFields("spreadsheetId")
.execute();
Makecolums(mService,spreadsheet.getSpreadsheetId());
upload(spreadsheet.getSpreadsheetId());
Log.d(TAG, "onCreate: " + spreadsheet.getSpreadsheetId());
Log.d(TAG, "run: " + spreadsheet.getSpreadsheetUrl());
}
// writeToSheetUsingApi(mService,spreadsheet.getSpreadsheetId());
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
// catch (GeneralSecurityException e) {
// e.printStackTrace();
// }
}
}.start();
}
//
// #Override
// protected List<String> doInBackground(Void... params) {
// try {
// return getDataFromApi();
// } catch (Exception e) {
// mLastError = e;
// cancel(true);
// return null;
// }
// }
//
//
// private List<String> getDataFromApi() throws IOException {
// String spreadsheetId = "196tcE1k5RuqTdGSBDpTFAI5h3m_dwXR875Q3csmi4ko";
// String range = "A1:X1";
//
// List<String> results = new ArrayList<String>();
// ValueRange response = this.mService.spreadsheets().values()
// .get(spreadsheetId, range)
// .execute();
//
// List<List<Object>> values = response.getValues();
// if (values != null) {
// for (int i = 0; i < values.size(); i++) {
// results.add(values.get(i).get(0) + ", " + values.get(i).get(1));
// }
// }
// return results;
// }
#Override
protected List<String> doInBackground(Void... voids) {
return null;
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
Log.d(TAG, "\"No results returned.\": ");
} else {
output.add(0, "Data retrieved using the Google Sheets API:");
Log.d(TAG, TextUtils.join("\n", output));
Log.d("TagOutputPost", TextUtils.join("\n", output));
}
}
#Override
protected void onCancelled() {
mProgress.hide();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
showGooglePlayServicesAvailabilityErrorDialog(
((GooglePlayServicesAvailabilityIOException) mLastError)
.getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) {
startActivityForResult(
((UserRecoverableAuthIOException) mLastError).getIntent(),
REQUEST_AUTHORIZATION);
} else {
Log.d(TAG, "The following error occurred:\n"
+ mLastError.getMessage());
}
} else {
Log.d(TAG, "Request onCancelled: ");
}
}
}
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
Log.d(TAG, "This app requires Google Play Services. Please install " +
"Google Play Services on your device and relaunch this app.");
} else {
getResultsFromApi();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.apply();
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
getResultsFromApi();
}
break;
}
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
return connectionStatusCode == ConnectionResult.SUCCESS;
}
private void acquireGooglePlayServices() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
}
}
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
Dialog dialog = apiAvailability.getErrorDialog(
ConfirmSurvey.this,
connectionStatusCode,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
#Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
#Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
}
Related
I have been trying to use this tutorial to create an app that can take pictures and videos with camera2 specifically as I need access to more technical aspects such as focus and exposure. As the title of this post states, I can get the code to save a video properly, but when I press the button to take a still image, it gives the following error message repeatedly:
Handler (android.os.Handler) {302c85a} sending message to a Handler on a dead thread
java.lang.IllegalStateException: Handler (android.os.Handler) {302c85a} sending message to a Handler on a dead thread
at android.os.MessageQueue.enqueueMessage(MessageQueue.java:560)
at android.os.Handler.enqueueMessage(Handler.java:778)
at android.os.Handler.sendMessageAtTime(Handler.java:727)
at android.os.Handler.sendMessageDelayed(Handler.java:697)
at android.os.Handler.post(Handler.java:427)
at android.hardware.camera2.impl.CameraDeviceImpl$CameraHandlerExecutor.execute(CameraDeviceImpl.java:2353)
at android.hardware.camera2.impl.CallbackProxies$SessionStateCallbackProxy.onCaptureQueueEmpty(CallbackProxies.java:94)
at android.hardware.camera2.impl.CameraCaptureSessionImpl$2.onRequestQueueEmpty(CameraCaptureSessionImpl.java:864)
at android.hardware.camera2.impl.CameraDeviceImpl$CameraDeviceCallbacks.onRequestQueueEmpty(CameraDeviceImpl.java:2331)
at android.hardware.camera2.ICameraDeviceCallbacks$Stub.onTransact(ICameraDeviceCallbacks.java:187)
at android.os.Binder.execTransactInternal(Binder.java:1285)
at android.os.Binder.execTransact(Binder.java:1244)
This may be related to this error that occurs when the startPreview method is called (see code at the bottom of post):
android.hardware.camera2.CameraAccessException: CAMERA_DISCONNECTED (2): checkPidStatus:2085: The camera device has been disconnected
at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:1390)
...
at com.[example].androidcamera2api.MainActivity$10.onConfigured(MainActivity.java:986)
The code, which I have modified slightly from the original github example to use non-deprecated API, is as follows. (I have also commented out lines related to getting audio. They kept causing app crashes, but they are unnecessary for my use case so it shouldn't matter. Also omitted imports for brevity.)
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Camera2VideoImageActivi";
private static final int REQUEST_CAMERA_PERMISSION_RESULT = 0;
private static final int REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_RESULT = 1;
private static final int STATE_PREVIEW = 0;
private static final int STATE_WAIT_LOCK = 1;
private int mCaptureState = STATE_PREVIEW;
private TextureView mTextureView;
private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
setupCamera(width, height);
connectCamera();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {}
};
private CameraDevice mCameraDevice;
private CameraDevice.StateCallback mCameraDeviceStateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
mCameraDevice = camera;
mMediaRecorder = new MediaRecorder();
if(mIsRecording){
try{
createVideoFileName();
} catch(IOException e){
e.printStackTrace();
}
startRecord();
mMediaRecorder.start();
runOnUiThread(new Runnable() {
#Override
public void run() {
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.setVisibility(View.VISIBLE);
mChronometer.start();
}
});
} else {
startPreview();
}
}
#Override
public void onDisconnected(CameraDevice camera) {
camera.close();
mCameraDevice = null;
}
#Override
public void onError(CameraDevice camera, int error) {
camera.close();
mCameraDevice = null;
}
};
private HandlerThread mBackgroundHandlerThread;
private Handler mBackgroundHandler;
private String mCameraId;
private Size mPreviewSize;
private Size mVideoSize;
private Size mImageSize;
private ImageReader mImageReader;
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
mBackgroundHandler.post(new ImageSaver(reader.acquireLatestImage()));
}
};
private class ImageSaver implements Runnable {
private final Image mImage;
public ImageSaver(Image image) {
mImage = image;
}
#Override
public void run() {
ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mImageFileName);
fileOutputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
mImage.close();
Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaStoreUpdateIntent.setData(Uri.fromFile(new File(mImageFileName)));
sendBroadcast(mediaStoreUpdateIntent);
if(fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
private MediaRecorder mMediaRecorder;
private Chronometer mChronometer;
private int mTotalRotation;
private CameraCaptureSession mPreviewCaptureSession;
private CameraCaptureSession.CaptureCallback mPreviewCaptureCallback = new CameraCaptureSession.CaptureCallback() {
private void process(CaptureResult captureResult) {
switch (mCaptureState) {
case STATE_PREVIEW:
break;
case STATE_WAIT_LOCK:
mCaptureState = STATE_PREVIEW;
Integer afState = captureResult.get(CaptureResult.CONTROL_AF_STATE);
if(afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED || afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) {
Toast.makeText(getApplicationContext(), "AF Locked!", Toast.LENGTH_SHORT).show();
startStillCaptureRequest();
}
break;
}
}
#Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
process(result);
}
};
private CameraCaptureSession mRecordCaptureSession;
private CameraCaptureSession.CaptureCallback mRecordCaptureCallback = new CameraCaptureSession.CaptureCallback() {
private void process(CaptureResult captureResult) {
switch (mCaptureState) {
case STATE_PREVIEW:
break;
case STATE_WAIT_LOCK:
mCaptureState = STATE_PREVIEW;
Integer afState = captureResult.get(CaptureResult.CONTROL_AF_STATE);
if(afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED || afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) {
Toast.makeText(getApplicationContext(), "AF Locked!", Toast.LENGTH_SHORT).show();
startStillCaptureRequest();
}
break;
}
}
#Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
process(result);
}
};
private CaptureRequest.Builder mCaptureRequestBuilder;
private ImageButton mRecordImageButton;
private ImageButton mStillImageButton;
private boolean mIsRecording = false;
private boolean mIsTimelapse = false;
private File mVideoFolder;
private String mVideoFileName;
private File mImageFolder;
private String mImageFileName;
private static SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 0);
ORIENTATIONS.append(Surface.ROTATION_90, 90);
ORIENTATIONS.append(Surface.ROTATION_180, 180);
ORIENTATIONS.append(Surface.ROTATION_270, 270);
}
private static class CompareSizeByArea implements Comparator<Size> {
#Override
public int compare(Size lhs, Size rhs) {
return Long.signum( (long)(lhs.getWidth() * lhs.getHeight()) -
(long)(rhs.getWidth() * rhs.getHeight()));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermissions(new String[]{"android.permission.CAMERA","android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_EXTERNAL_STORAGE"}, 1);
createVideoFolder();
createImageFolder();
mChronometer = (Chronometer) findViewById(R.id.chronometer);
mTextureView = (TextureView) findViewById(R.id.textureView);
mStillImageButton = (ImageButton) findViewById(R.id.cameraImageButton2);
mStillImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(mIsTimelapse || mIsRecording)) {
checkWriteStoragePermission();
}
lockFocus();
}
});
mRecordImageButton = (ImageButton) findViewById(R.id.videoOnlineImageButton);
mRecordImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mIsRecording || mIsTimelapse) {
mChronometer.stop();
mChronometer.setVisibility(View.INVISIBLE);
mIsRecording = false;
mIsTimelapse = false;
mRecordImageButton.setImageResource(R.mipmap.btn_video_online);
// Starting the preview prior to stopping recording which should hopefully
// resolve issues being seen in Samsung devices.
startPreview();
mMediaRecorder.stop();
mMediaRecorder.reset();
Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaStoreUpdateIntent.setData(Uri.fromFile(new File(mVideoFileName)));
sendBroadcast(mediaStoreUpdateIntent);
} else {
mIsRecording = true;
mRecordImageButton.setImageResource(R.mipmap.btn_video_busy);
checkWriteStoragePermission();
}
}
});
mRecordImageButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mIsTimelapse =true;
mRecordImageButton.setImageResource(R.mipmap.btn_timelapse);
checkWriteStoragePermission();
return true;
}
});
}
#Override
protected void onResume() {
super.onResume();
startBackgroundThread();
if(mTextureView.isAvailable()) {
setupCamera(mTextureView.getWidth(), mTextureView.getHeight());
connectCamera();
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_CAMERA_PERMISSION_RESULT) {
if(grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(),
"Application will not run without camera services", Toast.LENGTH_SHORT).show();
}
if(grantResults[1] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(),
"Application will not have audio on record", Toast.LENGTH_SHORT).show();
}
}
if(requestCode == REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_RESULT) {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(mIsRecording || mIsTimelapse) {
mIsRecording = true;
mRecordImageButton.setImageResource(R.mipmap.btn_video_busy);
}
Toast.makeText(this,
"Permission successfully granted!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,
"App needs to save video to run", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onPause() {
closeCamera();
stopBackgroundThread();
super.onPause();
}
#Override
public void onWindowFocusChanged(boolean hasFocas) {
super.onWindowFocusChanged(hasFocas);
View decorView = getWindow().getDecorView();
if(hasFocas) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}
private void setupCamera(int width, int height) {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
for(String cameraId : cameraManager.getCameraIdList()){
CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
if(cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) ==
CameraCharacteristics.LENS_FACING_FRONT){
continue;
}
StreamConfigurationMap map = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation();
mTotalRotation = sensorToDeviceRotation(cameraCharacteristics, deviceOrientation);
boolean swapRotation = mTotalRotation == 90 || mTotalRotation == 270;
int rotatedWidth = width;
int rotatedHeight = height;
if(swapRotation) {
rotatedWidth = height;
rotatedHeight = width;
}
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth, rotatedHeight);
mVideoSize = chooseOptimalSize(map.getOutputSizes(MediaRecorder.class), rotatedWidth, rotatedHeight);
mImageSize = chooseOptimalSize(map.getOutputSizes(ImageFormat.JPEG), rotatedWidth, rotatedHeight);
mImageReader = ImageReader.newInstance(mImageSize.getWidth(), mImageSize.getHeight(), ImageFormat.JPEG, 1);
mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
mCameraId = cameraId;
return;
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void connectCamera() {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) {
cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
} else {
if(shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA)) {
Toast.makeText(this,
"Video app required access to camera", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[] {android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO
}, REQUEST_CAMERA_PERMISSION_RESULT);
}
} else {
cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
System.out.println("Opened camera " + mCameraId);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void startRecord() {
try {
if(mIsRecording) {
setupMediaRecorder();
} else if(mIsTimelapse) {
setupTimelapse();
}
SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
Surface previewSurface = new Surface(surfaceTexture);
Surface recordSurface = mMediaRecorder.getSurface();
mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
mCaptureRequestBuilder.addTarget(previewSurface);
mCaptureRequestBuilder.addTarget(recordSurface);
mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, recordSurface, mImageReader.getSurface()),
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession session) {
mRecordCaptureSession = session;
try {
mRecordCaptureSession.setRepeatingRequest(
mCaptureRequestBuilder.build(), null, null
);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(CameraCaptureSession session) {
Log.d(TAG, "onConfigureFailed: startRecord");
}
}, null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void startPreview() {
SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
Surface previewSurface = new Surface(surfaceTexture);
try {
mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mCaptureRequestBuilder.addTarget(previewSurface);
mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()),
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession session) {
Log.d(TAG, "onConfigured: startPreview");
mPreviewCaptureSession = session;
try {
mPreviewCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(),
null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(CameraCaptureSession session) {
Log.d(TAG, "onConfigureFailed: startPreview");
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void startStillCaptureRequest() {
try {
if(mIsRecording) {
mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_VIDEO_SNAPSHOT);
} else {
mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
//mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_MANUAL);
Debug.logStack("Debug","Building still capture request",1);
}
mCaptureRequestBuilder.addTarget(mImageReader.getSurface());
mCaptureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, mTotalRotation);
CameraCaptureSession.CaptureCallback stillCaptureCallback = new
CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request, long timestamp, long frameNumber) {
super.onCaptureStarted(session, request, timestamp, frameNumber);
try {
createImageFileName();
} catch (IOException e) {
e.printStackTrace();
}
}
};
if(mIsRecording) {
mRecordCaptureSession.capture(mCaptureRequestBuilder.build(), stillCaptureCallback, null);
} else {
mPreviewCaptureSession.capture(mCaptureRequestBuilder.build(), stillCaptureCallback, null);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if(mCameraDevice != null) {
mCameraDevice.close();
mCameraDevice = null;
}
if(mMediaRecorder != null) {
mMediaRecorder.release();
mMediaRecorder = null;
}
}
private void startBackgroundThread() {
mBackgroundHandlerThread = new HandlerThread("Camera2VideoImage");
mBackgroundHandlerThread.start();
mBackgroundHandler = new Handler(mBackgroundHandlerThread.getLooper());
}
private void stopBackgroundThread() {
mBackgroundHandlerThread.quitSafely();
try {
mBackgroundHandlerThread.join();
mBackgroundHandlerThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static int sensorToDeviceRotation(CameraCharacteristics cameraCharacteristics, int deviceOrientation) {
int sensorOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
deviceOrientation = ORIENTATIONS.get(deviceOrientation);
return (sensorOrientation + deviceOrientation + 360) % 360;
}
private static Size chooseOptimalSize(Size[] choices, int width, int height) {
List<Size> bigEnough = new ArrayList<Size>();
for(Size option : choices) {
if(option.getHeight() == option.getWidth() * height / width &&
option.getWidth() >= width && option.getHeight() >= height) {
bigEnough.add(option);
}
}
if(bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizeByArea());
} else {
return choices[0];
}
}
private void createVideoFolder() {
File movieFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
mVideoFolder = new File(movieFile, "camera2VideoImage");
if(!mVideoFolder.exists()) {
mVideoFolder.mkdirs();
}
}
private File createVideoFileName() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "VIDEO_" + timestamp + "_";
File videoFile = File.createTempFile(prepend, ".mp4", mVideoFolder);
mVideoFileName = videoFile.getAbsolutePath();
return videoFile;
}
private void createImageFolder() {
File imageFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
mImageFolder = new File(imageFile, "camera2VideoImage");
if(!mImageFolder.exists()) {
mImageFolder.mkdirs();
}
}
private File createImageFileName() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "IMAGE_" + timestamp + "_";
File imageFile = File.createTempFile(prepend, ".jpg", mImageFolder);
mImageFileName = imageFile.getAbsolutePath();
return imageFile;
}
private void checkWriteStoragePermission() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
try {
createVideoFileName();
} catch (IOException e) {
e.printStackTrace();
}
if(mIsTimelapse || mIsRecording) {
startRecord();
mMediaRecorder.start();
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.setVisibility(View.VISIBLE);
mChronometer.start();
}
} else {
if(shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "app needs to be able to save videos", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION_RESULT);
}
} else {
try {
createVideoFileName();
} catch (IOException e) {
e.printStackTrace();
}
if(mIsRecording || mIsTimelapse) {
startRecord();
mMediaRecorder.start();
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.setVisibility(View.VISIBLE);
mChronometer.start();
}
}
}
private void setupMediaRecorder() throws IOException {
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
//mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setOutputFile(mVideoFileName);
mMediaRecorder.setVideoEncodingBitRate(1000000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
//mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mMediaRecorder.setOrientationHint(mTotalRotation);
mMediaRecorder.prepare();
}
private void setupTimelapse() throws IOException {
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH));
mMediaRecorder.setOutputFile(mVideoFileName);
mMediaRecorder.setCaptureRate(2);
mMediaRecorder.setOrientationHint(mTotalRotation);
mMediaRecorder.prepare();
}
private void lockFocus() {
mCaptureState = STATE_WAIT_LOCK;
mCaptureRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);
try {
if(mIsRecording) {
mRecordCaptureSession.capture(mCaptureRequestBuilder.build(), mRecordCaptureCallback, mBackgroundHandler);
} else {
mPreviewCaptureSession.capture(mCaptureRequestBuilder.build(), mPreviewCaptureCallback, mBackgroundHandler);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
I would be grateful if anyone could identify why I am having this error and help me to get the app to properly take pictures.
First, Thank you very much for looking at this!
I've been handed an app someone wrote before Marshmallow. I've fixed the Theme and SSL issues that came with Nougat but I'm having a heck of a time with Write to External Storage Permission or something associated. Debug is lacking or I'm not using it properly. This app creates a file onto the device and adds the ssl cert and login info in a folder called My Documents.
When I open the app it say network timeout right away. That message is from LoginActivity.java . I click ok then I get the Android pop up asking to allow permissions. I allow it. After that I put in the username and password and click login. It instantly gives the network timeout message from LoginActivity.java. LoginActivity.java is the Main Activity. If I click ok it's back to the login screen. All permissions are in the Android Manifest as well.
Maybe it's not from permissions but it works fine in version 22. I've worked on this 12 hours today and thought if you guys could help that'd be great. I'm a network engineer dabbling in Java so please excuse my question if it's "ugly".
I tried to find a line by line debug like I've done with phonegap but wasn't successful.
My Apps Main Activity LoginActivity.java and associated activity is LoginScreen.java and shown below.
LoginActivity.java
public class LoginActivity extends Activity {
private String userName = "";
private static final int PERMS_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blackactivity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
new SSLHandler().execute();
if(Variables.testing)
{
}
if (hasPermissions()){
// our app has permissions.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
//our app doesn't have permissions, So i m requesting permissions.
requestPerms();
}
}
//Begin Permission Methods
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
//End Permission Methods
private void attemptLogin() throws IOException {
String filepath = Variables.fileFolder + "/login.txt";
File tempFile = new File(filepath);
if (!tempFile.exists()) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
BufferedReader reader = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
} catch (Exception e) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
fileExists = true;
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean success = false;
Boolean timedOut = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
AlertDialog.Builder builder = new AlertDialog.Builder(
LoginActivity.this);
builder.setMessage("Network Timed Out").setTitle("Notice");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
if (result) {
Variables.storeTechName(userName, LoginActivity.this);
Variables.assignTechName();
startActivity(new Intent(LoginActivity.this,
MainActivity.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginActivity.this,
"Loading...", "Logging you in...");
mProgressDialog.getWindow().setGravity(Gravity.BOTTOM);
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
System.out.println(e.toString());
timedOut = true;
}
return success;
}
}
#Override
protected void onPause() {
super.onPause();
}
}
LoginScreen.java
public class LoginScreen extends Activity {
private String userName;
private static final int PERMS_REQUEST_CODE = 123;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (!SSLHandler.loaded) {
new SSLHandler().execute();
}
// Creates login and name files and attempts to log in
Button createButton = (Button) findViewById(R.id.createbutton);
createButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((EditText) findViewById(R.id.usernamefield)).getText()
.toString().isEmpty()
|| ((EditText) findViewById(R.id.passwordfield))
.getText().toString().isEmpty()) {
GUI.oneOptionDialog(LoginScreen.this,
"Missing field entries", "OK", false);
} else {
createLoginFile();
((EditText) findViewById(R.id.usernamefield)).setText("");
((EditText) findViewById(R.id.passwordfield)).setText("");
attemptLogin();
}
}
});
}
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
createFiles();
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
private void createFiles() {
}
private void attemptLogin() {
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
try {
String filepath = Variables.fileFolder + "/login.txt";
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
fileExists = true;
}
catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this,
"Login file does not exist. Please enter login info.",
"OK", false);
}
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean timedOut = false;
Boolean success = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
GUI.oneOptionDialog(LoginScreen.this, "Network Timed Out",
"OK", false);
} else {
if (result) {
Variables.storeTechName(userName, LoginScreen.this);
Variables.assignTechName();
startActivity(new Intent(LoginScreen.this,
MainActivity.class));
finish();
} else {
GUI.oneOptionDialog(LoginScreen.this,
"Login Failed. Please try again.", "OK", false);
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginScreen.this,
"Loading...", "Logging you in...");
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
jc.setConnectTimeout(Variables.timeoutTimeLimit);
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
timedOut = true;
}
return success;
}
}
private void createLoginFile() {
try {
File dir = new File(Variables.fileFolder);
if (!dir.isDirectory()) {
dir.mkdirs();
}
String filepath = Variables.fileFolder + "/Login.txt";
String username = ((EditText) findViewById(R.id.usernamefield))
.getText().toString();
String password = ((EditText) findViewById(R.id.passwordfield))
.getText().toString();
String salt = new RandomString(20).nextString();
String passwordHash = Variables.sha256(password + salt);
PrintWriter writer = new PrintWriter(filepath, "UTF-8");
writer.println(username);
writer.println(passwordHash);
writer.println(salt);
writer.close();
} catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this, e.toString(), "OK", false);
}
}
#Override
protected void onPause() {
super.onPause();
}
}
I am trying to create an app. I want to add search by address on google map in fragment Using the following code-
public class Search extends Fragment implements OnItemClickListener{
private final String TAG = this.getClass().getSimpleName();
MainActivity main=null;
PlacesTask placesTask = null ;
DownloadTask downloadTask=null;
LatLng latLng;
GoogleMap mMap;
Marker CurrentMarker,FindMarker;
AutoCompleteTextView autoCompView=null;
Button findbtn = null;
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
//------------ make your specific key ------------
private static final String API_KEY = "**************************************";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.search, container,false);
autoCompView = (AutoCompleteTextView) view.findViewById(R.id.editplace);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
autoCompView.setOnItemClickListener(this);
findbtn =(Button) view.findViewById(R.id.findbtn);
findbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = autoCompView.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
Log.e(TAG, "login button is clicked");
}
}
});
return view;
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getActivity());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0],3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address>addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getActivity(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker=mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
double mLatitude=address.getLatitude();
double mLongitude=address.getLongitude();
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + "liquor_store");
sb.append("&sensor=true");
sb.append("&key=********************************");
Log.d("Map", "<><>api: " + sb.toString());
//query places with find location
placesTask.execute(sb.toString());
//for direction Route
LatLng origin = CurrentMarker.getPosition();
LatLng dest = FindMarker.getPosition();
String url = getDirectionsUrl(origin, dest);
// Start downloading json data from Google Directions API
downloadTask.execute(url);
Toast.makeText(getActivity(), " Location found", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
return true;
}
return false;
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
getActivity().getActionBar().setTitle("IQWINER");
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position,
long id) {
// TODO Auto-generated method stub
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: "+url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
//Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
[enter error description here][2]
how to implement search by address location on Google Map in fragment.Please tell me..
enter error description here
You can do it in another way.
You can generate an api key along with Google maps & Google places api in your developers console (Click on the circled link and Enable the api)
You can call the api like below with your AutoCompleteView onclick listener or any other listener of your wish
private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;// declare this globally
//Call this on your listener method
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(getActivity());
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
This will open the Google place search screen and you can get the result like below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
mSearchPlace = place;
mSearchText.setText(String.valueOf(place.getName()));
// You will get Lat,Long values here where you can use it to move your map or reverse geo code it.
LatLng latLng = new LatLng(place.getLatLng().latitude, place.getLatLng().longitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
} else if (resultCode == getActivity().RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
Hope this helps.
Hi I am having a bit of trouble with the AsyncTask class for android. Here is my code for logging in a user on Parse. There are different cases such when the password is incorrect, etc.
My problem is that the error checking works and the different cases work fine but the progressDialog button will not go away after i close the alertdialog... Can anybody help me with this?
Here is my code
private class LoadTask extends AsyncTask<Map<String, String>, Integer, Void> {
// called before running code in a separate thread
private Result resultCode;
private boolean isSuccess;
private ProgressDialog progressDialog;
public LoadTask(Activity activity) {
onPreExecute();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TitlePage.this,
getString(R.string.login_progress_title),
getString(R.string.login_progress_message), false, false);
}
#Override
protected Void doInBackground(Map<String, String>... arg0) {
// Try to login with the given inputs
ParseUser user = null;
Map<String, String> argMap = arg0[0];
try {
user = ParseUser.logIn(argMap.get("username"), argMap.get("password"));
} catch (ParseException e) {
e.fillInStackTrace();
boolean errorOccured = false;
List<ParseObject> usernameResults = new ArrayList<ParseObject>();
List<ParseObject> passwordResults = new ArrayList<ParseObject>();
ParseQuery query = ParseUser.getQuery();
// try to find the username that the user typed in
query.whereEqualTo("username", argMap.get("username"));
try {
query.count();
usernameResults = query.find();
} catch (ParseException e1) {
// error occured trying to find the username
errorOccured = true;
e1.printStackTrace();
} catch (NullPointerException e1) {
errorOccured = true;
e1.printStackTrace();
}
// try to find the password that the user typed in
// associated with that username
query.whereEqualTo("username", argMap.get("username"));
query.whereEqualTo("password", argMap.get("password"));
try {
query.count();
passwordResults = query.find();
} catch (ParseException e1) {
// error occured trying to find the password
errorOccured = true;
e1.printStackTrace();
} catch (NullPointerException e1) {
errorOccured = true;
e1.printStackTrace();
}
// figure out the error
if (errorOccured) {
resultCode = Result.UNEXPECTED_ERROR;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
}
if ((usernameResults.size() == 0) && (passwordResults.size() == 0)) {
resultCode = Result.BOTH_INCORRECT;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_combo);
} else if ((usernameResults.size() == 0) && (passwordResults.size() != 0)) {
resultCode = Result.USERNAME_INCORRECT;
//buildAlertDialog(R.string.error_login_title, R.string.error_login_uname);
} else if ((usernameResults.size() != 0) && (passwordResults.size() == 0)) {
resultCode = Result.PASSWORD_INCORRECT;
//buildAlertDialog(R.string.error_login_title, R.string.error_login_pswd);
} else {
// unexpected error
resultCode = Result.UNEXPECTED_ERROR;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
}
isSuccess = false;
return null;
}
// Check for verified email
boolean emailVerified = user.getBoolean("emailVerified");
if (!emailVerified) {
resultCode = Result.EMAIL_NOT_VERIFIED;
ParseUser.logOut();
}
isSuccess = true;
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
if (isSuccess) {
TitlePage.this.setReturnStatus(isSuccess);
} else {
System.out.println("THIS IS RESULT CODE " + resultCode);
if (resultCode == Result.UNEXPECTED_ERROR) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
} else if (resultCode == Result.BOTH_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_combo);
} else if (resultCode == Result.USERNAME_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_uname);
} else if (resultCode == Result.PASSWORD_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_pswd);
} else {
buildAlertDialog(R.string.error_login_title, R.string.error_login_verif);
}
TitlePage.this.setReturnStatus(isSuccess);
}
}
}
And here is my code to run the async task in my main activity
Map<String, String> argMap = new HashMap<String, String>();
argMap.put("username", usernameString);
argMap.put("password", passwordString);
LoadTask task = new LoadTask(this);
task.execute(argMap);
private void buildAlertDialog(final int title, final int message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.close_alert, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
// if this button is clicked, close the dialog box
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show the message
alertDialog.show();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
Thank you
we can make progress dialog as same in the following example :
#Override
protected void onPreExecute() {
loadingDailog = new ProgressDialog(context,AlertDialog.THEME_HOLO_LIGHT);
((ProgressDialog) loadingDailog).setIndeterminate(true);
((ProgressDialog) loadingDailog).setProgressStyle(ProgressDialog.THEME_HOLO_LIGHT);
loadingDailog.setMessage("Loading...");
loadingDailog.show();
}
when you want to disapear this bar:
if (loadingDailog != null && loadingDailog.isShowing()) {
loadingDailog.dismiss();
}
I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult
public class MainActivity extends Activity {
Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}else{
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
}
This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.
Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.
private void initFacebook()
{
try
{
if (APP_ID == null)
{
Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
}
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
{
public void onComplete(Bundle values)
{
getHTTPConnection();
}
public void onFacebookError(FacebookError error)
{
Log.i("public void onFacebookError(FacebookError error)....","....");
}
public void onError(DialogError e)
{
Log.i("public void onError(DialogError e)....", "....");
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
dialog.show();
}
public void onCancel()
{
Log.i("public void onCancel()....", "....");
}
});
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.
private void getHTTPConnection()
{
try
{
mAccessToken = mFacebook.getAccessToken();
HttpClient httpclient = new DefaultHttpClient();
String result = null;
HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
parseJSON(result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now after successfully connecting with facebook , we are getting JSON data and further to parse it .
private void parseJSON(String data1) throws Exception,NullPointerException, JSONException
{
try
{
JSONObject jObj = new JSONObject(data1);
JSONArray jObjArr = jObj.optJSONArray("data");
int lon = jObjArr.length();
for (int i = 0; i < lon; i++)
{
JSONObject tmp = jObjArr.optJSONObject(i);
String temp_image = tmp.getString("picture"); String temp_fname = tmp.getString("first_name");
String temp_lname = tmp.getString("last_name");
String temp_loc = null;
JSONObject loc = tmp.getJSONObject("location");
temp_loc = loc.getString("name");
}
}
catch (Exception e)
{
Log.i("Exception1 is Here>> ", e.toString());
e.printStackTrace();
}
}
It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity