I want to create an application to get the user location info in coordinates using Locaion manager. The problem is my application always has stopped when it runs and always get java.lang.NullPointerException
this is my Main ACtivity
package com.ionlab.project.volley;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ionlab.project.volley.app.AppController;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements LocationListener {
//location
private TextView textView;
private LocationManager locationManager;
//waktu
TextView textviewDate;
Button buttonChoose;
FloatingActionButton buttonUpload;
Toolbar toolbar;
ImageView imageView;
EditText txt_name;
EditText txt_item;
Bitmap bitmap, decoded;
int success;
int PICK_IMAGE_REQUEST = 1;
int bitmap_size = 60; // range 1 - 100
private static final String TAG = MainActivity.class.getSimpleName();
/* 10.0.2.2 adalah IP Address localhost Emulator Android Studio. Ganti IP Address tersebut dengan
IP Address Laptop jika di RUN di HP/Genymotion. HP/Genymotion dan Laptop harus 1 jaringan! */
private String UPLOAD_URL = "http://192.168.1.4/android/upload_image/upload.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private String KEY_ITEM = "item";
private String KEY_LOKASI = "lokasi";
private String KEY_WAKTU = "waktu";
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (FloatingActionButton) findViewById(R.id.buttonUpload);
txt_name = (EditText) findViewById(R.id.editText);
txt_item = (EditText) findViewById(R.id.editItem);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
//Calendar
Calendar calendar = Calendar.getInstance();
String currenDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
textviewDate = findViewById(R.id.text_view_date);
textviewDate.setText(currenDate);
//textloc
textView = (TextView) findViewById(R.id.id_textview);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
//menampilkan progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
if (success == 1) {
Log.e("v Add", jObj.toString());
Toast.makeText(MainActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
kosong();
} else {
Toast.makeText(MainActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
//menghilangkan progress dialog
loading.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//menghilangkan progress dialog
loading.dismiss();
//menampilkan toast
Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, error.getMessage().toString());
}
}) {
#Override
protected Map<String, String> getParams() {
//membuat parameters
Map<String, String> params = new HashMap<String, String>();
//menambah parameter yang di kirim ke web servis
params.put(KEY_IMAGE, getStringImage(decoded));
params.put(KEY_NAME, txt_name.getText().toString().trim());
params.put(KEY_ITEM, txt_item.getText().toString().trim());
params.put(KEY_WAKTU, textviewDate.getText().toString().trim());
params.put(KEY_LOKASI, textView.getText().toString().trim());
//kembali ke parameters
Log.e(TAG, "" + params);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_json_obj);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//mengambil fambar dari Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// 512 adalah resolusi tertinggi setelah image di resize, bisa di ganti.
setToImageView(getResizedBitmap(bitmap, 512));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void kosong() {
imageView.setImageResource(0);
txt_name.setText(null);
txt_item.setText(null);
}
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//menampilkan gambar yang dipilih dari camera/gallery ke ImageView
imageView.setImageBitmap(decoded);
}
// fungsi resize image
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
#Override
public void onLocationChanged(Location location) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
textView.setText("Longitude:" + longitude + "\n" + "Latitude:" + latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
i also make sure that my android manifest is correct
I have Spent Day and Night trying to solve this problem, Browsed through numerous pages on the topic, Tried different codes of my own.
And it still happens. I am a beginner in Android. And please, please do help me. Is there no possible way to solve my problem?
this is my logcat
LogCat
Firstly, you should include your logcat in text form as a part of your question!
However, from what I can read from your screenshot the issue is in the onLocationChanged() method. Perform a check on "location" to see if it is null before trying to read it.
#Override
public void onLocationChanged(Location location) {
if(location != null){
double longitude = location.getLongitude();
double latitude = location.getLatitude();
textView.setText("Longitude:" + longitude + "\n" + "Latitude:" + latitude);
}
else{
Log.e(TAG, "onLocationChanged -- location is null!");
}
}
Note:
Just in case you didn't know the "TAG" is generally added to the beginning of most Android class like this:
public class MainActivity extends AppCompatActivity implements LocationListener {
private static final String TAG = MainActivity.class.getSimpleName();
Why MainActivity.class.getSimpleName() instead of just "MainActivity"? Because if you ever refactor your code, then the name will automatically be changed.
EDIT:
Have you added the necessary permissions in your manifest file?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>
Related
I'm follow the tutorial and implement the google place api to my file.
But I want to change it save to Firebase. Maybe save to a table "Location"
Anyone can guide me how to save it to firebase. The code I refer is from here:https://github.com/delaroy/AndroidLocationGeofencing
Thanks in advance and sorry for if there was lack of information Ii will added again.
Screenshot 1
Screenshot 2
package com.example.edward.neweventmanagementsystem;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.edward.neweventmanagementsystem.provider.PlaceContract;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
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.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import static android.widget.Toast.LENGTH_SHORT;
public class ManageLocation extends AppCompatActivity implements
ConnectionCallbacks,
OnConnectionFailedListener {
// Constants
public static final String TAG = ManageLocation.class.getSimpleName();
private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final int PLACE_PICKER_REQUEST = 1;
// Member variables
private PlaceListAdapter mAdapter;
private RecyclerView mRecyclerView;
private boolean mIsEnabled;
private GoogleApiClient mClient;
private Geofencing mGeofencing;
private DatabaseReference mDatabaseReference;
Context mContext;
PlaceBuffer mPlaces;
/**
* Called when the activity is starting
*
* #param savedInstanceState The Bundle that contains the data supplied in onSaveInstanceState
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_location);
// Set up the recycler view
mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PlaceListAdapter(this, null);
mRecyclerView.setAdapter(mAdapter);
// Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch);
// mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled), false);
// onOffSwitch.setChecked(mIsEnabled);
// onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// #Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
// editor.putBoolean(getString(R.string.setting_enabled), isChecked);
// mIsEnabled = isChecked;
// editor.commit();
// if (isChecked) mGeofencing.registerAllGeofences();
// else mGeofencing.unRegisterAllGeofences();
// }
//
// });
mClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, this)
.build();
mGeofencing = new Geofencing(this, mClient);
}
/***
* Called when the Google API Client is successfully connected
*
* #param connectionHint Bundle of data provided to clients by Google Play services
*/
#Override
public void onConnected(#Nullable Bundle connectionHint) {
refreshPlacesData();
Log.i(TAG, "API Client Connection Successful!");
}
/***
* Called when the Google API Client is suspended
*
* #param cause cause The reason for the disconnection. Defined by constants CAUSE_*.
*/
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "API Client Connection Suspended!");
}
/***
* Called when the Google API Client failed to connect to Google Play Services
*
* #param result A ConnectionResult that can be used for resolving the error
*/
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
Log.e(TAG, "API Client Connection Failed!");
}
public void refreshPlacesData() {
Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
Cursor data = getContentResolver().query(
uri,
null,
null,
null,
null);
if (data == null || data.getCount() == 0) return;
List<String> guids = new ArrayList<String>();
while (data.moveToNext()) {
guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID)));
}
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient,
guids.toArray(new String[guids.size()]));
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
mAdapter.swapPlaces(places);
mGeofencing.updateGeofencesList(places);
if (mIsEnabled) mGeofencing.registerAllGeofences();
}
});
}
public void onAddPlaceButtonClicked(View view) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_LONG).show();
return;
}
try {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Intent i = builder.build(this);
startActivityForResult(i, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
} catch (Exception e) {
Log.e(TAG, String.format("PlacePicker Exception: %s", e.getMessage()));
}
}
/***
* Called when the Place Picker Activity returns back with a selected place (or after canceling)
*
* #param requestCode The request code passed when calling startActivityForResult
* #param resultCode The result code specified by the second activity
* #param data The Intent that carries the result data.
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
if (place == null) {
Log.i(TAG, "No place selected");
return;
}
final String placeID = place.getId();
// Insert a new place into DB
// ContentValues contentValues = new ContentValues();
// contentValues.put(PlaceContract.PlaceEntry.COLUMN_PLACE_ID, placeID);
// getContentResolver().insert(PlaceContract.PlaceEntry.CONTENT_URI, contentValues);
//Place the data into Firebase
// Get live data information
refreshPlacesData();
}
}
public void onRingerPermissionsClicked(View view) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
public void onLocationPermissionClicked(View view) {
ActivityCompat.requestPermissions(ManageLocation.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
if (place == null) {
Log.i(TAG, "No place selected");
return;
}
final String placeID = place.getId();
//Place the data into Firebase
insertPlcaeIdinDb(placeID);
// Get live data information
refreshPlacesData();
}
}
private void insertPlcaeIdinDb(String placeID)
{
mDatabase.child("yourBranchNameinDb").setValue(placeID );
}
To understand what is
FirebaseDatabase.getInstance().getReference()
you can follow Firebase for android official documentation from there
I have tried 3 diffrent methods for sending a image from my Android to PHP.
All three gives the message "Missing inp_image name". I am thinking that I maybe am not sending the image as an image, but rather as some text ?
I am using this http request class in Android: https://github.com/kevinsawicki/http-request
Method 1 with encoding it to base64:
//String selectedFilePath = FilePath.getPath(context, imageUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bm = BitmapFactory.decodeFile(destImage,options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byteImage_photo = baos.toByteArray(); // bitmap object
//generate base64 string of image
String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
// Send image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", encodedImage);
stringResponse = request.body();
Method 2 - sending a input stream of image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", in); // sending input stream
stringResponse = request.body();
Method 3 - sending file:
String sourceFilename= FilePath.getPath(context, imageUri);
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", new File(sourceFilename)); // sending input stream
stringResponse = request.body();
Android Mainifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity:
package com.nettport.imageupload.imageupload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Check permission */
checkPermissionRead();
checkPermissionWrite();
/* Button listener */
buttonListener();
} // onCreate
private void checkPermissionRead(){
int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
private void checkPermissionWrite(){
int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
public void buttonListener() {
// Image button listener
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadImage);
buttonLoadImage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
// Load gallery
// User can select images and upload them
// Result will be in onActivityResult
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
});
// Camera
Button buttonLoadCamera = (Button) findViewById(R.id.buttonLoadCamera);
buttonLoadCamera.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
// Load camera
// Result will be in onActivityResult
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code
}
});
} // buttonListener
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Set image
ImageView imageViewImage = (ImageView)findViewById(R.id.imageViewImage);
imageViewImage.setImageURI(selectedImageUri);
// Save image
String destinationFilename = savefile(selectedImageUri);
try {
InputStream in = getContentResolver().openInputStream(selectedImageUri);
TextView textViewDynamicText = (TextView) findViewById(R.id.textViewDynamicText); // Dynamic text
String apiURL = "https://xxxxxx.com/xxxxxx/image_upload.php";
UploadImage task = new UploadImage(this, apiURL, in, selectedImageUri, destinationFilename, textViewDynamicText, new UploadImage.TaskListener() {
#Override
public void onFinished(String result) {
// Do Something after the task has finished
imageUploadResult();
}
});
task.execute();
//in.close();
}
catch (java.io.FileNotFoundException e) {
Toast.makeText(this, "MainAcrivity java.io.FileNotFoundException: " + e.toString(), Toast.LENGTH_LONG).show();
}
catch (java.io.IOException e) {
Toast.makeText(this, "MainAcrivity java.io.IOException: " + e.toString(), Toast.LENGTH_LONG).show();
}
} // RESULT_OK
} // onActivityResult
public void imageUploadResult(){
// Dynamic text
TextView textViewDynamicText = (TextView)findViewById(R.id.textViewDynamicText);
Toast.makeText(this, textViewDynamicText.getText().toString(), Toast.LENGTH_SHORT).show();
} // imageUploadResult
public String savefile(Uri sourceuri) {
String sourceFilename= FilePath.getPath(this, sourceuri);
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Upload";
String destinationFilename = destinationPath+"/upload_me.png";
// Make dir
File folder = new File(destinationPath);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
} else {
Toast.makeText(this, "Dir failed", Toast.LENGTH_LONG).show();
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
// Toast.makeText(this, "Saved to " + destinationFilename, Toast.LENGTH_LONG).show();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "savefile#1: " + e.toString() + "\nFrom: " + sourceFilename, Toast.LENGTH_LONG).show();
}
finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "savefile#2: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
return destinationFilename;
}
}
UploadImage class:
package com.nettport.imageupload.imageupload;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by bruker on 08.08.2017.
* Updated
*/
public class UploadImage extends AsyncTask<String, Void, String> {
/* Class variables */
private Context context; // Holder (this)
private String apiUrl; // URL for image upload form, example http://website.com/image_upload.php
private TextView dynamicText;
private InputStream in;
private Uri imageUri;
private String destImage;
private final UploadImage.TaskListener taskListener; // This is the reference to the associated listener
public interface TaskListener {
public void onFinished(String result);
}
/*- Constructor GET, SEND --------------------------------------------------------------- */
public UploadImage(Context ctx, String applicationPIUrl, InputStream input, Uri selectedImageUri, String destinationFilename, TextView textViewDynamicText, UploadImage.TaskListener listener) {
context = ctx;
apiUrl = applicationPIUrl;
in = input;
imageUri = selectedImageUri;
destImage = destinationFilename;
dynamicText = textViewDynamicText;
this.taskListener = listener; // The listener reference is passed in through the constructor
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dynamicText.setText(dynamicText.getText().toString() + "\n" + "Loading...");
}
#Override
protected String doInBackground(String... params) {
// Run methods
String stringResponse ="";
try {
try{
// Method 1 - Base 64
/*
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bm = BitmapFactory.decodeFile(destImage,options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byteImage_photo = baos.toByteArray(); // bitmap object
//generate base64 string of image
String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
// Send image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", encodedImage);
stringResponse = request.body();
*/
// Method 2 - Input stream
/*
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", in); // sending input stream
stringResponse = request.body();
*/
// Method 3 - File
String sourceFilename= FilePath.getPath(context, imageUri);
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", new File(sourceFilename)); // sending input stream
stringResponse = request.body();
}
catch (Exception e){
return e.toString();
}
}
catch(Exception e){
return e.toString();
}
return stringResponse;
}
#Override
protected void onPostExecute(String result) {
// Set text view with result string
if(dynamicText == null){
Toast.makeText(context, "NULL", Toast.LENGTH_SHORT).show();
}
else {
dynamicText.setText(dynamicText.getText().toString() + "\n" + result);
}
// In onPostExecute we check if the listener is valid
if(this.taskListener != null) {
// And if it is we call the callback function on it.
this.taskListener.onFinished(result);
}
}
#Override
protected void onProgressUpdate(Void... values) {}
}
PHP Script:
<?php
/**
*
* File: image_upload.php
* Date 13:05 04.08.2017
* Version 1
* Copyright (c) 2017 S. A. Ditlefsen
* License: http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/*- Get extention ---------------------------------------------------------------------- */
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
/*- Path -------------------------------------------------------------------------------- */
if(!(is_dir("_images"))){
mkdir("_images");
}
/*- Script start ------------------------------------------------------------------------ */
$name = stripslashes($_FILES['inp_image']['name']);
if($name){
$extension = getExtension($name);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
echo"unknown_file_extension";
}
else{
$date_time = date("Y-m-d_h-i-s");
$new_name = $date_time . ".png";
$new_path = "_images/";
$uploaded_file = $new_path . $new_name;
// Upload file
if (move_uploaded_file($_FILES['inp_image']['tmp_name'], $uploaded_file)) {
// Get image size
$file_size = filesize($uploaded_file);
// Check with and height
list($width,$height) = getimagesize($uploaded_file);
if($width == "" OR $height == ""){
echo"getimagesize_failed";
}
else{
// Resize to $settings_image_width
$newwidth=1000;
$newheight=($height/$width)*$newwidth; // 667
$tmp=imagecreatetruecolor($newwidth,$newheight);
if($extension=="jpg" || $extension=="jpeg" ){
$src = imagecreatefromjpeg($uploaded_file);
}
else if($extension=="png"){
$src = imagecreatefrompng($uploaded_file);
}
else{
$src = imagecreatefromgif($uploaded_file);
}
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight, $width,$height);
imagepng($tmp,$uploaded_file);
imagedestroy($tmp);
echo"$new_name";
} // width height
} // move_uploaded_file
else{
switch ($_FILES['inp_food_image_b']['error']) {
case UPLOAD_ERR_OK:
echo"image_to_big";
break;
case UPLOAD_ERR_NO_FILE:
echo"no_file_uploaded";
break;
case UPLOAD_ERR_INI_SIZE:
echo"to_big_size_in_configuration";
break;
case UPLOAD_ERR_FORM_SIZE:
echo"to_big_size_in_form";
break;
default:
echo"unknown_error";
break;
}
}
} // extention
} // name
else{
echo"Missing inp_image name";
}
?>
try this and it is working for me ,
String imgstring = getStringImage(bitmap)
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
volley
public void addimage() {
String link = CommonVariables.SERVER_IP + "/uploadimage.php";
StringRequest request = new StringRequest(Request.Method.POST, link, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError != null && volleyError.getMessage() != null) {
Toast.makeText(getContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("imagename", "yourimagename");
params.put("imagecode", imageString);
return params;
}
};
RetryPolicy mRetryPolicy = new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(mRetryPolicy);
queue.add(request);
}
php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$imgcode = $_POST['imagecode'];
$imagename = $_POST['imagename'];
require_once('dbconnect.php');
// this is ths path where your image is stored in the file in server
$path = "images/$imagename.jpg";
$sql = "INSERT INTO productlist(proimagename)
VALUES ('$imagename')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($imgcode));
echo "1";
}
mysqli_close($con);
}else{
echo "0";
}
UPDATE - edited code to display my broadcast idea. Using the method causes a !!! FAILED BINDER TRANSACTION !!! and no location data to be displayed by toast.
I was wondering if there was an elegant way to separate google fused location services away from activities. My warning class currently implements location services but I have another activity that takes photos. When a photo is taken I want to associate a location with the image. My current idea is to just use my broadcast receiver in my Bluetooth warning class to listen for a broadcast my camera will send and associate it then with a location. I'm not a fan of the idea because it doesn't separate functionality very well so was hoping for some suggestions or patterns. Code for classes below.
CAMERA CLASS
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraOperations extends AppCompatActivity {
public final static String ACTION_PICTURE_RECEIVED = "ACTION_PICTURE_RECEIVED";
public final static String TRANSFER_DATA = "bitmap";
ImageView mImageView;
String photoPath;
int REQUEST_IMAGE_CAPTURE = 1;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_view);
mImageView = (ImageView) findViewById(R.id.imageView);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(CameraOperations.this, "No Camera", Toast.LENGTH_SHORT).show();
} else {
dispatchTakePictureIntent();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
if(data == null){
Toast.makeText(this, "Data is null", Toast.LENGTH_SHORT);
Bitmap pictureMap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
mImageView.setImageBitmap(pictureMap);
broadcastUpdate(ACTION_PICTURE_RECEIVED, pictureMap);
}else {
Toast.makeText(this, "Error Occurred", Toast.LENGTH_SHORT).show();
}
}
}
private void broadcastUpdate(final String action, Bitmap picture) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
Intent intent = new Intent(action);
intent.putExtra(TRANSFER_DATA, bytes);
sendBroadcast(intent);
intent = new Intent(CameraOperations.this, Warning.class);
startActivity(intent);
finish();
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
photoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try{
photoFile = createImageFile();
}catch(IOException e){
e.printStackTrace();
}
if(photoFile != null){
Uri photoUri = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
BLUETOOTH WARNING CLASS
import android.Manifest;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class Warning extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final static String TAG = Warning.class.getSimpleName();
private String mDeviceAddress;
private HandleConnectionService mBluetoothLeService;
private boolean quitService;
private final int PLAY_SERVICES_REQUEST_TIME = 1000;
private Location mLastLocation;
private GoogleApiClient mGoogleClient;
private boolean requestingLocationUpdates = false;
private LocationRequest locationRequest;
private int UPDATE_INTERVAL = 10000; // 10 seconds
private int FASTEST_INTERVAL = 5000; // 5 seconds
private int DISTANCEMOVED = 10; //In meters
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((HandleConnectionService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
mBluetoothLeService.connect(mDeviceAddress);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (HandleConnectionService.ACTION_GATT_DISCONNECTED.equals(action)) {
if (!quitService) {
mBluetoothLeService.connect(mDeviceAddress);
Log.w(TAG, "Attempting to reconnect");
}
Log.w(TAG, "Disconnected, activity closing");
} else if (HandleConnectionService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
getGattService(mBluetoothLeService.getSupportedGattService());
} else if (HandleConnectionService.ACTION_DATA_AVAILABLE.equals(action)) {
checkWarning(intent.getByteArrayExtra(HandleConnectionService.EXTRA_DATA));
}else if(CameraOperations.ACTION_PICTURE_RECEIVED.equals(action)){
byte[] bytes = intent.getByteArrayExtra("bitmap");
Bitmap picture = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
findLocation();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
if (checkGoogleServices()) {
buildGoogleApiClient();
}
quitService = false;
Intent intent = getIntent();
mDeviceAddress = intent.getStringExtra(Device.EXTRA_DEVICE_ADDRESS);
Intent gattServiceIntent = new Intent(this, HandleConnectionService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
MenuItem connect = menu.findItem(R.id.connect);
connect.setVisible(false);
MenuItem disconnect = menu.findItem(R.id.disconnect);
disconnect.setVisible(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.home:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Return Home")
.setMessage("Returning home will disconnect you, continue?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
quitService = true;
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
Intent intent = new Intent(Warning.this, Main.class);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
case R.id.connect:
Toast.makeText(this, "Connect Pressed", Toast.LENGTH_SHORT).show();
return true;
case R.id.disconnect:
disconnectOperation();
intent = new Intent(Warning.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.profiles:
Toast.makeText(this, "Profiles Pressed", Toast.LENGTH_SHORT).show();
return true;
case R.id.camera:
Toast.makeText(this, "Camera Pressed", Toast.LENGTH_SHORT).show();
intent = new Intent(Warning.this, CameraOperations.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
quitService = true;
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
Intent intent = new Intent(Warning.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onDestroy() {
super.onDestroy();
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
System.exit(0);
}
public boolean disconnectOperation(){
this.quitService = true;
mBluetoothLeService.disconnect();
mBluetoothLeService.close();
return true;
}
private void checkWarning(byte[] byteArray) {
if (byteArray != null) {
for (int i = 0; i < byteArray.length; i++) {
if (byteArray[i] == 48) {
findLocation();
}
}
}
}
private void getGattService(BluetoothGattService gattService) {
if (gattService == null) {
return;
}
BluetoothGattCharacteristic characteristicRx = gattService.getCharacteristic(HandleConnectionService.UUID_BLE_SHIELD_RX);
mBluetoothLeService.setCharacteristicNotification(characteristicRx, true);
mBluetoothLeService.readCharacteristic(characteristicRx);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(HandleConnectionService.ACTION_GATT_CONNECTED);
intentFilter.addAction(HandleConnectionService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(HandleConnectionService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(HandleConnectionService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(CameraOperations.ACTION_PICTURE_RECEIVED);
return intentFilter;
}
private boolean checkGoogleServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int available = googleAPI.isGooglePlayServicesAvailable(this);
if (available != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(available)) {
googleAPI.getErrorDialog(this, available, PLAY_SERVICES_REQUEST_TIME).show();
}
return false;
}
return true;
}
public void findLocation() {
int REQUEST_CODE_ASK_PERMISSIONS = 123;
double latitude = 0.0;
double longitude = 0.0;
if(Build.VERSION.SDK_INT >= 23){
boolean fineLocationAccess = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean courseLocationAccess = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean accessGranted = fineLocationAccess && courseLocationAccess;
if (accessGranted) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
if(mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Toast.makeText(this, "latitude: " + latitude + " longitude: " + longitude, Toast.LENGTH_LONG).show();
}else{
Log.i("Warning", "Unable to get Location");
}
}else{
Log.i("Connection", "Request permission");
}
}else{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
if(mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Toast.makeText(this, "latitude: " + latitude + " longitude: " + longitude, Toast.LENGTH_LONG).show();
}else{
Log.i("Warning", "Unable to get Location");
}
}
}
public void buildGoogleApiClient() {
mGoogleClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
#Override
public void onConnected(Bundle bundle) {
Log.w("Connected", " : " + mGoogleClient.isConnected());
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "Location Services Stopped", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "Location Services Connection Fail", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleClient != null) {
mGoogleClient.connect();
}
}
}
I think your original idea is actually pretty sound as long as you construct it a certain way. The activity that is knowledgeable about the location information can update and store that location independent of any other activity. This would probably be ideal to have as a service actually that runs every x amount of time, or when the location changes.
Inside of that same class you can have a generic broadcast receiver that handles request for that location information. You can make this as generic as you want in terms of allowing other applications/activities you make also being to leverage it, as long as the location data is returned in a way that is usable to each requester.
From within your activity that takes photos (and eventually any activity you desire), when you take a photo, you can send a broadcast requesting that location information, with some default or null info if none is returned. One of the complexities is knowing how long to wait for this location info before completing. In this scenario the location activity is the 'generalized' one in that multiple activities can request location data if you construct it correctly.
Another potentially robust approach is to make the photo taking activity the generalized one. One way to do this is that when you take a photo, you can have your photo activity send broadcast to the location activity that contains the photos filepath/uri/identifying information, but you don't wait for a response. Instead, you make the location activity listen for this broadcast, and write to the photos meta data with the location using the provided identifying info to find said photo. In this way your photo taking app isn't stuck waiting for the location activity to finish (or event start if it ever does).
Good luck, sounds like a fun project.
i am working on wallpaper app in which i am downloading image, but now i want to show download process while downloading a image.
what i want is: see this screenshot: http://www.techfeb.com/wp-content/uploads/2012/03/download-facebook-photos-on-android-smartphone-2.jpg
this is my code:
Utils.java
package info.androidhive.awesomewallpapers.util;
import info.androidhive.awesomewallpapers.R;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
#SuppressLint("NewApi")
public class Utils {
private String TAG = Utils.class.getSimpleName();
private Context _context;
private PrefManager pref;
// constructor
public Utils(Context context) {
this._context = context;
pref = new PrefManager(_context);
}
/*
* getting screen width
*/
#SuppressWarnings("deprecation")
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) _context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) {
// Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
public void saveImageToSDCard(Bitmap bitmap) {
String dirname = "/Amazing Wallpapers/";
File myDir = new File(Environment
.getExternalStorageDirectory().getPath() + dirname);
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Wallpaper-" +n+".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_LONG).show();
Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();
}
}
public void setAsWallpaper(Bitmap bitmap) {
try {
WallpaperManager wm = WallpaperManager.getInstance(_context);
wm.setBitmap(bitmap);
Toast.makeText(_context,
_context.getString(R.string.toast_wallpaper_set),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_wallpaper_set_failed),
Toast.LENGTH_SHORT).show();
}
}
}
FullScreenActivity.java
package info.androidhive.awesomewallpapers;
import info.androidhive.awesomewallpapers.app.AppController;
import info.androidhive.awesomewallpapers.picasa.model.Wallpaper;
import info.androidhive.awesomewallpapers.util.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
public class FullScreenViewActivity extends Activity implements OnClickListener {
private static final String TAG = FullScreenViewActivity.class
.getSimpleName();
public static final String TAG_SEL_IMAGE = "selectedImage";
private Wallpaper selectedPhoto;
private ImageView fullImageView;
private LinearLayout llSetWallpaper, llDownloadWallpaper;
private Utils utils;
private ProgressBar pbLoader;
// Picasa JSON response node keys
private static final String TAG_ENTRY = "entry",
TAG_MEDIA_GROUP = "media$group",
TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url",
TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_image);
fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
// hide the action bar in fullscreen mode
getActionBar().hide();
utils = new Utils(getApplicationContext());
// layout click listeners
llSetWallpaper.setOnClickListener(this);
llDownloadWallpaper.setOnClickListener(this);
// setting layout buttons alpha/opacity
llSetWallpaper.getBackground().setAlpha(70);
llDownloadWallpaper.getBackground().setAlpha(70);
Intent i = getIntent();
selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE);
// check for selected photo null
if (selectedPhoto != null) {
// fetch photo full resolution image by making another json request
fetchFullResolutionImage();
} else {
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT)
.show();
}
}
/**
* Fetching image fullresolution json
* */
private void fetchFullResolutionImage() {
String url = selectedPhoto.getPhotoJson();
// show loader before making request
pbLoader.setVisibility(View.VISIBLE);
llSetWallpaper.setVisibility(View.GONE);
llDownloadWallpaper.setVisibility(View.GONE);
// volley's json obj request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG,
"Image full resolution json: "
+ response.toString());
try {
// Parsing the json response
JSONObject entry = response
.getJSONObject(TAG_ENTRY);
JSONArray mediacontentArry = entry.getJSONObject(
TAG_MEDIA_GROUP).getJSONArray(
TAG_MEDIA_CONTENT);
JSONObject mediaObj = (JSONObject) mediacontentArry
.get(0);
String fullResolutionUrl = mediaObj
.getString(TAG_IMG_URL);
// image full resolution widht and height
final int width = mediaObj.getInt(TAG_IMG_WIDTH);
final int height = mediaObj.getInt(TAG_IMG_HEIGHT);
Log.d(TAG, "Full resolution image. url: "
+ fullResolutionUrl + ", w: " + width
+ ", h: " + height);
ImageLoader imageLoader = AppController
.getInstance().getImageLoader();
// We download image into ImageView instead of
// NetworkImageView to have callback methods
// Currently NetworkImageView doesn't have callback
// methods
imageLoader.get(fullResolutionUrl,
new ImageListener() {
#Override
public void onErrorResponse(
VolleyError arg0) {
Toast.makeText(
getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(
ImageContainer response,
boolean arg1) {
if (response.getBitmap() != null) {
// load bitmap into imageview
fullImageView
.setImageBitmap(response
.getBitmap());
adjustImageAspect(width, height);
// hide loader and show set &
// download buttons
pbLoader.setVisibility(View.GONE);
llSetWallpaper
.setVisibility(View.VISIBLE);
llDownloadWallpaper
.setVisibility(View.VISIBLE);
}
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
// unable to fetch wallpapers
// either google username is wrong or
// devices doesn't have internet connection
Toast.makeText(getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
});
// Remove the url from cache
AppController.getInstance().getRequestQueue().getCache().remove(url);
// Disable the cache for this url, so that it always fetches updated
// json
jsonObjReq.setShouldCache(false);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Adjusting the image aspect ration to scroll horizontally, Image height
* will be screen height, width will be calculated respected to height
* */
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void adjustImageAspect(int bWidth, int bHeight) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
if (bWidth == 0 || bHeight == 0)
return;
int sHeight = 0;
if (android.os.Build.VERSION.SDK_INT >= 13) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
sHeight = size.y;
} else {
Display display = getWindowManager().getDefaultDisplay();
sHeight = display.getHeight();
}
int new_width = (int) Math.floor((double) bWidth * (double) sHeight
/ (double) bHeight);
params.width = new_width;
params.height = sHeight;
Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width
+ ", h = " + sHeight);
fullImageView.setLayoutParams(params);
}
/**
* View click listener
* */
#Override
public void onClick(View v) {
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
switch (v.getId()) {
// button Download Wallpaper tapped
case R.id.llDownloadWallpaper:
utils.saveImageToSDCard(bitmap);
break;
// button Set As Wallpaper tapped
case R.id.llSetWallpaper:
utils.setAsWallpaper(bitmap);
break;
default:
break;
}
}
}
A very good toturial to do so here..
http://www.androidbegin.com/tutorial/android-download-image-from-url/\
A snippet of the code from the site is below:
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Download Image Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// Set the bitmap into ImageView
image.setImageBitmap(result);
// Close progressdialog
mProgressDialog.dismiss();
}
}
You can use ProgressDialog within the onCreate method.
mProgressDialog = new ProgressDialog(YourActivity.this);
You can then add other attributes like a message and so on like this:
mProgressDialog.setMessage("A message");
You can also add listeners like this:
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// Do stuff on Cancel
}
});
Check this link:
Download a file with Android, and showing the progress in a ProgressDialog
So here I want to have click event on pressing which i will have particular Category of location rather than search box for searching places. On pressing OnClickGPS it will open PlacePickerFragment of Facebook with search box at the top. But i want to search places category wise like Restaurent, Theatre, etc. on button click. Any assistance in this will be highly appreciable.
package com.priyank.checkin;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.facebook.model.GraphLocation;
import com.facebook.model.GraphPlace;
import com.facebook.widget.PlacePickerFragment;
import com.facebook.Session;
public class PlacePickerSampleActivity extends FragmentActivity implements LocationListener {
private static final int PLACE_ACTIVITY = 1;
private static final Location SEATTLE_LOCATION = new Location("") {
{
setLatitude(47.6097);
setLongitude(-122.3331);
}
};
private static final Location SAN_FRANCISCO_LOCATION = new Location("") {
{
setLatitude(37.7750);
setLongitude(-122.4183);
}
};
private static final Location PARIS_LOCATION = new Location("") {
{
setLatitude(48.857875);
setLongitude(2.294635);
}
};
private TextView resultsTextView;
private LocationManager locationManager;
private Location lastKnownLocation;
private String NameEditTextValue;
private EditText NameEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main7);
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
NameEditTextValue = NameEditText.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Alert Message");
i.putExtra(Intent.EXTRA_TEXT, NameEditTextValue +"- via Security Android App");
startActivity(Intent.createChooser(i, "Alert Status"));
}
});
NameEditText = (EditText) findViewById(R.id.editText1);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
Button button = (Button) findViewById(R.id.seattleButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickSeattle();
}
});
button = (Button) findViewById(R.id.sanFranciscoButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickSanFrancisco();
}
});
button = (Button) findViewById(R.id.gpsButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickGPS();
}
});
if (Session.getActiveSession() == null ||
Session.getActiveSession().isClosed()) {
Session.openActiveSession(this, true, null);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onStart() {
super.onStart();
// Update the display every time we are started (this will be "no place selected" on first
// run, or possibly details of a place if the activity is being re-created).
displaySelectedPlace(RESULT_OK);
}
private void onError(Exception exception) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error").setMessage(exception.getMessage()).setPositiveButton("OK", null);
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PLACE_ACTIVITY:
displaySelectedPlace(resultCode);
break;
default:
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
break;
}
}
private void displaySelectedPlace(int resultCode) {
String results = "";
PlacePickerApplication application = (PlacePickerApplication) getApplication();
GraphPlace selection = application.getSelectedPlace();
if (selection != null) {
GraphLocation location = selection.getLocation();
results = String.format("Name: %s\nCategory: %s\nLocation: (%f,%f)\nStreet: %s, %s, %s, %s, %s",
selection.getName(), selection.getCategory(),
location.getLatitude(), location.getLongitude(),
location.getStreet(), location.getCity(), location.getState(), location.getZip(),
location.getCountry());
} else {
results = "<No place selected>";
}
resultsTextView.setText(results);
NameEditText.setText(results);
}
public void onLocationChanged(Location location) {
lastKnownLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void startPickPlaceActivity(Location location) {
PlacePickerApplication application = (PlacePickerApplication) getApplication();
application.setSelectedPlace(null);
Intent intent = new Intent(this, PickPlaceActivity.class);
PickPlaceActivity.populateParameters(intent, location, null);
startActivityForResult(intent, PLACE_ACTIVITY);
}
private void onClickSeattle() {
try {
startPickPlaceActivity(SEATTLE_LOCATION);
} catch (Exception ex) {
onError(ex);
}
}
private void onClickSanFrancisco() {
try {
startPickPlaceActivity(SAN_FRANCISCO_LOCATION);
} catch (Exception ex) {
onError(ex);
}
}
private void onClickGPS() {
try {
if (lastKnownLocation == null) {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
if (bestProvider != null) {
lastKnownLocation = locationManager.getLastKnownLocation(bestProvider);
}
}
if (lastKnownLocation == null) {
String model = android.os.Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// Looks like they are on an emulator, pretend we're in Paris if we don't have a
// location set.
lastKnownLocation = PARIS_LOCATION;
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.error_dialog_title)
.setMessage(R.string.no_location)
.setPositiveButton(R.string.ok_button, null)
.show();
return;
}
}
startPickPlaceActivity(lastKnownLocation);
} catch (Exception ex) {
onError(ex);
}
}
}
The best way to do this is to use the PlacePickerFragment, and call setSearchText("restaurant"). While it doesn't necessarily restrict it to a category, it will search everything that is categorized as a restaurant.
You can also see an example of this in the Scrumptious sample app (in the PickerActivity class).