I try to run the following code, but android studio keeps saying there are problems with saving string objects, but as far as I know the code was written correctly. Can anyone see where the problem is and help me fix it?
I have way more problems with the android studio after the latest update, so I have difficulty figuring out whether the problems are due to my code being wrong somewhere or the update.
Error:(90, 37) error: no suitable constructor found for Intent(CityWeatherData,Class) constructor Intent.Intent(String,Uri) is not applicable (argument mismatch; CityWeatherData cannot be converted to String) constructor Intent.Intent(Context,Class) is not applicable (argument mismatch; CityWeatherData cannot be converted to Context)
Error:(95, 13) error: cannot find symbol method startActivity(Intent)
Error:Execution failed for task ':app:compileDebugJavaWithJavac'. > Compilation failed; see the compiler error output for details.
I have a class that gets data from OpenWeatherMap as JSON objects and displays them in an Activity.
Non-activity class:
public class CityWeatherData extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = ""; //JSON data will be kept here when first downloaded
URL url;
HttpURLConnection urlConnection = null;
//API set up in OpenWeatherMap
//Try and catch used in case user does not have internet connection etc.
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream input = urlConnection.getInputStream();
//Reader to read inputStream for URL
InputStreamReader inputReader = new InputStreamReader(input);
int data = inputReader.read(); //Data from stream is put into an int called data
//When data finishes reading = -1 ; There for while loop need for data not equal to -1
while (data != -1){
char current = (char) data;
result += current;
data = inputReader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Create JSON object from result
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject weatherData = new JSONObject(jsonObject.getString("main"));
//The data we are interesed in is located after "main"
//Get temp from main
double temp = Double.parseDouble(weatherData.getString("temp"));
//Temp is given i Kelvin so it needs to be converted to Celcius
int tempInt = (int) (temp -273.15);
//Get city name
String placeName = jsonObject.getString("name");
//Get description
String weatherDescription = jsonObject.getString("description");
//Get humidity
double humidityValue = Double.parseDouble(weatherData.getString("humidity"));
Intent sendDataIntent = new Intent(CityWeatherData.this, CityDetailsActivity.class);
sendDataIntent.putExtra("tempData", tempInt);
sendDataIntent.putExtra("cityNameData", placeName);
sendDataIntent.putExtra("humidityData", humidityValue);
sendDataIntent.putExtra("descriptionData", weatherDescription);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Activity class:
public class CityDetailsActivity extends AppCompatActivity {
String placeName;
int tempInt;
double humidityValue;
String weatherDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_details);
Bundle getData = getIntent().getExtras();
if (getData !=null){
int tempInt = getData.getInt("tempData");
String placeName = getData.getString("cityNameData");
double humidityValue = getData.getDouble("humidityData");
String weatherDescription = getData.getString("descriptionData");
}
}
#Override
protected void onResume() {
super.onResume();
// Update with info from ShowData
updateFields();
}
private void updateFields(){
// Used to show data
TextView city_name = findViewById(R.id.city_name);
city_name.setText(placeName);
TextView temp = findViewById(R.id.temp);
temp.setText(String.valueOf(tempInt));
TextView humidity = findViewById(R.id.humidity);
humidity.setText(String.valueOf(humidityValue));
TextView show_description = findViewById(R.id.show_description);
show_description.setText(weatherDescription);
}
//Save current data in activity upon rotation
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Your AsyncTask is taking in parameters without actually launching the activity.
Edit: Using weak reference for activity context.
private static class CityWeatherData extends AsyncTask<String,Void,String> {
private WeakReference<MainActivity> mainActivity;
public CityWeatherData(MainActivity context) {
mainActivity = new WeakReference<>(context);
}
#Override
protected String doInBackground(String... urls) {
....
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
MainActivity cxt = mainActivity.get();
if (cxt != null) {
//Create JSON object from result
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject weatherData = new JSONObject(jsonObject.getString("main"));
//The data we are interesed in is located after "main"
//Get temp from main
double temp = Double.parseDouble(weatherData.getString("temp"));
//Temp is given i Kelvin so it needs to be converted to Celcius
int tempInt = (int) (temp -273.15);
//Get city name
String placeName = jsonObject.getString("name");
//Get description
String weatherDescription = jsonObject.getString("description");
//Get humidity
double humidityValue = Double.parseDouble(weatherData.getString("humidity"));
Intent sendDataIntent = new Intent(cxt, CityDetailsActivity.class);
sendDataIntent.putExtra("tempData", tempInt);
sendDataIntent.putExtra("cityNameData", placeName);
sendDataIntent.putExtra("humidityData", humidityValue);
sendDataIntent.putExtra("descriptionData", weatherDescription);
startActivity(sendDataIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am trying to get the response of a servlet as text, to parse this text and extract the coordinates for showing markers on google maps. My problem is that I don't know how to call the result from onPostExecute method in the onMapReady method. Like I'm calling in my code, the input String is obviously empty.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap map;
private static final String LOG_TAG = "ExampleApp";
TextView tvIsConnected;
TextView tvResult;
TextView textView2;
private static final String SERVICE_URL = "http://192.168.178.42:8080/TutorialApp/User/GetAll";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
tvResult = (TextView) findViewById(R.id.tvResult);
textView2 = (TextView) findViewById(R.id.textView2);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (checkNetworkConnection())
// perform HTTP GET request
new HTTPAsyncTask().execute("http://192.168.178.42:8080/TutorialApp/User/GetAll");
}
public boolean checkNetworkConnection() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
boolean isConnected = false;
if (networkInfo != null && (isConnected = networkInfo.isConnected())) {
// show "Connected" & type of network "WIFI or MOBILE"
tvIsConnected.setText("Connected " + networkInfo.getTypeName());
// change background color to red
tvIsConnected.setBackgroundColor(0xFF7CCC26);
} else {
// show "Not Connected"
tvIsConnected.setText("Not Connected");
// change background color to green
tvIsConnected.setBackgroundColor(0xFFFF0000);
}
return isConnected;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line + "\n";
inputStream.close();
return result;
}
private String HttpGet(String myUrl) throws IOException {
InputStream inputStream = null;
String result = "";
URL url = new URL(myUrl);
// create HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// make GET request to the given URL
conn.connect();
// receive response as inputStream
inputStream = conn.getInputStream();
// convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
return result;
}
private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return HttpGet(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
//onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
tvResult.setText(result);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
String input = tvResult.getText().toString();
String[] lines = input.split( "\n" );
List<Pair<Double, Double>> list = new ArrayList<>();
String ss="i";
for( int i =1; i < lines.length-1; i++ ) {
int firstcomma = lines[i].indexOf(",");
int secondcomma = lines[i].indexOf(",", firstcomma + 1);
int thirdcomma = lines[i].indexOf(",", secondcomma + 1);
Double lat = Double.parseDouble(lines[i].substring(secondcomma + 1, thirdcomma));
Double longitude = Double.parseDouble(lines[i].substring(thirdcomma + 1, lines.length));
list.add(new Pair(lat,longitude));
}
for(int j=1; j<list.size();j++) {
map = googleMap;
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
LatLng sydney = new LatLng(list.get(j).first, list.get(j).second);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
}
The reason you can't call the result of onPostExecute() in onMapReady() is because they are both running in the background. The only thing that you can really do here is either call getMapAsync() from your onPostExecute(), which will ensure that your onPostExecute() has completed; or, move the functionality of the onMapReady() into the onPostExecute(). You basically have 2 asyncTasks running, so you either need to chain them (which is kind of hacky) or move the logic from onMapReady() to onPostExecute().
EDIT: Found the solution to my problem.
The json string output returned the wrong url for my local images.
i am barely new to android and struggle with asyncTask.
What i want is to get the corresponding image to a marker on a map.
every entry on this map has its own image which has to be loaded from server via json.
the image load works fine but i dont get the right workflow to get the image i need for one entry.
by now i have one solution to load an async task in a for-loop, but this cant be the right way because the app refuses to go on after 43 tasks and stops with
"ECONNECTION TIMEOUT"
so how can get the asynctask out of the loop?
hope anyone can help? thank you!
here is my code:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
public class MapImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
String url, userId, contentId, title;
LatLng location;
BufferedReader reader = null;
public MapImageLoadTask(String url, String userId, String contentId, String title, LatLng location) {
this.url = url;
this.userId = userId;
this.contentId = contentId;
this.title = title;
this.location = location;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(title).position(location).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
hashMap.put(m, contentId);
}
}
}
Your problem maybe AsyncTask limitations. In android.os.AsyncTask.java you will see core size and blockingqueue size(128), should use counter for asynctask and debug it(Problem is, lots of async tasks or other).
AsyncTask.java
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
...}
Change Your Code Use Buffer(RequestData) And Use Only One Async Task. Update Market instance every publishProgress in onProgressUpdate
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
List<RequestData> datas = new ArrayList<RequestData>();
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
RequestData data = new RequestData();
data.url = "http://192.168.63.35:1234/rest_app_users/getImage/";
data.userId = userId;
data.contentId = contentId;
data.contentTitle = contentTitle;
data.latlng = latlng;
datas.add(data);
//new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
new MapImageLoadTask(datas).execute();
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
static class RequestData{
public String url;
public String userId;
public String contentId;
public String contentTitle;
public LatLng latLng;
public Bitmap bmp;
}
public class MapImageLoadTask extends AsyncTask<Void, RequestData, Void> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
BufferedReader reader = null;
List<RequestData> dataSet;
public MapImageLoadTask(List<RequestData> dataSet) {
this.dataSet = dataSet;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
for(RequestData item : dataSet){
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//
item.bmp = bmp;
publishProgress(item);
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPublishProgress(RequestData item){
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(item.title).position(item.location).icon(BitmapDescriptorFactory.fromBitmap(item.bmp)));
hashMap.put(m, contentId);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
This problem may sound a little weird, but whenever I run the app it crashes and when I change the name of LatLang variable in the function private LatLng getCurrentLocation(), It starts working. But when I change anything(even in any other file) it crashes and I have to keep changing the variable names to keep it running.
I am sure of the problem, it is something related to LatLang variable.
GetApproxTimeMaps.java
public class GetApproxTimeMaps extends FragmentActivity {
private static double destiLatitude;
private static double destiLongitude;
GoogleMap mMap;
GMapV2Direction md;
LatLng userLocation;
LatLng destination;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_approx_time_maps);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
userLocation = getCurrentLocation();
double lati = userLocation.latitude;
double longi = userLocation.longitude;
JSONObject jasonObject = getLocationInfo("Infosys");
boolean value = getLatLong(jasonObject);
System.out.println("value is: "+ value);
destination = new LatLng(destiLatitude, destiLongitude);
System.out.println("destination latitude :" + destiLatitude);
System.out.println("destination longitude :" + destiLongitude);
md = new GMapV2Direction();
mMap = ((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
double toZoomLat = (destination.latitude + userLocation.latitude)/2;
double toZoomLon = (destination.longitude + userLocation.longitude)/2;
LatLng coordinates = new LatLng(toZoomLat, toZoomLon);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 12));
mMap.addMarker(new MarkerOptions().position(userLocation).title("Start"));
mMap.addMarker(new MarkerOptions().position(destination).title("End"));
Document doc = md.getDocument(userLocation, destination, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
System.out.println(duration);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.BLUE);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
private LatLng getCurrentLocation(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userlocat = new LatLng(location.getLatitude(),location.getLongitude());
return userlocat;
}
public static JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
public static boolean getLatLong(JSONObject jsonObject) {
try {
destiLongitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
destiLatitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
return true;
}
In my android application I need to parse JSON. From one website I take this JSON. I want to parse an array 'words' in this JSON and set it to one TextView. I am little bit confused. Can any way show me right way and check my code. Thanks for any help!
JSON:
MainActivity.java
GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_location.xml
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
mGoogleMap = mSupportMapFragment.getMap();
// Enabling MyLocation Layer of Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = mLocationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = mLocationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
mLocationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng mLatLng = new LatLng(latitude, longitude);
//Add Marker to current location of devise
//mGoogleMap.addMarker(new MarkerOptions().position(mLatLng).title("Geolocation system").snippet("Your last current location which was available!").icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location)));
// Showing the current location in Google Map
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
// Show Zoom buttons
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
// Turns on 3D buildings
mGoogleMap.setBuildingsEnabled(true);
// Zoom in the Google Map
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//Convert double to String
String mLatitude = Double.toString(latitude);
String mLongitude = Double.toString(longitude);
// URL of what3words service
String w3w_URL = "http://api.what3words.com/position?key=" + w3w_API_KEY + "&position=" + mLongitude + "," + mLatitude;
String json = null;
try {
json = readUrl(w3w_URL);
} catch (Exception e) {
e.printStackTrace();
}
JSONResponse response = new Gson().fromJson(json, JSONResponse.class);
String[]words = response.getWords();
TextView positionWords = (TextView) findViewById(R.id.location_information);
positionWords.setText(Arrays.toString(words).replaceAll("\\[|\\]", ""));
}
private String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
JSONResponse.java:
public class JSONResponse {
private String[] words;
long position;
public String[] getWords() {
return words;
}
public void setWords(String[] words) {
this.words = words;
}
public long getPosition() {
return position;
}
public void setPosition(long position) {
this.position = position;
}
}
Logcat error:
04-05 19:56:33.905 21272-21272/ua.com.what3wordsexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at ua.com.what3wordsexample.MainActivity$1.success(MainActivity.java:31)
at ua.com.what3wordsexample.MainActivity$1.success(MainActivity.java:27)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5454)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
You can use https://code.google.com/p/google-gson/
Use something like that
User user = new Gson().fromJson(userJSON, User.class);
Update:
public class Response {
private String[] words;
private Position position;
private String language;
public String[] getWords() {
return words;
}
public void setWords(String[] words) {
this.words = words;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
Finally:
Response response = new Gson().fromJson(String_response_from_server, Response.class);
String_response_from_server - it's your String response from server, in your code it's
json = mStringBuilder.toString();
After that you can easily get needed information
String[]words = response.getWords()
Update2
private String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
Usage:
String json = readUrl("http://api.what3words.com/position?key=YOURAPIKEY&position=" + mLongitude + "," + mLatitude);
Response response = new Gson().fromJson(json, Response.class);
P.S. I can't see what contains your position array so I puted some class Position, if there are the same values like in words you can replase it with String[] position;