How to post HTTP by post method - java

I fetch latitude and longitude from the location manager but its doesn't connect with thingboard HTTP iot cloud. I used HTTP post response.it does not generate any error but it also doesn't transfer any data.since it is an AsyncTask it does not generate any error.i have encoded the latitude and long
package com.example.currentgpslocation;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity<policy> extends AppCompatActivity implements LocationListener {
LocationManager locationManager;
String GPS_PROVIDER;
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
GPS_PROVIDER = locationManager.getBestProvider(criteria, false);
if (GPS_PROVIDER != null && !GPS_PROVIDER.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);;
locationManager.requestLocationUpdates(GPS_PROVIDER, 15000, 1, this);
if (location != null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
TextView longitude = (TextView) findViewById(R.id.textView);
TextView latitude = (TextView) findViewById(R.id.textView1);
longitude.setText("Current Longitude:" + location.getLongitude());
latitude.setText("Current Latitude:" + location.getLatitude());
try {
Object latitud = location.getLatitude();
latitud = latitud.toString();
Object longtitud = location.getLongitude();
longtitud = longtitud.toString();
data = URLEncoder.encode("latitude", "UTF-8")
+ "=" + URLEncoder.encode(String.valueOf(latitude), "UTF-8");
data += "," + URLEncoder.encode("longtitude", "UTF-8")
+ "=" + URLEncoder.encode(String.valueOf(latitude), "UTF-8");
}catch (Exception ex){
ex.printStackTrace();
}
DemoTask ob= new DemoTask();
ob.execute();
}
public class DemoTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
String text = "";
BufferedReader reader = null;
try {
// Defined URL where to send data
URL url = new URL("https://cloud.thingsboard.io/api/v1/JD98YCFBU8ywGIwVmdFL/telemetry");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.connect();
int responseCode = conn.getResponseCode();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(), "UTF8");
wr.write(data);
conn.getErrorStream();
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
wr.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Generate the Error :
W/System.err: java.io.IOException: closed
W/System.err: at com.android.okhttp.okio.RealBufferedSink$1.write(RealBufferedSink.java:196)

Related

Send an image and other string parameters to server using HttpURLConnection and Base64

I am trying to send an image and some string values from android to a php script using HttpURLConnection. I have successfully done so with strings, but can't seem to get it right with the image. I am using Base64 (android.util.Base64) to convert my image to a string to send it. Now, I have a separate HttpParse.java file I use to send all my info to the server, and I think that is where the change needs to be made to allow the image, but I'm not sure, (I am newer to java/android development). I've researched several similar questions, but they aren't fully clicking for me for what I'm doing wrong. Also, I have tested that I am successfully converting the image to a string. Here is my code:
EDIT I got a little farther... After testing, I am getting the issue because the three variables I try to get with getArguments() are coming back as null... But, I can't figure out how to get them to come through successfully... I added the code for how I start my fragment and how I try to get my bundle
My fragment start:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_units);
Intent intent = getIntent();
LexaUser = intent.getStringExtra("UserName");
ReadOnly = intent.getStringExtra("ReadOnly");
Password = intent.getStringExtra("Password");
QA = intent.getStringExtra("QA");
SearchValue = intent.getStringExtra("SearchInput");
bottomNavigation = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigation.inflateMenu(R.menu.bottom_menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.getMenu().getItem(0).setChecked(true);
UnitDetailsHeader = findViewById(R.id.UnitDetailsViewTitle);
UnitDetailsHeader.setText(SearchValue);
UnitSizeText = findViewById(R.id.UnitSize);
UnitStatusText = findViewById(R.id.UnitStatus);
if (SearchValue.contains("-")) {
getUnitDetails(SearchValue, LexaUser);
} else {
getSiblings();
}
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_search:
fragment = new NewUnitStatusFragment();
break;
case R.id.action_cart:
fragment = new PendingUnitStatusFragment();
break;
case R.id.action_hot_deals:
fragment = new FinalUnitStatusFragment();
break;
case R.id.action_siblings:
fragment = new SiblingUnitFragment();
break;
}
Bundle connBundle = new Bundle();
connBundle.putString("SearchValue", SearchValue);
connBundle.putString("LexaUser", LexaUser);
connBundle.putString("Password", Password);
connBundle.putString("QA", QA);
fragment.setArguments(connBundle);
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment).commit();
return true;
}
});
}
And where I try to get my arguments: (I originally had in onCreateView but then tried to move it to onCreate. But the behavior was the same)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
}
My fragment where I get the image and send my data:
package [my_package];
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.util.Base64;
import java.util.HashMap;
import static android.app.Activity.RESULT_OK;
public class NewUnitStatusFragment extends Fragment {
Context newUnitStatusContext;
Activity newUnitStatusActivity;
Intent cameraIntent;
ProgressDialog progressDialog;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultNewUnitStatus;
String HttpURLNewUnitStatus = "https://[path/to/file]/insertNewUnitStatus.php";
HashMap<String, String> hashMapNewUnitStatus = new HashMap<>();
HttpParse httpParse = new HttpParse();
Spinner statusSpinner;
Spinner generalCauseSpinner;
EditText newUSComment;
Button addPhotoBtn;
ImageView newUnitStatusImage;
Button addNewUnitStatus;
String newUnitStatus;
String generalCause;
String newUnitStatusComment;
String newUnitStatusPhoto;
String message;
private static final int PICK_FROM_GALLERY = 1;
public NewUnitStatusFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newunitstatus, container, false);
newUnitStatusContext = getContext();
newUnitStatusActivity = getActivity();
statusSpinner = view.findViewById(R.id.Status);
generalCauseSpinner = view.findViewById(R.id.GeneralCause);
newUSComment = view.findViewById(R.id.NewComment);
newUnitStatusImage = view.findViewById(R.id.AddPhoto);
addPhotoBtn = view.findViewById(R.id.AddPhotosLabel);
addNewUnitStatus = view.findViewById(R.id.addBtnNewUnitStatus);
ArrayAdapter<CharSequence> statusSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.new_unit_status_array, android.R.layout.simple_spinner_item);
statusSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerAdapter);
newUnitStatus = statusSpinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> generalCauseSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.status_general_cause_array, android.R.layout.simple_spinner_item);
generalCauseSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
generalCauseSpinner.setAdapter(generalCauseSpinnerAdapter);
generalCause = generalCauseSpinner.getSelectedItem().toString();
addPhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGallery();
}
});
// Set a click listener for the text view
addNewUnitStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newUnitStatus = statusSpinner.toString();
generalCause = generalCauseSpinner.toString();
newUnitStatusComment = newUSComment.toString();
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
addNewUnitStatus(SearchValue, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, LexaUser, Password);
}
});
return view;
}
private void startGallery() {
cameraIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
cameraIntent.setAction(Intent.ACTION_GET_CONTENT);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
} else {
Toast.makeText(newUnitStatusContext, "Error: " + cameraIntent + " - cameraIntent.resolveActivity(getActivity().getPackageManager()) = null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
Uri returnUri = data.getData();
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
newUnitStatusImage.setImageBitmap(bitmapImage);
newUnitStatusImage.buildDrawingCache();
Bitmap bm = newUnitStatusImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
newUnitStatusPhoto = Base64.encodeToString(b, Base64.DEFAULT);
} catch (IOException ioEx) {
ioEx.printStackTrace();
Toast.makeText(newUnitStatusContext, "ioEx Error: " + ioEx, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + requestCode, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + resultCode, Toast.LENGTH_LONG).show();
}
}
public void addNewUnitStatus(String searchInput, String newUnitStatus, String generalCause, String newUnitStatusComment, String newUnitStatusPhoto, String lexaUser, String password) {
class NewUnitStatusClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(newUnitStatusContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONObject object = new JSONObject(httpResponseMsg);
message = object.getString("message");
Toast.makeText(newUnitStatusContext, httpResponseMsg, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(newUnitStatusContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(newUnitStatusContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapNewUnitStatus.put("searchinput", params[0]);
hashMapNewUnitStatus.put("newUnitStatus", params[1]);
hashMapNewUnitStatus.put("generalCause", params[2]);
hashMapNewUnitStatus.put("newUnitStatusComment", params[3]);
hashMapNewUnitStatus.put("newUnitStatusPhoto", params[4]);
hashMapNewUnitStatus.put("lexauser", params[5]);
hashMapNewUnitStatus.put("password", params[6]);
finalResultNewUnitStatus = httpParse.postRequest(hashMapNewUnitStatus, HttpURLNewUnitStatus);
return finalResultNewUnitStatus;
}
}
NewUnitStatusClass newUnitStatusClass = new NewUnitStatusClass();
newUnitStatusClass.execute(searchInput, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, lexaUser, password);
}
}
And my code to do that actuall HttpURLConnection: HttpParse.java
package [my_package];
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpParse extends ListActivity {
String FinalHttpData = "";
String Result;
BufferedWriter bufferedWriter;
OutputStream outputStream;
BufferedReader bufferedReader;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
All help is appreciated! Thank you!
P.S. my app shows the following error:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
This then leads to this:
E/JSONException: Error: org.json.JSONException: End of input at character 0 of

START_STICKY of onStartCommand in Android 6.0.0

I am working with some application which starts a service.
When I close app under Android 7.0.0 its service is continue working fine.
But under Android 6.0.0 it does not.
I use this snippet to keep working service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
What do I missing here?
Code of the service class
import android.Manifest;
//import android.app.LoaderManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
//import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
//import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.ContextCompat;
//import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.gson.Gson;
import java.util.Date;
import java.util.Timer;
//import java.util.TimerTask;
import java.io.*;
import java.net.*;
//import java.util.Timer;
//import java.util.TimerTask;
import static com.google.android.gms.location.LocationServices.getFusedLocationProviderClient;
public class gps_service extends Service {
private static final String TAG = "MyService";
private LocationListener listener;
private LocationManager locationManager;
private Timer timer = new Timer();
// private DLocation dLocation;
private final Object lock = new Object();
Context context;
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 60 * 1000; /* 60 secs */
private long FASTEST_INTERVAL = 10000; /* 10 sec */
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
startLocationUpdates();
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
context = this;
}
// Trigger new location updates at interval
protected void startLocationUpdates() {
// Create the location request to start receiving updates
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
// do work here
onLocationChanged(locationResult.getLastLocation());
}
}, Looper.myLooper());
}
public void getLastLocation() {
// Get last known recent location using new Google Play Services SDK (v11+)
FusedLocationProviderClient locationClient = getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
if (location != null) {
onLocationChanged(location);
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "Ошибка получения последнего GPS позиции");
e.printStackTrace();
}
});
}
public void onLocationChanged(Location location) {
// New location has now been determined
try
{
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(context, "App_Settings", 0);
AppSettings appSettings = complexPreferences.getObject("App_Settings", AppSettings.class);
if (appSettings != null) {
LocationItem locationItem = new LocationItem();
locationItem.DeviceID = appSettings.getDeviceID();
locationItem.Latitude = Double.toString(location.getLatitude());
locationItem.Longitude = Double.toString(location.getLongitude());
Date d = new Date();
CharSequence timeOfRequest = DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime()); // YYYY-MM-DD HH:mm:ss
locationItem.TimeOfRequest = timeOfRequest.toString();
locationItem.SerialNumber = appSettings.getSerialNumber();
//**************** Отправка сообщения в окно *********************
Intent i = new Intent("location_update");
Log.d(TAG, "Рассылка по слушателям в окнах");
DLocation dLocation = new DLocation();
dLocation.Latitude = locationItem.Latitude;
dLocation.Longitude = locationItem.Longitude;
dLocation.TimeOfRequest = locationItem.TimeOfRequest;
dLocation.Errors = "Данные передаются...";
i.putExtra("coordinates", dLocation);
sendBroadcast(i);
//**************** Отправка сообщения в окно *********************
Gson gson = new Gson();
String requestObject = gson.toJson(locationItem);
Log.d(TAG, "Формирование URL API сервера");
String url = appSettings.getIpAddress() + "/api/staff/savedata";
makeRequest(url, requestObject, dLocation);
}
}
catch (Exception ex)
{
Log.d(TAG, "Ошибка: " + ex.getMessage());
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null) {
locationManager.removeUpdates(listener);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void makeRequest(String uri, String json, DLocation dLocation) {
HandlerThread handlerThread = new HandlerThread("URLConnection");
handlerThread.start();
Handler mainHandler = new Handler(handlerThread.getLooper());
Runnable myRunnable = createRunnable(uri, json, dLocation);
mainHandler.post(myRunnable);
}
private Runnable createRunnable(final String uri, final String data,final DLocation dLocation){
Runnable aRunnable = new Runnable(){
public void run(){
try {
Log.d(TAG, "Перед запросом HTTP");
//Connect
HttpURLConnection urlConnection;
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
try {
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,"Ошибка записи в буфер для пережачи по HTTP");
}
writer.close();
outputStream.close();
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
String result = sb.toString();
Log.d(TAG, "После запроса HTTP");
Log.d(TAG, result);
// Log.d(TAG, "Результат передачи: " + result);
//**************** Отправка сообщения в окно *********************
Intent iResult = new Intent("location_update");
Log.d(TAG, "Рассылка по слушателям в окнах");
DLocation dLocation = new DLocation();
if(result.equals("true"))
{
dLocation.Errors = "Данные успешно переданы.";
}
else
{
dLocation.Errors = "Ошибка передачи данных.";
}
iResult.putExtra("result", dLocation);
sendBroadcast(iResult);
//**************** Отправка сообщения в окно *********************
}catch( Exception err){
err.printStackTrace();
Log.d(TAG, "Ошибка HTTP " + err.getMessage());
}
}
};
return aRunnable;
}
}
Use attribute android:stopWithTask="false" in manifest, if its true (By default its false if you are not using this in manifest).
<service
android:name=".gps_service"
android:enabled="true"
android:stopWithTask="false"/>
restart the service on onTaskRemoved().
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}
As documentation says
onTaskRemoved will called if the service is currently running and the user has removed a task that comes from the service's application. If you have set ServiceInfo.FLAG_STOP_WITH_TASK then you will not receive this callback; instead, the service will simply be stopped.

Upload image using base64 string, result in a broken image

I encode the image using base64 and then send to php server.
It uploaded success but result in a broken image.
No errors only a black image. May be I missing some important settings?
Upload activity
package xxxx.com.myapps;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class UploadImageActivity extends Activity {
private Button btnBrowse, btnUpload;
private AlertDialog.Builder dialogBuilder;
private ImageView imageToUpload;
private String imgPath, fileName;
String encodedString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
btnBrowse = (Button) findViewById(R.id.btnBrowse);
btnUpload = (Button) findViewById(R.id.btnUpload);
imageToUpload = (ImageView) findViewById(R.id.imageToUpload);
btnBrowse.setOnClickListener(btnListener);
btnUpload.setOnClickListener(btnListener);
}
private Button.OnClickListener btnListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnBrowse:
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, Constants.PICK_IMAGE_CONTACT_REQUEST);
break;
case R.id.btnUpload:
Network network = new Network(UploadImageActivity.this);
if (network.isConnected()) {
new UploadImageAsyntask().execute();
} else {
dialogBuilder.setTitle(R.string.waring).setMessage(R.string.no_network_connection);
dialogBuilder.create();
dialogBuilder.show();
}
break;
}
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == Constants.PICK_IMAGE_CONTACT_REQUEST && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView
imageToUpload.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
// Get the Image's file name
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
private class UploadImageAsyntask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(imgPath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
encodedString = Base64.encodeToString(byteArray,0);
String postParams = "tag=upload_new&filename=" + fileName + "&image=" + encodedString;
String jsonResult = Network.webRequest(Constants.RENOTE_DB_URL, postParams);
return jsonResult;
}
#Override
protected void onPostExecute(String jsonResult) {
super.onPostExecute(jsonResult);
// Log.d("testing", jsonResult);
}
}
}
Http Request class
package xxxx.com.myapps;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Network {
Context context;
public Network(Context context) {
this.context = context;
}
public boolean isConnected() {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
public static final String webRequest(String url, String postParams) {
String requestResult = null;
HttpURLConnection conn = null;
try {
URL remoteDbUrl = new URL(url);
conn = (HttpURLConnection) remoteDbUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setUseCaches(false);
if (postParams != null) {
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream outputStream = conn.getOutputStream();
outputStream.write(postParams.getBytes());
outputStream.close();
}
BufferedReader bufferedReader = new BufferedReader((new InputStreamReader(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
requestResult = sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return requestResult;
}
}
php upload code
...
else if ($tag == 'upload_new') {
// Get image string posted from Android App
$base = $_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];
// Decode Image
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploadedimages/' . $filename, 'wb');
// Create File
$result = fwrite($file, $binary);
if ($result) {
echo "success";
} else {
echo "fail";
}
fclose($file);
}

Android Google Maps Polyline not showing on Map

I have made a class that have a method and a locaton listener. The locationListener will be executed every 2 seconds , gets the lat longs and will pass it to the Async Task. The Async Task class will pass the lat longs to Google Road Api to get snapped lat longs and will pass the lat longs to postExecute()
The PostExecute() should draw the polylines But it does not..
Please See the below code.:
MapsActivity.java
package com.example.akshay.roadsapi;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
final String URL = "https://roads.googleapis.com/v1/snapToRoads?path=";
final String KEY = "API KEY HERE";
int i = 0;
AsyncTask<Void, Void, LatLng> latLng1 = null;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
BackgroundTask backgroundTask = new BackgroundTask(MapsActivity.this, latLng, URL, KEY, activity, mMap);
backgroundTask.execute();
/*mMap.addMarker(new MarkerOptions().position(latLng1));*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
BackgroundTask.java
package com.example.akshay.roadsapi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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.URI;
import java.net.URISyntaxException;
/**
* Created by Akshay on 9/8/2015.
*/
public class BackgroundTask extends AsyncTask<Void, Void, LatLng> {
Context CONTEXT;
LatLng LATLNGS;
String URL;
String KEY;
Double LAT = null;
Double LONG = null;
GoogleMap map;
Activity ACTIVITY;
myInt myInt = null;
int flag = 0;
LatLng prev;
LatLng latlng;
public BackgroundTask(Context context, LatLng LATLNGS, String URL, String KEY, Activity ACTIVITY, GoogleMap map) {
this.CONTEXT = context;
this.LATLNGS = LATLNGS;
this.URL = URL;
this.KEY = KEY;
this.ACTIVITY = ACTIVITY;
this.map = map;
}
#Override
protected LatLng doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet();
HttpResponse response = null;
HttpEntity entity = null;
InputStream inputStreamReader = null;
BufferedReader bufferedReader = null;
String line = null;
StringBuilder strin = new StringBuilder();
try {
get.setURI(new URI(URL + LATLNGS.latitude + "," + LATLNGS.longitude + "&interpolate=false&key=" + KEY));
response = client.execute(get);
entity = response.getEntity();
inputStreamReader = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStreamReader));
while ((line = bufferedReader.readLine()) != null) {
strin.append(line + "\n");
}
Log.e("============", strin.toString());
JSONObject ob = new JSONObject(strin.toString());
JSONArray array = ob.getJSONArray("snappedPoints");
for (int i = 0; i <= array.length(); i++) {
JSONObject object = array.getJSONObject(i).getJSONObject("location");
LAT = object.getDouble("latitude");
LONG = object.getDouble("longitude");
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
latlng= new LatLng(LAT, LONG);
return latlng;
}
#Override
protected void onPostExecute(LatLng latLng) {
super.onPostExecute(latLng);
/* MarkerOptions markerOptions = new MarkerOptions().position(latLng);
map.addMarker(markerOptions);*/
if (flag == 0) {
prev = latLng;
flag = 1;
}
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18);
/* Marker marker = map.addMarker(new MarkerOptions().position(latLng));*/
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.add(prev, latLng).color(Color.BLUE).width(50).visible(true);
map.addPolyline(polylineOptions);
map.animateCamera(cameraUpdate);
prev = latLng;
latLng = null;
}
}
I am getting the Json Array From GOOGLE API and getting the lats long values successfully but polyline is not Drawn..
Please Help
Thanks

i'v added google map in my project but it is not loading on emulator givin that "meetup someone via smarphone is stopped unfortunately"

google map is loading on emulator givin error that application is stopped unfortunately following is my code package com.ayesha.MIT;
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;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Spot_Location_Screen extends FragmentActivity implements
LocationListener {
Database_Table_Operations database;
ArrayList<String> locations = new ArrayList<String>();
ArrayList<String> latitude = new ArrayList<String>();
ArrayList<String> longitude = new ArrayList<String>();
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
Intent intent;
String[] mPlaceType = null;
String[] mPlaceTypeName = null;
double mLatitude = 0;
double mLongitude = 0;
Button btnFind;
Button doneButton;
boolean isFound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.spot_location_screen);
mPlaceType = getResources().getStringArray(R.array.place_type);
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
mSprPlaceType.setAdapter(adapter);
btnFind = (Button) findViewById(R.id.btn_find);
doneButton = (Button) findViewById(R.id.doneButton);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mGoogleMap = fragment.getMap();
mGoogleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
database = new Database_Table_Operations(getApplicationContext());
if (getIntent().getStringExtra("Update") != null) {
if (getIntent().getStringExtra("Update").equals("true")) {
addMarker(getIntent().getStringExtra("Date"));
}
}
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
if (location != null) {
onLocationChanged(location);
}
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (checkInternetConnection(getApplicationContext())) { // browser
// key
mGoogleMap.clear();
locations.clear();
latitude.clear();
longitude.clear();
int selectedPosition = mSprPlaceType
.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + 33.6000 + "," + 73.0333);
sb.append("&radius=20000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyAVhTyd9GXAkJ9VJ1S7OD9ldrBsQgOH69c");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
}
}
});
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (checkInternetConnection(getApplicationContext())) {
if (getIntent().getStringExtra("Update").equals("true")) {
database.open();
String myDate = getIntent().getStringExtra("Date");
locations.add(database.getLocation(myDate));
latitude.add(database.getLatitude(myDate));
longitude.add(database.getLongitude(myDate));
intent = new Intent(Spot_Location_Screen.this,
Locations_List_View_Screen.class);
intent.putStringArrayListExtra("Locations",
locations);
intent.putStringArrayListExtra("Latitude", latitude);
intent.putStringArrayListExtra("Longitude",
longitude);
intent.putExtra("Date",
getIntent().getStringExtra("Date"));
intent.putExtra("Update", getIntent()
.getStringExtra("Update"));
database.close();
startActivity(intent);
finish();
} else {
if (locations.size() != 0) {
intent = new Intent(Spot_Location_Screen.this,
Locations_List_View_Screen.class);
intent.putStringArrayListExtra("Locations",
locations);
intent.putStringArrayListExtra("Latitude",
latitude);
intent.putStringArrayListExtra("Longitude",
longitude);
intent.putExtra("Date", getIntent()
.getStringExtra("Date"));
intent.putExtra("Update", getIntent()
.getStringExtra("Update"));
startActivity(intent);
finish();
}
}
}
}
});
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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 while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends
AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(
String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
latitude.add(String.valueOf(lat));
double lng = Double.parseDouble(hmPlace.get("lng"));
longitude.add(String.valueOf(lng));
String name = hmPlace.get("place_name");
String vicinity = hmPlace.get("vicinity");
locations.add(name + ", " + vicinity);
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
mGoogleMap.addMarker(markerOptions);
}
if (locations.size() > 1) {
int median = locations.size();
median = median / 2;
LatLng myLatLng = new LatLng(Double.parseDouble(latitude
.get(median)),
Double.parseDouble(longitude.get(median)));
mGoogleMap.animateCamera(CameraUpdateFactory
.newLatLng(myLatLng));
} else if (locations.size() == 1) {
LatLng myLatLng = new LatLng(
Double.parseDouble(latitude.get(0)),
Double.parseDouble(longitude.get(0)));
mGoogleMap.animateCamera(CameraUpdateFactory
.newLatLng(myLatLng));
}
}
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
intent = new Intent(Spot_Location_Screen.this,
SetMeetup_Screen.class);
startActivity(intent);
finish();
}
return super.onKeyDown(keyCode, event);
}
public void addMarker(String date) {
database.open();
MarkerOptions markerOptions = new MarkerOptions();
final LatLng latLng = new LatLng(Double.parseDouble(database
.getLatitude(date)), Double.parseDouble(database
.getLongitude(date)));
markerOptions.position(latLng);
markerOptions.title("Your saved location:\n"
+ database.getLocation(date));
mGoogleMap.addMarker(markerOptions);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
database.close();
}
}, 2500);
}
public boolean checkInternetConnection(Context context) {
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
isFound = true;
} else {
isFound = false;
}
return isFound;
}
}
Google Android Map API is not able to run Google Maps on the Android emulator. You must use an Real Android device for testing your app.
Refer this link to run Google Map on emulator.
hey ma problem is solved but the emulator is not working with Google maps I think its about the device problem but before it was also not working with the blue stacks for that I've changed the package name
right click the package from
src folder->refactor->rename
and
change the package name then change the package name in the manifest then click the on the project
ctrl+shiftz+o
it will change the package name throughout your project..
then again create the browser key and android key with new package name and it will load the map.....
and don forget to turn on the API's in Google console... and also check the minimum SDK version if its 9 then go to SSDK manager and install API 9 by clicking the obsolete option there...

Categories