How to show nearby locations from current location android studio? - android-studio

I have been trying to display nearby locations from my current location. But when i run it and click the button to view the nearby locations nothing appears. The first time i ran it, it displayed but when i backed out and came back in, it didnt display anything. i tried cleaning the project and other methods.
this is the method in my main class:
public void findRestaurants(View v){
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
stringBuilder.append("location="+latLngCurrent.latitude + "," +latLngCurrent.longitude);
stringBuilder.append("&radius="+5000);
stringBuilder.append("&keyword="+"restaurant");
stringBuilder.append("&key="+getResources().getString(R.string.google_map_keyy));
String url = stringBuilder.toString();
Object dataTransfer[] = new Object[2];
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
}
public class getNearbyPlaces extends AsyncTask<Object,String,String> {
GoogleMap mMap;
String url;
InputStream is;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String data;
#Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
try {
URL myurl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) myurl.openConnection();
httpURLConnection.connect();
is = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
stringBuilder = new StringBuilder();
while((line = bufferedReader.readLine() ) != null){
stringBuilder.append(line);
}
data = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject parentObject = new JSONObject(s);
JSONArray resultsArray = parentObject.getJSONArray("results");
for (int i = 0; i<resultsArray.length(); i++){
JSONObject jsonObject = resultsArray.getJSONObject(i);
JSONObject locationObj = jsonObject.getJSONObject("geometry").getJSONObject("location");
String latitude = locationObj.getString("lat");
String longitude = locationObj.getString("lng");
JSONObject nameObject = resultsArray.getJSONObject(i);
String name_restaurant = nameObject.getString("name");
String vicinity = nameObject.getString("vicinity");
LatLng latLng = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
MarkerOptions markeroptions = new MarkerOptions();
markeroptions.title(vicinity);
markeroptions.position(latLng);
mMap.addMarker(markeroptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
it worked the first time when i lunched it. Did i do something wrong?

hope you are doing fine. Can you replace the lines
new getNearbyPlaces().execute(dataTransfer);
instead of these 2 lines
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
I am not sure whether this is going to impact much, but this is the way AsyncTask class should be called.
If this is not working, can you share the entire code of this java page, so we can look at how findRestaurant() method is called.

Related

How do I maintain my app running and doing the same thing without the app´s window opened?

It's probably pretty obvious, but I'm completely new to programming or asking a question at stackoverflow, so I apologize in advance if I can't explain myself properly. Also, there are some parts I have no idea what they are for anymore since the code is basically a mix of tutorials.
What I need the app to do is for it to keep doing what it's doing (the handler part), but while it's is closed (not minimized). But instead of changing the background, I need it to send a notification instead.
In other words, every 10 minutes, if the value of temperBU is 19, I get a notification even if the app is closed.
For that, if I'm not mistaken, what I need is a service, but I don't understand what type is better for this situation. I tried some tutorials, but nothing seems to work, and if it's possible to start the service as soon as the app gets started.
public class MainActivity extends AppCompatActivity {
ConstraintLayout layout;
class Weather extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... address) {
try {
URL url = new URL(address[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
String content = "";
char ch;
while (data != -1) {
ch = (char) data;
content = content + ch;
data = isr.read();
}
Log.i("Content", content);
return content;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String content;
Weather weather = new Weather();
{
{
try {
content = weather.execute("https://api.openweathermap.org/data/2.5/weather?q=budapest,hu&units=metric&appid=ce2fd10cdcc8ab209f979f6a41c27cfe").get();
JSONObject jsonObject = new JSONObject(content);
String mainData = jsonObject.getString("main");
Log.i("mainData", mainData);
JSONObject object = new JSONObject(mainData);
Double temp = object.getDouble("temp");
Log.i("temp", String.valueOf(temp));
int temperBU = (int) Math.round(temp);
Log.i("temperBU", String.valueOf(temperBU));
layout = findViewById(R.id.hs_n);
if (temperBU == 19)
layout.setBackgroundResource(R.drawable.hungry_summer_premium_yes_simple);
else layout.setBackgroundResource(R.drawable.hungry_summer_premium_no_simple);
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
String content;
Weather weather = new Weather();
try {
content = weather.execute("https://api.openweathermap.org/data/2.5/weather?q=budapest,hu&units=metric&appid=ce2fd10cdcc8ab209f979f6a41c27cfe").get();
JSONObject jsonObject = new JSONObject(content);
String mainData = jsonObject.getString("main");
Log.i("mainData", mainData);//*
JSONObject object = new JSONObject(mainData);
Double temp = object.getDouble("temp");
Log.i("temp", String.valueOf(temp));
int temperBU = (int) Math.round(temp);
Log.i("temperBU", String.valueOf(temperBU));//*
layout = findViewById(R.id.hs_n);
if (temperBU == 19)
layout.setBackgroundResource(R.drawable.hungry_summer_premium_yes_simple);
else
layout.setBackgroundResource(R.drawable.hungry_summer_premium_no_simple);
} catch (Exception e) {
e.printStackTrace();
}
handler.postDelayed(this::run, 600000);
}
};
handler.postDelayed(r, 600000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Thank you so much for the help.
Please note that AsyncTask is deprecated, so use the following to do a background work:
Android AsyncTask API deprecating in Android 11.What are the alternatives?
In order to continue doing something after the user closed your app try using foreground service, like this:
in Android manifest, add
uses-permission android:name="android.permission.FOREGROUND_SERVICE"
this inside the application tag:
service android:name=".services.WorkerSvc"
add this class:
class WorkerSvc : Service() {
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
LogUtil.i("onStartCommand")
startForeground(
NotificationUtil.NOTIFICATION_ID,
NotificationUtil.makeForeGroundNotification(getString(R.string.please_wait))
)
processIntent(intent)
return START_STICKY
}
private fun processIntent(intent: Intent?) {
if (intent == null) {
stopSelf()
} else {
// DO YOUR WORK HERE. USE INTENT EXTRAS TO PASS DATA TO SERVICE
// NOTE THIS IS EXECUTED IN MAIN THREAD SO USE ONE OF THE SOLUTION PROVIDED IN A LINK ABOVE
}
}
}
To start the service:
val svcIntent = Intent(App.instance, WorkerSvc::class.java)
svcIntent.putExtra(
//DATA TO PASS TO SERVICE
)
if (context != null) {
ContextCompat.startForegroundService(context, svcIntent)
}

Not recieving any response from Volley

I am not getting virtually any response.
This is for a school project, i am not getting any response from volley what so ever, please help.
I've tried different versions of Volley, I've tried adding internet access to the manifest, no help.
RequestQueue queue = Volley.newRequestQueue(this);
api();
public void api(){
String new_url = "http://api.myjson.com/bins/kp9wz";
System.out.println(new_url);
final JsonObjectRequest request = new
JsonObjectRequest(Request.Method.GET, new_url, null, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("employees");
devices = new ArrayList<>();
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String deviceId = jsonObject.getString("firstname");
String deviceName = jsonObject.getString("age");
String deviceStatus = jsonObject.getString("mail");
System.out.println(jsonObject.getString("firstname"));
System.out.println(jsonObject.getString("age"));
System.out.println(jsonObject.getString("mail"));
devices.add(new
Device(deviceName,deviceStatus,deviceId));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("WTF");
}
});
}
´´´
I don't get anything
I expect it to save the data into the arraylist and sout, each field in the for loop
I was stupid enough to not att the request to a RequestQueue, I've solved it.

AndroidStudio about HttpURLConnection

This is my method!
private String logInActivity() {
String userID = idText.getText().toString();
String userPW = pwText.getText().toString();
final String SERVER = "http://115.145.241.151:8080/AndroidCommunication/LoginActivity.jsp";
if (userID != null && userPW != null) {
final String QUERY = "?id=" + userID + "&pw=" + userPW;
HttpURLConnection connection = null;
URL url = null;
try {
url = new URL(SERVER+QUERY);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
return line;
} catch (Exception e) {
e.printStackTrace();
return "3";
}
} else {
Toast.makeText(GetReview.this, "Type all required info", Toast.LENGTH_SHORT).show();
return "2";
}
}
I'm just practicing HttpURLConnection( by GET METHOD). I know i shouldn't send passwords or ids like this way but i'm just practicing my exercise. But I just don't get why this goes to an Exception. Please help!
I didn't type my addresses or anything wrong because I tried it, and server was on. I debugged it and the connection.connect(); doesn't seems to work.
my onCreate goes:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_review);
pwText = findViewById(R.id.pwText);
idText = findViewById(R.id.idText);
resultText = findViewById(R.id.resultText);
findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAsyncTask().execute(logInActivity());
}
});
}
The problem is that issuing HTTP requests on the main thread is not allowed by android. That's why you are receiving a NetworkOnMainThreadException exception. To resolve this, you can use an IntentService to do that job for you and then broadcast the results back to the receiver (your activity).
If you don't know much about android Services, then have a read in the documentation, you'll find yourself using them time and time again...
https://developer.android.com/guide/components/services#CreatingAService

What can i do to use httpclient method in android studio.

I am using HttpClient and defaultHttpClient Methods in getInternetData function on android studi. but these methods are no longer part of the SDK 23. how can i overcome this problem.i have used dependencies in build.gradle too , but still error remains here. Kindly tell me are there any other methods to call.?
public class GetMethodEx {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://api.twitter.com/1/statuses/public_timeline.json");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}

getPostDataString(java.util.HashMap<java.lang.String,java.lang.String>) cannot be applied to (java.util.HashMap<java.lang.String,java.lang.String>[])

I'm trying to post to a server via Asynchronous Task and while converting Hashmap to String, this error occurred. What does that Error mean. Why does it occour ? How do I resolve this ?
here is my code:
public class NetworkAccess extends AsyncTask<HashMap<String,String>,Void,String> {
private URL url;
private HttpURLConnection con;
private OutputStream os;
#Override
protected String doInBackground(HashMap<String, String>... vals) {
String response = "";
try {
url = new URL("http://192.168.0.3/chow/user-login.php");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setConnectTimeout(1000);
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String pd = getPostDataString(vals); //Error
writer.write(pd);
writer.flush();
writer.close();
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(bis));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
response = total.toString();
}
catch (Exception e){
e.printStackTrace();
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
The error which you got shows that you're directly trying to create a array of HashMap, rather you can create just Array of String, iterate the Collection and insert the HashMap objects into it.
Inside the getPostDataString(), change the code to
StringBuilder[] sb = new StringBuilder[100];
and check if it works.

Resources