Photo Upload to Google Drive via Android app+cannot exit app until i press home button - google-drive-api

Hi I want to develop an app that takes photo and uploads to Google Drive. I found the master(source code) from Github today which is by Google https://github.com/googledrive/android-quickstart
This is very useful. But I found some problems that If i Press back button the application still does not finish it's activity. By default it always opens camera and taking photo and saving it to the Google Drive.Its doing the same thing again and again.If I want to exit the app I cannot until I press Home button. Any solution? Also There is another problem: after taking photo it shows a dialog windows asking where to save the image and what will be the image name.The problem is if I press cancel button it shows the same dialog again and again. If I press Ok then it doesnot show the dialog but If I press cancel it shows the same dialog again. I want to get rid of it when I press cancel. Any solution? This is the code :
package com.randb.uploadtogdrive;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.ContentsResult;
import com.google.android.gms.drive.MetadataChangeSet;
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "android-drive-quickstart";
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
final Bitmap image = mBitmapToSave;
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
// If the operation was not successful, we cannot do anything
// and must
// fail.
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getContents().getOutputStream();
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle("myPhoto.png").build();
// Create an intent for the file chooser, and start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(result.getContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onBackPressed(){
Toast.makeText(MainActivity.this,"Going Somehwere?", Toast.LENGTH_LONG).show();
finish();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
}
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// // Just start the camera again for another photo.
// startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
// REQUEST_CODE_CAPTURE_IMAGE);
}
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
if (mBitmapToSave == null) {
// This activity has no UI of its own. Just start the camera.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
return;
}
saveFileToDrive();
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}

This should take care of you 'thumbnail' problem. Basically, replace the bitmap mBitmapToSave with a file '_picFl'. The code below is modified, the var names are different, but it does essentially what you're asking for.
private File _picFl;
private GoogleApiClient _gac;
#Override public void onConnected(Bundle connectionHint) {
if (_picFl == null)
takePic();
else
save2GooDrv();
}
//-----------------------------------------------------------------------------------------------
private void takePic() {
Intent icIt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (icIt.resolveActivity(getPackageManager()) != null) try {
_picFl = new File(getCcheDir(), tm2FlNm(null));
if (_picFl != null) {
icIt.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(_picFl));
startActivityForResult(icIt, RC_GETIMAGE);
}
} catch (Exception e) {le(e);}
}
//-----------------------------------------------------------------------------------------------
private synchronized void save2GooDrv() {
Drive.DriveApi.newContents(_gac).setResultCallback(new ResultCallback<ContentsResult>() {
#Override public void onResult(ContentsResult rslt) {
if (rslt.getStatus().isSuccess()) try {
OutputStream os = rslt.getContents().getOutputStream();
os.write(file2Bytes(_picFl));
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle(_picFl.getName()).build();
_picFl.delete();
_picFl = null;
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(rslt.getContents())
.build(_gac);
try {
startIntentSenderForResult( intentSender, RC_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {le(e);}
} catch (Exception e) {le(e);}
}
});
}
//***********************************************************************************************
public String getCcheDir() {
Context actx = getApplicationContext();
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!Environment.isExternalStorageRemovable() ?
actx.getExternalCacheDir().getPath() : actx.getCacheDir().getPath();
}
//***********************************************************************************************
public byte[] file2Bytes(File file) {
byte[] buf = null;
RandomAccessFile raFl = null;
if (file != null) try {
raFl = new RandomAccessFile(file, "r");
buf = new byte[(int)raFl.length()];
raFl.readFully(buf);
} catch (Exception e) {le(e);}
finally {
if (raFl != null) try {
raFl.close();
} catch (Exception e) {le(e);}
}
return buf;
}
//***********************************************************************************************
public String tm2FlNm(Long milis) { // time -> yymmdd-hhmmss
try {
return new SimpleDateFormat("yyMMdd-HHmmss",Locale.US)
.format((milis == null) ? new Date() : new Date(milis));
} catch (Exception e) {le(e);}
return null;
}
//***********************************************************************************************
public void le(Exception e){
try {
Log.e("_", (e==null) ? "NULL" : Log.getStackTraceString(e));
}catch (Exception f) { try { Log.e("_", "ERR on err");} catch (Exception g) {} }
}

Here is a quick fix for your problem. Back button from both the activities you're talking about (camera, creator) returns 'Activity.RESULT_CANCELED', so just kill your activity (using finish()) when you don't get 'Activity.RESULT_OK'.
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
} else
finish();
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// // Just start the camera again for another photo.
// startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
// REQUEST_CODE_CAPTURE_IMAGE);
} else
finish();
break;
}
But in general, 'quickstart' is usually just a proof-of-concept, not something you should build you app on.

Related

ViewPart hangs on click of JButton

I am working on Teamcenter RAC customization. I have changed an existing code which deals with viewpart and jbuttons on it. The viewpart(SWT) loads a stylesheet rendering panel. the problem is whenever I click on the save button (JButton) this hangs the teamcenter application on post -executing activities.
The code is as follows:
saveCheckOutButton.addActionListener( new ActionListener()
{
#Override
public void actionPerformed( ActionEvent paramAnonymousActionEvent )
{
final AbstractRendering sheetPanel = itemPanel.getStyleSheetPanel();
final AbstractRendering sheetPanel1 = itemRevPanel.getStyleSheetPanel();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground()
throws Exception
{
if(pPanel==null)
return null;
if( pPanel.isPanelSavable())
{
if(sheetPanel==null|| sheetPanel1==null)
return null;
sheetPanel.saveRendering();
sheetPanel1.saveRendering();
/*if(!sheetPanel.getErrorFlag() && !sheetPanel1.getErrorFlag())
{
sheetPanel.setModifiable( false );
sheetPanel1.setModifiable( false );
}*/
}
return null;
}
#Override
protected void done(){
if(!sheetPanel.getErrorFlag() && !sheetPanel1.getErrorFlag())
{
sheetPanel.setModifiable( false );
sheetPanel1.setModifiable( false );
}
}
};
worker.execute();
}
} );
I have written the code under swingworker as suggested by some of the experts here but to no success. Request for some immediate help.
What do you mean by "it hangs the teamcenter application". Whether it responds too slow or doInBackground() is not properly executed?
Anyway you can try executing your rendering code in SwingUtilities.invokeLater() and use the method get(). If you don't call get() in the done method, you will lose all the exceptions that the computation in the doInBackground() has thrown. So we will get to know about exception if any is there.
SwingUtilities.invokeLater() allows a task to be executed at some later point in time, as the name suggests; but more importantly, the task will be executed on the AWT event dispatch thread. Refer Invoke later API documentation for the detailed info.
About get():
Waits if necessary for the computation to complete, and then retrieves its result.
Note: calling get on the Event Dispatch Thread blocks all events, including repaints, from being processed until this SwingWorker is complete.
saveCheckOutButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent paramAnonymousActionEvent) {
final AbstractRendering sheetPanel = itemPanel.getStyleSheetPanel();
final AbstractRendering sheetPanel1 = itemRevPanel.getStyleSheetPanel();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
if (pPanel == null)
return null;
if (pPanel.isPanelSavable()) {
if (sheetPanel == null || sheetPanel1 == null)
return null;
saveRendering();
}
return null;
}
#Override
protected void done() {
try {
get();
if (!sheetPanel.getErrorFlag() && !sheetPanel1.getErrorFlag()) {
sheetPanel.setModifiable(false);
sheetPanel1.setModifiable(false);
}
} catch (final InterruptedException ex) {
throw new RuntimeException(ex);
} catch (final ExecutionException ex) {
throw new RuntimeException(ex.getCause());
}
}
};
worker.execute();
}
});
private void saveRendering() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
sheetPanel.saveRendering();
sheetPanel1.saveRendering();
}
});
}

JavaFX: Getting the Exception from another Class and setting it to a label

I have a controller that has a button to start a copy and a Label (lblError) to print error messages. To copy files, I call my CopyTask class. In case the file is existing, I'd like to set the lblError's text with an error message (from my CopyTask).
Here's my CopyTask class
public class CopyTask {
String error;
protected List<File> call() throws Exception {
File dir = new File("/Users/Ellen/EllenA/Tennis Videos");
File[] files = dir.listFiles();
int count = files.length;
List<File> copied = new ArrayList<File>();
int i = 0;
for (File file : files) {
if (file.isFile()) {
this.copy(file);
copied.add(file);
}
i++;
}
return copied;
}
private void copy(File file) throws Exception {
try{
Path from = Paths.get(file.toString());
System.out.println(file.toString());
Path to = Paths.get("/Users/Ellen/EllenA/TEMP COPY",file.getName());
CopyOption[] options = new CopyOption[]{
//StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(from, to, options);
} catch (FileAlreadyExistsException e){
System.err.println("FILE EXISTING");
this.error = "FILE EXISTING";
} catch (IOException e){
System.err.println(e);
this.error = e.toString();
}
}
public String getError(){
return error;
}
}
Extend Task<List<File>>. This class contains a message property you could bind to the label text.
public class CopyTask extends Task<List<File>> {
...
#Override
protected List<File> call() throws Exception {
...
}
private void copy(File file) throws Exception {
try {
...
} catch (FileAlreadyExistsException e){
System.err.println("FILE EXISTING");
// update message property from application thread
updateMessage("FILE EXISTING");
}
...
}
}
Calling code
Task<File> task = new CopyTask();
lblError.textProperty().bind(task);
new Thread(task).start();

GoogleMaps displaying "locals" on wrong position

i want to display the CurrentPosition of the mobile phone and display all bar|cafe nearby the position.
The CurrentPosition works.
But the displaying of the bars/cafes is wrong. It seems like they are showing up from the center of vienna and not from the position of my phone.
Would be really thankful if someone could find the problem
MapsActivity.java
package androfenix.currentpositionandplacesnearby;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
LatLng latLng;
double mLatitude=0;
double mLongitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Mit setMapType setzen wir das Aussehen der Karte auf "Hybrid"
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onPause()
{
super.onPause();
//Unregister for location callbacks:
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
// Create a LatLng object for the current location
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
StringBuilder sbValue = new StringBuilder(sbMethod());
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
public StringBuilder sbMethod() throws SecurityException
{
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=50000");
sb.append("&sensor=true");
sb.append("&keyword=" + "bar|cafe");
sb.append("&key= SERVER API KEY ");
Log.d("Map", "url: " + sb.toString());
return sb;
}
private class PlacesTask extends AsyncTask<String, Integer, String>
{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParserTask
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException
{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
Place_JSON placeJson = new Place_JSON();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJson.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
Log.d("Map", "list size: " + list.size());
// Clears all the existing markers;
//mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
Log.d("Map", "place: " + name);
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// Placing a marker on the touched position
Marker m = mMap.addMarker(markerOptions);
// ZZZZZZZZZZZZZZZZZZZ
}
}
}
public class Place_JSON {
/**
* Receives a JSONObject and returns a list
*/
public List<HashMap<String, String>> parse(JSONObject jObject) {
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for (int i = 0; i < placesCount; i++) {
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject) jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/**
* Parsing the Place JSON object
*/
private HashMap<String, String> getPlace(JSONObject jPlace)
{
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = jPlace.getString("reference");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
place.put("reference", reference);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
}
Using the Google Places API for Android, you can discover the place where the device is currently located. That is, the place at the device's currently-reported location. Examples of places include local businesses, points of interest, and geographic locations.
If your app uses PlaceDetectionApi.getCurrentPlace() must request the ACCESS_FINE_LOCATION permission.
The following code sample retrieves the list of places where the device is most likely to be located, and logs the name and likelihood for each place.
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
Log.i(TAG, String.format("Place '%s' has likelihood: %g",
placeLikelihood.getPlace().getName(),
placeLikelihood.getLikelihood()));
}
likelyPlaces.release();
}
});
The PlacePicker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place.
The following code snippet retrieves the place that the user has selected:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}

Android ListView Volley FATAL EXCEPTION error

I'm developing an Android App and i create a slide menu. In the slide menu i have item "Search". This is a fragment that call a json (using volley) and input the result into custom list view.
Now when i call the fragment (using debug mode) the fragment start to download some data but after some record of json download the app crash and i receive this error:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.firstproject.fragment.SearchFragment.loadListView(SearchFragment.java:175)
at com.firstproject.fragment.SearchFragment.access$000(SearchFragment.java:46)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:105)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:98)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
I attach my code where i call a json file (for privacy delete the url json)
Any help please?
Thanks
public class SearchFragment extends Fragment {
public SearchFragment(){}
private static final String url = "http://<server_name>/<folder>/data.json";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search, container, false);
}
ListView geoJSON;
String globalResponse="";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String tag_string_req = "string_req";
final ProgressDialog pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
RequestQueue mRequestQueue;
Network network = new BasicNetwork(new HurlStack());
//Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Instantiate the RequestQueue with the cache and network.
Cache cache = AppController.getInstance().getRequestQueue().getCache();
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
Cache.Entry entry = cache.get(url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
//loadListView(gobalResponse,0,1000);
//Toast.makeText(getActivity(), "Cache utilized!", 0).show();
// handle data, like converting it to xml, json, bitmap etc.,
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else{
// Cached response doesn't exists. Make network call here
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
globalResponse=response;
Globals.GlobalResponse=globalResponse;
Log.d("", response.toString());
loadListView(globalResponse,0,1000);
//loadListView(response,0,1000);
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(), error.getMessage()+"", 0).show();
pDialog.hide();
}
});
strReq.setShouldCache(true);
//strReq.
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
private ArrayList<GeoJsonResponse> globalResponseObject;//=new ArrayList<GeoJsonResposne>();
private void loadListView(String response,float lowerLimit,float upperLimit)
{
try {
JSONObject featureCollection=new JSONObject(response);
globalResponseObject=new ArrayList<GeoJsonResponse>();
JSONArray features=featureCollection.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject properties=features.getJSONObject(i);
float mag=Float.parseFloat(properties.getJSONObject("properties").getString("mag"));
if(!(mag>=lowerLimit&&mag<upperLimit)) continue;
Log.d("",properties.getJSONObject("properties").getString("author")
+ properties.getJSONObject("properties").getString("mag")
+ properties.getJSONObject("properties").getString("place")
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)
);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date1 = format.parse(properties.getJSONObject("properties").getString("time"));
GeoJsonResponse obj=new GeoJsonResponse(
properties.getJSONObject("properties").getString("eventId"),
properties.getJSONObject("properties").getString("author"),
properties.getJSONObject("properties").getString("place"),
Double.parseDouble(properties.getJSONObject("properties").getString("mag")),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)),
properties.getJSONObject("properties").getString("time"),date1,
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1))
);
globalResponseObject.add(obj);}
if(lowerLimit==0)
Globals.geoJsonResponse=globalResponseObject;
// Collections.sort(globalResponseObject, new DateSorter());
CustomListAdapter adpater=new CustomListAdapter(getActivity()
, globalResponseObject);
adpater.notifyDataSetChanged();
geoJSON.setAdapter(adpater);
geoJSON.invalidate();
geoJSON.invalidateViews();
//, author, place, magnitude, distance, date)
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Http Post with Blackberry 6.0 issue

I am trying to post some data to our webservice(written in c#) and get the response. The response is in JSON format.
I am using the Blackberry Code Sample which is BlockingSenderDestination Sample. When I request a page it returns with no problem. But when I send my data to our webservice it does not return anything.
The code part that I added is :
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
What am i doing wrong? And what is the alternatives or more efficients way to do Post with Blackberry.
Regards.
Here is my whole code:
class BlockingSenderSample extends MainScreen implements FieldChangeListener {
ButtonField _btnBlock = new ButtonField(Field.FIELD_HCENTER);
private static UiApplication _app = UiApplication.getUiApplication();
private String _result;
public BlockingSenderSample()
{
_btnBlock.setChangeListener(this);
_btnBlock.setLabel("Fetch page");
add(_btnBlock);
}
public void fieldChanged(Field button, int unused)
{
if(button == _btnBlock)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://192.168.1.250/mobileServiceOrjinal.aspx"; //our webservice address
//String uriStr = "http://www.blackberry.com";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("name", URI.create(uriStr));//name for context is name. is it true?
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("ender"),
URI.create(uriStr)
);
}
//Dialog.inform( "1" );
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
if(response != null)
{
BSDResponse(response);
}
}
catch(Exception e)
{
//Dialog.inform( "ex" );
// process the error
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
}
private void BSDResponse(Message msg)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result = new String(data);
}
}
_app.invokeLater(new Runnable() {
public void run() {
_app.pushScreen(new HTTPOutputScreen(_result));
}
});
}
}
..
class HTTPOutputScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public HTTPOutputScreen(String message)
{
_rtfOutput.setText("Retrieving data. Please wait...");
add(_rtfOutput);
showContents(message);
}
// After the data has been retrieved, display it
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
HttpMessage does not extend ByteMessage so when you do:
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
it throws a ClassCastException. Here's a rough outline of what I would do instead. Note that this is just example code, I'm ignoring exceptions and such.
//Note: the URL will need to be appended with appropriate connection settings
HttpConnection httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
OutputStream out = httpConn.openOutputStream();
out.write(<YOUR DATA HERE>);
out.flush();
out.close();
InputStream in = httpConn.openInputStream();
//Read in the input stream if you want to get the response from the server
if(httpConn.getResponseCode() != HttpConnection.OK)
{
//Do error handling here.
}