How to upload image Android to Server using PHP mysql - java

I have a problem about uploading images from android to a server, the problem is about the android version, my application can run on android version 2.3 but can not run on version > 2.3. these is my code
function TambahLokasi()
{
$base = $_REQUEST["gambar"];
if (isset($base)){
$suffix = createRandomID();
$image_name = "img_".$suffix."_".date("Y-m-d-H-m-s").".jpg";
$binary = base64_decode($base);
header("Content-Type: bitmap; charset=utf-8");
$file = fopen("gambar/" . $image_name, "wb");
fwrite($file, $binary);
fclose($file);
$username = $_POST['USERNAME'];
$loc_name = $_POST['LOCATION_NAME'];
$category = $_POST['CATEGORY'];
$address = $_POST['ADDRESS'];
$city = $_POST['CITY'];
$descript = $_POST['DESCRIPTION'];
$own = $_POST['OWNER'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$query = "insert into location (USERNAME,LOCATION_NAME,CATEGORY,ADDRESS,CITY,DESCRIPTION,OWNER,lat,lng,gambar)values ('$username', '$loc_name', '$category', '$address','$city','$descript','$own','$lat','$lng','$image_name')";
//$query = "insert into pasien values ('','n', 'n', 'n', 'n','bar','','','n','n','n')";
$hasil = mysql_query($query);
if($hasil)
{
$respon["success"] = "1";
$respon["pesan"] = "Data berhasil diinput";
echo json_encode($respon);
}
else
{
$respon["success"] = "0";
$respon["pesan"] = "Data gagal diinput. Mohon cek kembali.";
echo json_encode($respon);
die($image_name);
}
}else {
die("No POST");
}
}
function createRandomID() {
$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";
//srand((double) microtime() * 1000000);
$i = 0;
$pass = "";
while ($i <= 5) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
and this is java code
package com.adi.lib;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.adi.peta.AddLocation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.Button;
public class HttpUploader extends AsyncTask<String, Void, String>
{
String ba1;
Base64 base;
ProgressDialog pDialog;
Intent intent;
AddLocation add;
#SuppressWarnings("static-access")
protected String doInBackground(String... path)
{
String output = null;
for(String sdPath : path)
{
Bitmap bmp = BitmapFactory.decodeFile(sdPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
double width = bmp.getWidth();
double height = bmp.getHeight();
double ratio = 400/width;
int newHeight = (int)(ratio*height);
bmp = Bitmap.createScaledBitmap(bmp, 400, newHeight, true);
bmp.compress(CompressFormat.JPEG, 90, bao);
byte[] ba= bao.toByteArray();
ba1 = base.encodeToString(ba, 0);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("USERNAME", add.strUsername));
params.add(new BasicNameValuePair("LOCATION_NAME", add.strLocName));
params.add(new BasicNameValuePair("CATEGORY", add.strCategory));
params.add(new BasicNameValuePair("ADDRESS", add.strAddress));
params.add(new BasicNameValuePair("CITY", add.strCity));
params.add(new BasicNameValuePair("DESCRIPTION", add.strDesc));
params.add(new BasicNameValuePair("OWNER", add.strowner));
params.add(new BasicNameValuePair("lat", add.strlat));
params.add(new BasicNameValuePair("lng", add.strLng));
params.add(new BasicNameValuePair("gambar", ba1));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://batiktour.adi-hidayat.com/Android/AddLocation.php");
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity);
Log.i("GET RESPONSE--",output);
Log.e("log_tag ******", "good connection");
bmp.recycle();
}
catch (Exception e)
{
Log.e("log_tag ******",
"Error in http connection " + e.toString());
}
}
return output;
}
}
AddLocation.java
package com.adi.peta;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.ErrorManager;
import android.widget.AdapterView.OnItemSelectedListener;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.w3c.dom.Text;
import com.adi.lib.HttpUploader;
import com.adi.lib.JSONParser;
import com.adi.lib.SessionManager;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.R.string;
import android.location.Address;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.widget.AdapterView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddLocation extends FragmentActivity implements LocationListener
{
Uri currImageURI;
GoogleMap googlemap;
ProgressDialog pDialog;
SessionManager session;
JSONParser jsonParser = new JSONParser();
EditText loc_name, address, city, desc, owner, latitude, longitude;
Spinner category;
Button submit, browse, gps;
String[] items = { "Tulis", "Cap", "Campuran" };
String id_user, tempcate, email, name, phone;
TextView path,status;
String image_name;
private static String url = "http://batiktour.adi-hidayat.com/Android/AddLocation.php";
public static String strUsername;
public static String strLocName;
public static String strCategory;
public static String strAddress;
public static String strCity;
public static String strDesc;
public static String strowner;
public static String strlat;
public static String strLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_location);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
.show();
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_USER);
// phone = user.get(SessionManager.KEY_PHONE);
TextView status = (TextView) findViewById(R.id.status);
status.setText(Html.fromHtml(email));
loc_name = (EditText) findViewById(R.id.locName);
address = (EditText) findViewById(R.id.address);
city = (EditText) findViewById(R.id.city);
desc = (EditText) findViewById(R.id.desc);
owner = (EditText) findViewById(R.id.owner);
latitude = (EditText) findViewById(R.id.tvLAT);
longitude = (EditText) findViewById(R.id.tvLNG);
category = (Spinner) findViewById(R.id.category);
submit = (Button) findViewById(R.id.submit);
browse = (Button) findViewById(R.id.browse);
gps = (Button) findViewById(R.id.ubahGPS);
path = (TextView) findViewById(R.id.path);
category = (Spinner)findViewById(R.id.category);
ArrayAdapter aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(aa);
category.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
strCategory = items[position];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapTambah);
googlemap = fm.getMap();
googlemap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
ImageView img = new ImageView(this);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), 1);
}
});
gps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
double chgLat;
double chgLng;
chgLat = Double.parseDouble(latitude.getText().toString());
chgLng = Double.parseDouble(longitude.getText().toString());
LatLng latlng = new LatLng(chgLat, chgLng);
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
googlemap.addMarker(new MarkerOptions()
.position(latlng)
.title("POSISI")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
});
googlemap.setOnMapClickListener(new OnMapClickListener()
{
#Override
public void onMapClick(LatLng latlong)
{
double lat = latlong.latitude;
double lng = latlong.longitude;
latitude.setText(String.valueOf(lat));
longitude.setText(String.valueOf(lng));
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latlong);
googlemap.clear();
// Animating to the touched position
googlemap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
// Placing a marker on the touched position
googlemap.addMarker(markerOptions);
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(loc_name.getText().toString().trim().length()>0 &&
address.getText().toString().trim().length()>0 &&
city.getText().toString().trim().length()>0 &&
owner.getText().toString().trim().length()>0 &&
desc.getText().toString().trim().length()>0 &&
latitude.getText().toString().trim().length()>0 &&
longitude.getText().toString().trim().length()>0
){
if (path.getText().equals("")) {
Toast.makeText(getApplicationContext(),
"Belum Pilih Gambar", Toast.LENGTH_LONG).show();
} else {
String idUser;
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
idUser = user.get(SessionManager.KEY_USER);
strUsername = idUser;
strLocName = loc_name.getText().toString();
strAddress = address.getText().toString();
strCity = city.getText().toString();
strDesc = desc.getText().toString();
strowner = owner.getText().toString();
strlat = latitude.getText().toString();
strLng = longitude.getText().toString();
new AddLoc().execute();
}
}
else
{
Toast.makeText(getApplicationContext(), "Isilah yang kosong", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onLocationChanged(Location location) {
EditText tvLAT = (EditText) findViewById(R.id.tvLAT);
EditText tvLNG = (EditText) findViewById(R.id.tvLNG);
Button gps = (Button) findViewById(R.id.ubahGPS);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
googlemap.addMarker(new MarkerOptions().position(latLng)
.title("You're Here"));
tvLAT.setText(String.valueOf(latitude));
tvLNG.setText(String.valueOf(longitude));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// currImageURI is the global variable I’m using to hold the
// content:
currImageURI = data.getData();
path.setText(getRealPathFromURI(currImageURI));
}
}
}
// Convert the image URI to the direct file system path of the image file
#SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
android.database.Cursor cursor = managedQuery(contentUri, proj,
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
class AddLoc extends AsyncTask<String, String, String> {
String hasil,success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddLocation.this);
pDialog.setMessage("Menyimpan...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
HttpUploader uploader = new HttpUploader();
try {
image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
} catch (InterruptedException e) {
Log.e("note1", "upload");
hasil="Interupasi terdapat kesalahan";
Log.e("kesalahan", hasil);
finish();
} catch (ExecutionException e) {
Log.e("note1", "upload2");
hasil="Eksekusi terdapat kesalahan";
Log.e("kesalahan", hasil);
finish();
}
return image_name;
}
protected void onPostExecute(String notifikasi) {
pDialog.dismiss();
Intent dash = new Intent(AddLocation.this,Dashboard.class);
startActivity(dash);
}
}
}

The culprit is most likely related to this line:
image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
You're firing an AsyncTask from inside another AsyncTask, and the first one blocks until the second is completed. But, from the documentation:
Starting with HONEYCOMB, tasks are executed on a single thread to
avoid common application errors caused by parallel execution.
Since the second task never gets to start (in Android >= 3.0), the first one never gets to finish.
You could fix this by using executeOnExecutor(THREAD_POOL_EXECUTOR)...
... but I would suggest changing your code. Since the first task does nothing (i/o, networking) that would need a background thread, that code can just run in the UI thread. Provide the second (now, only) task with a callback to call in onPostExecute() when it has the result. See android asynctask sending callbacks to ui for a good example of this pattern.
Using get() on AsyncTasks is rarely a good idea.

Related

How do I find nearby places in Android Studio and place them as markers?

I've been working on this for the past few days and have tried different codes, but none of them have worked so far. I'm trying to make an activity that takes the user's current location and displays nearby hospitals to them.
Here's the code I'm using (it's the 1 I found online that doesn't crash android studio):
activity_hospitals.java (The draw() function is where I place markers):
package com.example.mobileproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.maps.model.PlacesSearchResult;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class activity_hospitals extends FragmentActivity implements OnMapReadyCallback {
Toolbar mytoolbar;
GoogleMap Gmap;
FusedLocationProviderClient flsc;
public LatLng here;
public double longo, lato;
Button Test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospitals);
Test=findViewById(R.id.btnGet);
Test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if (here == null)
Toast.makeText(activity_hospitals.this, "Success!", Toast.LENGTH_SHORT).show();
else{
Toast.makeText(activity_hospitals.this, "Error", Toast.LENGTH_SHORT).show();
draw();
}
}
catch(Exception e){
}
}
});
mytoolbar = (Toolbar) findViewById(R.id.hospitalToolbar);
mytoolbar.setTitle("Hospitals Near You");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
flsc = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Gmap = googleMap;
}
public void draw(){
here = new LatLng(33.71456158807447, 35.48425016137045);
Gmap.addMarker(new MarkerOptions().position(here).title("Your Location").snippet("Your last recorded location"));
float zoomLevel = 11.0f; //This goes up to 21
Gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(here, zoomLevel));
double lat = here.latitude;
double lng = here.longitude;
StringBuilder sb = new StringBuilder("http://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+ 33.71456158807447 + "," + 35.48425016137045);
sb.append("&radius=1000");
sb.append("&types=hospital|health");
sb.append("&sensor=true");
sb.append("&key=" +getResources().getString(R.string.map_key));
String url=sb.toString();
Object dataFetch[] = new Object[2];
dataFetch[0] = Gmap;
dataFetch[1] = url;
FetchData fetchData = new FetchData();
fetchData.execute(dataFetch);
}
public void getLastLocation(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
flsc.getLastLocation().addOnSuccessListener(this, location -> {
if (location != null) {
longo = location.getLatitude();
lato = location.getLongitude();
here = new LatLng(lato, longo);
}
});
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 100){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
getLastLocation();
}
else{
Toast.makeText(this, "Required Permission", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
DownloadURL.java:
package com.example.mobileproject;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadURL {
public String retrieveUrl(String url) throws IOException {
String urlData="";
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
URL getUrl = new URL(url);
httpURLConnection = (HttpURLConnection) getUrl.openConnection();
httpURLConnection.connect();
inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer sb = new StringBuffer();
String line ="";
while((line = bufferedReader.readLine())!=null){
sb.append(line);
}
urlData = sb.toString();
bufferedReader.close();//////
}catch(Exception e){
Log.d("Exception", e.toString());
}finally{
inputStream.close();
httpURLConnection.disconnect();
}
return urlData;
}
}
FetchData.java:
package com.example.mobileproject;
import android.os.AsyncTask;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
public class FetchData extends AsyncTask<Object, String, String> {
String googleNearByPlacesData;
GoogleMap googleMap;
String url;
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsOnObject = jsonArray.getJSONObject(i);
JSONObject getLocation=jsOnObject.getJSONObject("geometry").getJSONObject("location");
String lat = getLocation.getString("lat");
String lng = getLocation.getString("lng");
JSONObject getName = jsonArray.getJSONObject(i);
String name = getName.getString("name");
LatLng latlng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.title(name);
markerOptions.position(latlng);
googleMap.addMarker(markerOptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Object... objects) {
try{
googleMap = (GoogleMap) objects[0];
url = (String) objects[1];
DownloadURL downloadURL = new DownloadURL();
googleNearByPlacesData = downloadURL.retrieveUrl(url);
} catch (IOException e) {
e.printStackTrace();
}
return googleNearByPlacesData;
}
}
I've also tried a different way using PlacesSearchResponse request = new PlacesSearchResponse(); that I found in a stackoverflow post. It also didn't crash the application, but it didn't work.

Android Studio Java JSON fetching data problem

PLEASE HELP, WHAT IS WRONG WITH MY CODE, IT DISPLAYS NOTHING BUT ZEROS AND NULL
I already search through tutorials, i even copied the whole code but i cant get the data from this API, my textviews on int are returning zeros and my textviews on string are returning null after a press the update button.
here is my api link = api link
here is the result
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView confirmed, recovered, deaths, country, date;
private RequestQueue mQueue;
private Button update;
private int c,r,d;
private String co,da;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirmed = findViewById(R.id.confirmed);
recovered = findViewById(R.id.recovered);
deaths = findViewById(R.id.deaths);
country = findViewById(R.id.country);
date = findViewById(R.id.date);
update = findViewById(R.id.update);
mQueue = Volley.newRequestQueue(this);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
confirmed.setText(String.valueOf(c));
recovered.setText(String.valueOf(r));
deaths.setText(String.valueOf(d));
country.setText(co);
date.setText(da);
}
});
}
private void jsonParse(){
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=Philippines";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("All");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject cases = jsonArray.getJSONObject(i);
c = cases.getInt("confirmed");
r = cases.getInt("recovered");
d = cases.getInt("deaths");
co = cases.getString("country");
da = cases.getString("updated");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
mQueue.add(request);
}
}
I don't know what is the problem here, can someone help
I already fixed it thank you so much.
my solution is I removed JsonArray.
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView confirmed, recovered, deaths, country, date;
private RequestQueue mQueue;
private Button update;
private int c,r,d;
private String co,da;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirmed = findViewById(R.id.confirmed);
recovered = findViewById(R.id.recovered);
deaths = findViewById(R.id.deaths);
country = findViewById(R.id.country);
date = findViewById(R.id.date);
update = findViewById(R.id.update);
mQueue = Volley.newRequestQueue(this);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=Philippines";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
//JSONArray jsonArray = response.getJSONArray();
for (int i = 0; i < response.length(); i++) {
JSONObject cases = response.getJSONObject("All");
c = cases.getInt("confirmed");
r = cases.getInt("recovered");
d = cases.getInt("deaths");
co = cases.getString("country");
da = cases.getString("updated");
confirmed.setText(String.valueOf(c));
recovered.setText(String.valueOf(r));
deaths.setText(String.valueOf(d));
country.setText(co);
date.setText(da);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
mQueue.add(request);
}
}
I replaced
JSONObject cases = jsonArray.getJSONObject(i);
with
JSONObject cases = response.getJSONObject("All");
and removed
JSONArray jsonArray = response.getJSONArray();
because it is not necessary.

latitude and longitude always return 0.0 when using lastKnownLocation

I just got the permissions handled through the library Let, but I still can't get a longitude and latitude in my android app. I'm using a service called GPS_Service.java. Also I'm not 100% sure my permissions aren't the issue. The call to the google API in GPS_Service still is underlined with the warning that it requires permissions which might be rejected. Is that supposed to go away even with third party libraries? Would this still be an issue because on my device the app has location permissions enabled?
here is my main activity:
package com.example.paxie.stormy.ui;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.canelmas.let.AskPermission;
import com.canelmas.let.DeniedPermission;
import com.canelmas.let.Let;
import com.canelmas.let.RuntimePermissionListener;
import com.canelmas.let.RuntimePermissionRequest;
import com.example.paxie.stormy.GPS_Service;
import com.example.paxie.stormy.R;
import com.example.paxie.stormy.weather.Current;
import com.example.paxie.stormy.weather.Day;
import com.example.paxie.stormy.weather.Forecast;
import com.example.paxie.stormy.weather.Hour;
import com.google.android.gms.maps.model.LatLng;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements RuntimePermissionListener {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
private Forecast mForecast;
private double mLatitude;
private double mLongitude;
private BroadcastReceiver broadcastReceiver;
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private Context mContext;
#BindView(R.id.timeLabel)
TextView mTimeLabel;
#BindView(R.id.temperatureLabel)
TextView mTemperatureLabel;
#BindView(R.id.humidityValue)
TextView mHumidityValue;
#BindView(R.id.precipValue)
TextView mPrecipValue;
#BindView(R.id.summaryLabel)
TextView mSummaryLabel;
#BindView(R.id.iconImageView)
ImageView mIconImageView;
#BindView(R.id.refreshImageView)
ImageView mRefreshImageView;
#BindView(R.id.progressBar)
ProgressBar mProgressBar;
#BindView(R.id.locationLabel)
TextView mLocationlabel;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Let.handle(this, requestCode, permissions, grantResults);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast();
}
});
getForecast();
Log.d(TAG, "Main UI code is running!");
}
private void getForecast() {
checkGPS();
String apiKey = "1621390f8c36997cb1904914b726df52";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + mLatitude + "," + mLongitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e)
{
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(this, "Network is currently unavailable!", Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mLocationlabel.setText(mLatitude + " " + mLongitude);
Current current = mForecast.getCurrent();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("At " + current.getFormattedTime() + " it will be:");
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ContextCompat.getDrawable(this, current.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrent(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonDay = data.getJSONObject(i);
Day day = new Day();
day.setSummary(jsonDay.getString("summary"));
day.setIcon(jsonDay.getString("icon"));
day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
day.setTime(jsonDay.getLong("time"));
day.setTimeZone(timezone);
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getDouble("temperature"));
hour.setIcon(jsonHour.getString("icon"));
hour.setTime(jsonHour.getLong("time"));
hour.setTimeZone(timezone);
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current();
current.setHumidity(currently.getDouble("humidity"));
current.setTime(currently.getLong("time"));
current.setIcon(currently.getString("icon"));
current.setPrecipChance(currently.getDouble("precipProbability"));
current.setSummary(currently.getString("summary"));
current.setTemperature(currently.getDouble("temperature"));
current.setTimeZone(timezone);
Log.d(TAG, current.getFormattedTime());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
#OnClick(R.id.hourlyButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
startActivity(intent);
}
#AskPermission({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
private void checkGPS() {
GPS_Service gps_service = new GPS_Service(this);
gps_service.getLocation();
mLatitude = gps_service.getLatitude();
mLongitude = gps_service.getLongitude();
}
#Override
public void onShowPermissionRationale(List<String> permissionList, RuntimePermissionRequest permissionRequest) {
}
#Override
public void onPermissionDenied(List<DeniedPermission> deniedPermissionList) {
}
}
And here is my GPS_Service.java:
package com.example.paxie.stormy;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
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.IBinder;
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.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.canelmas.let.AskPermission;
import com.canelmas.let.DeniedPermission;
import com.canelmas.let.Let;
import com.canelmas.let.RuntimePermissionListener;
import com.canelmas.let.RuntimePermissionRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import java.util.ArrayList;
import java.util.List;
/**
* Created by paxie on 10/27/16.
*/
public class GPS_Service extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
private static final int RC_GPS_PERMS = 124;
public String[] perm = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
public GPS_Service(Context c) {
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void getLocation() {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In that case enable your GPS and go to google maps and hit the location button, wait until google maps locate u and then go back and test in ur app. This should work because if u are using the first time ur phone without never been conected to GPS it gives u that problem
It is looking for specifically "LastKnownLocation", I had this issue as well. Move about 3 meters and try again. If there is no 'last known location' then it sends a null value.
What I did was set a few if statements for my application. If the GPS Provider was spitting out null values, then use the Network Provider location coordinates, and if that was spitting out null values then I just displayed a message saying "To Wait" or "Try again later". Eventually your GPS Provider will pick up location values after it has been activated for a while.
newLoc = _locationManager.GetLastKnownLocation(_locationProvider);
if (newLoc != null)
{
_latitudeUser = newLoc.Latitude;
_longitudeUser = newLoc.Longitude;
_locationText.Text = string.Format("{0:f6},{1:f6}", newLoc.Latitude, newLoc.Longitude);
}
else
{
_locationProvider = LocationManager.NetworkProvider;
newLoc = _locationManager.GetLastKnownLocation(_locationProvider);
if (newLoc != null)
{
_latitudeUser = newLoc.Latitude;
_longitudeUser = newLoc.Longitude;
_locationText.Text = string.Format("{0:f6},{1:f6}", newLoc.Latitude, newLoc.Longitude);
}
else
{
_locationText.Text = string.Format("We currently cannot determine your location, please try again later.");
}

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

Android Java Error OutOfMemory

currently I am developing an Android Application (Native). In my application, I need to load many images and that cause a problem.
The problem is:
1. When I first open the app after deploy it on my android phone, it works fine. However, after I close the application (by clicking the back button), and then I open the application again, the app closed unexpectedly. When I check the logcat, I found out that it was closed because of OutOfMemory error.
2. Second problem: after I open my application, and I go to the next page, it also give me OutOfMemory error.
I guess, the problem occur because I load too many images. After I do some searching on the internet, it suggest me to do System.gc
But unfortunately, it did not work for me.
Here is my code:
Homepage_Activity.java
package dev.com.friseur;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.friseur.insert.AddComment;
import dev.friseur.rest.Photo;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class HomePage extends ActionBarActivity {
private String p_id = "1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Intent intent = getIntent();
int size = Integer.parseInt(intent.getStringExtra("size")) * 2;
LinearLayout hp = (LinearLayout)findViewById(R.id.homepage);
Photo photo = new Photo(hp, this, size);
photo.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The photo.execute() code will call an asynchronous task. Here it is:
package dev.friseur.rest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.com.friseur.RecognizeFace;
import dev.com.friseur.ViewPhoto;
import dev.friseur.insert.AddComment;
import dev.friseur.insert.AddLike;
import android.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.SystemClock;
import android.text.InputFilter;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Photo extends AsyncTask<String, Void, String>{
private Context context;
private LinearLayout homepage;
private int size;
private String sessionUname;
private String sessionUserid;
private File file;
private ArrayList<String> photo_id;
private ArrayList<String> imageName;
private ArrayList<String> date_upload;
private ArrayList<String> url_original;
private ArrayList<String> url_with_hair;
private ArrayList<String> caption;
private ArrayList<String> user_id;
private ArrayList<String> username;
private ArrayList<JSONArray> comments;
private ArrayList<Integer> totalcomment;
public Photo(LinearLayout homepage, Context context, int size){
this.context = context;
this.homepage = homepage;
this.size = size;
this.sessionUname = "testuser";
this.sessionUserid = "1";
photo_id = new ArrayList<String>();
imageName = new ArrayList<String>();
date_upload = new ArrayList<String>();
url_original = new ArrayList<String>();
url_with_hair = new ArrayList<String>();
caption = new ArrayList<String>();
user_id = new ArrayList<String>();
username = new ArrayList<String>();
comments = new ArrayList<JSONArray>();
totalcomment = new ArrayList<Integer>();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.43.8:8080/FriseurRest/WebService/GetPhotos");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
int i = 0;
while ((line = reader.readLine()) != null) {
JSONObject json_data = new JSONObject(line);
photo_id.add(json_data.getString("p_id"));
imageName.add(json_data.getString("imagename"));
date_upload.add(json_data.getString("date_upload"));
url_original.add(json_data.getString("url_original"));
url_with_hair.add(json_data.getString("url_with_hair"));
caption.add(json_data.getString("caption"));
user_id.add(Integer.toString(json_data.getInt("user_id")));
username.add(json_data.getString("username"));
comments.add(json_data.getJSONArray("photoComments"));
totalcomment.add(json_data.getInt("total_comment"));
i++;
}
is.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onDestroy() {
System.gc();
Runtime.getRuntime().gc();
}
protected void onPostExecute(String p_id) {
for(int i = 0; i < imageName.size(); i++){
final int j = i;
LinearLayout photo = new LinearLayout(context);
photo.setOrientation(LinearLayout.VERTICAL);
photo.setPadding(0, 0, 0, 50);
LinearLayout postdesc = createPostDesc(i);
file = new File(Environment.getExternalStorageDirectory() + "/" + url_original.get(i), imageName.get(i));
Uri imgUri = Uri.fromFile(file);
ImageView img = new ImageView(context);
img.setImageURI(imgUri);
img.setMaxWidth(size);
img.setMinimumWidth(size);
img.setMaxHeight(size);
img.setMinimumHeight(size);
TextView tv = new TextView(context);
tv.setText(caption.get(i));
final LinearLayout showcomment = new LinearLayout(context);
showcomment.setOrientation(LinearLayout.VERTICAL);
showcomment.setPadding(0, 10, 0, 10);
try {
if(totalcomment.get(i) > 5){
LinearLayout more = new LinearLayout(context);
more.setPadding(0, 0, 0, 5);
TextView viewmore = new TextView(context);
viewmore.setTextColor(Color.GRAY);
viewmore.setText("View More Comments");
viewmore.setClickable(true);
viewmore.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, ViewPhoto.class);
intent.putExtra("size", size);
intent.putExtra("p_id", photo_id.get(j));
intent.putExtra("imageName", imageName.get(j));
intent.putExtra("date_upload", date_upload.get(j));
intent.putExtra("url_original", url_original.get(j));
intent.putExtra("url_with_hair", url_with_hair.get(j));
intent.putExtra("caption", caption.get(j));
intent.putExtra("user_id", user_id.get(j));
intent.putExtra("username", username.get(j));
context.startActivity(intent);
}
});
more.addView(viewmore);
showcomment.addView(more);
}
for(int k = 0; k < comments.get(i).length(); k++) {
//ArrayList<String> photoCom = comments.get(k);
//int userCom = photoCom.length();
JSONObject photoCom = comments.get(i).getJSONObject(k);
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(photoCom.getString("com_username"));
TextView showcom = new TextView(context);
showcom.setText(photoCom.getString("com_desc"));
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
} catch (Exception e) {
}
LinearLayout addcomment = createAddComment(i);
final EditText et_comment = new EditText(context);
et_comment.setHint("Add Comment");
et_comment.setMaxWidth(size*3/4);
et_comment.setMinimumWidth(size*3/4);
int maxLength = 150;
et_comment.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
Button button_comment = new Button(context);
button_comment.setText("Post");
button_comment.setTextSize(15);
button_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String com = et_comment.getText().toString();
try{
AddComment ac = new AddComment(sessionUserid, com, photo_id.get(j));
ac.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(sessionUname);
TextView showcom = new TextView(context);
showcom.setText(com);
showcom.setAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in));
et_comment.setText("");
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
});
addcomment.addView(et_comment);
addcomment.addView(button_comment);
addcomment.setVisibility(View.GONE);
LinearLayout social = createSocialFeature(i, addcomment, et_comment);
photo.addView(postdesc);
photo.addView(img);
photo.addView(tv);
photo.addView(showcomment);
photo.addView(social);
photo.addView(addcomment);
homepage.addView(photo);
}
}
private LinearLayout createPostDesc(int i){
LinearLayout postdesc = new LinearLayout(context);
postdesc.setOrientation(LinearLayout.VERTICAL);
postdesc.setMinimumHeight(40);
TextView uname = new TextView(context);
uname.setText("#"+username.get(i));
TextView timeupload = new TextView(context);
timeupload.setText(date_upload.get(i));
if(i>0){
View separator = new View(context);
separator.setMinimumHeight(1);
separator.setBackgroundColor(Color.BLACK);
separator.setPadding(0, 10, 0, 0);
postdesc.addView(separator);
}
postdesc.addView(uname);
postdesc.addView(timeupload);
return postdesc;
}
private LinearLayout createSocialFeature(final int i, final LinearLayout addcomment, final EditText et_comment){
LinearLayout social = new LinearLayout(context);
social.setOrientation(LinearLayout.HORIZONTAL);
social.setMinimumHeight(40);
social.setPadding(0,10,10,0);
TextView tv_comment = new TextView(context);
tv_comment.setText("Add Comment");
tv_comment.setPadding(0, 0, 15, 0);
tv_comment.setClickable(true);
tv_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addcomment.setVisibility(View.VISIBLE);
et_comment.setFocusableInTouchMode(true);
et_comment.setFocusable(true);
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
}
});
final TextView tv_like = new TextView(context);
tv_like.setText("Like");
tv_like.setClickable(true);
tv_like.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String like = tv_like.getText().toString();
try{
AddLike lk = new AddLike(sessionUserid, like, photo_id.get(i));
lk.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if(like.equals("Like")){
tv_like.setText("Unlike");
}
else{
tv_like.setText("Like");
}
}
});
social.addView(tv_comment);
social.addView(tv_like);
return social;
}
private LinearLayout createAddComment(int i){
LinearLayout addcomment = new LinearLayout(context);
addcomment.setId(Integer.parseInt(photo_id.get(i)));
addcomment.setOrientation(LinearLayout.HORIZONTAL);
addcomment.setPadding(0,20,0,0);
return addcomment;
}
}
This asynchronous task used to call the rest service.
What is wrong with my code? And how can I solve the OutOfMemory error. Any help would be appreciated. Thanks in advance
You can use lazyloading to fix this and follow this url for lazy loading:
https://github.com/nostra13/Android-Universal-Image-Loader
You can see my answer here.It will be useful to handle your bitmap efficiently.
How to make application more responsive which uses several bitmaps?

Categories