Not recieving any response from Volley - android-studio

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.

Related

How to show nearby locations from current location 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.

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)
}

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

How do I create a Windows Service using Threading and multiple HttpWebRequest async calls?

I need help with creating a windows service using Threading and asynchronous HttpWebRequest calls. I have created a few C# windows services before but never using threading. Also, I seem to be getting hung up with the async calls using HttpWebRequest. I have googled this as well as looking on this site. I could not find anything that helped. This is mainly because I could not seem to get what was presented in other questions to work in my specific example.
Please keep in mind that I may be overlapping things based on my lack of knowledge in this specific area as well as through trying to figure it out.
The main flow of this is to get a list of urls during onStart. Typically this list would be retrieved from a _facade.GetUrls call. Then, at each time interval call scanSites. A request is made to each url and then I save the results to the database in _facade.SaveUrlResponse.
My problems is it seems as if I am caught in an endless loop when I debug it. I am not exactly sure how/where to do this. Thanks in advance.
Here is what I have:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.ServiceProcess;
using System.Threading;
using URLValidation.BusinessManager.Facade;
using URLValidation.BusinessManager.Model;
namespace URLValidation
{
partial class URLValidation : ServiceBase
{
#region " class variables "
private System.Timers.Timer _timer;
private List<UrlModel> _url_List = null;
private Facade _facade;
private Thread _t;
private int _x;
#endregion
public URLValidation()
{
_facade = new Facade();
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
_url_List = new List<UrlModel>
{
new UrlModel(address: "http://www.google.com", addressID: 1),
new UrlModel(address: "http://www.microsoft.com", addressID: 2),
new UrlModel(address: "http://www.stackoverflow.com", addressID: 3)
};
resetTimer();
GC.KeepAlive(_timer);
}
catch (Exception ex)
{
throw ex;
}
}
private void resetTimer()
{
try
{
_timer = new System.Timers.Timer();
_timer.Interval = 10000;//1800000; //30 minutes
_timer.Start();
_timer.Enabled = true;
_timer.Elapsed += scanSites;
}
catch (Exception ex)
{
throw ex;
}
}
private void scanSites(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Stop();
_x = 0;
_t = new Thread(new ThreadStart(scanSites));
_t.IsBackground = true;
_t.Start();
}
private void scanSites()
{
try
{
foreach (UrlModel url in _url_List)
{
_x += 1;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Address);
request.Method = "HEAD";
RequestModel requestModel = new RequestModel(request, url);
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(saveUrlResponse), requestModel);
ThreadPool.RegisterWaitForSingleObject
(
result.AsyncWaitHandle,
new WaitOrTimerCallback(ScanTimeoutCallback),
requestModel,
(30 * 1000), // 30 second timeout
true
);
}
}
catch (Exception ex)
{
throw ex;
}
}
private void saveUrlResponse(IAsyncResult result)
{
//grab the custom state object
RequestModel requestModel = (RequestModel)result.AsyncState;
HttpWebRequest request = (HttpWebRequest)requestModel.Request;
//get the Response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
// process the response...
ResponseModel responseModel = new ResponseModel(request, response, requestModel.UrlModel.AddressID);
_facade.SaveUrlResponse(responseModel);
}
private void ScanTimeoutCallback(object requestModel, bool timedOut)
{
if (timedOut)
{
RequestModel reqState = (RequestModel)requestModel;
if (reqState != null)
reqState.Request.Abort();
}
if (_x == _url_List.Count)
{
resetTimer();
}
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
Okay, I think I am getting somewhere. I have moved my code to a console app. I am able to get the results saved to the database by using either GetResponse (sync) and BeginGetResponse (async). From what I can tell I believe this is a good solution. Can somebody verify this and let me know if you foresee any problems once this is moved to a Windows Service. Here is the new code
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
namespace ConsoleApplication2
{
static class Program
{
private static List<UrlModel> _url_List = null;
private static Object _acctLock = new object();
private static Facade _facade = new Facade();
static void Main(string[] args)
{
_url_List = new List<UrlModel>
{
new UrlModel(address: "http://www.microsoft.com", addressID: 1),
new UrlModel(address: "http://www.google.com", addressID: 2),
new UrlModel(address: "http://www.stackoverflow.com", addressID: 3)
};
lockThreadAndGetUrlStatus(_url_List);
Console.ReadLine();
}
static void lockThreadAndGetUrlStatus(List<UrlModel> _url_List)
{
Thread[] threads;
try
{
threads = new Thread[_url_List.Count];
Thread.CurrentThread.Name = "main";
int i = 0;
foreach (UrlModel url in _url_List)
{
//Thread t = new Thread(() => scanSites(url));
Thread t = new Thread(() => scanSitesWithAsync(url));
t.Name = i.ToString();
threads[i] = t;
i += 1;
}
for (i = 0; i < _url_List.Count; i++)
{
Console.WriteLine("Thread {0} Alive : {1}", threads[i].Name, threads[i].IsAlive);
threads[i].Start();
Console.WriteLine("Thread {0} Alive : {1}", threads[i].Name, threads[i].IsAlive);
}
Console.WriteLine("Current Priority : {0}", Thread.CurrentThread.Priority);
Console.WriteLine("Thread {0} Ending", Thread.CurrentThread.Name);
}
catch (Exception ex)
{
throw ex;
}
}
static void scanSitesWithAsync(UrlModel url)
{
try
{
lock (_acctLock)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Address);
request.Method = "HEAD";
RequestModel requestModel = new RequestModel(request, url);
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(saveUrlResponseWithAsync), requestModel);
ThreadPool.RegisterWaitForSingleObject
(
result.AsyncWaitHandle,
new WaitOrTimerCallback(scanTimeoutCallback),
requestModel, 30000, true
);
}
}
catch (Exception ex)
{
throw ex;
}
}
static void saveUrlResponseWithAsync(IAsyncResult result)
{
try
{
RequestModel requestModel = (RequestModel)result.AsyncState;
HttpWebRequest request = (HttpWebRequest)requestModel.Request;
//get the Response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
// process the response...
ResponseModel responseModel = new ResponseModel(requestModel.Request, response, requestModel.UrlModel.AddressID);
_facade.SaveUrlResponse(responseModel);
Console.WriteLine(response.StatusCode);
}
catch (Exception ex)
{
throw ex;
}
}
static void scanTimeoutCallback(object requestModel, bool timedOut)
{
try
{
if (timedOut)
{
RequestModel reqState = (RequestModel)requestModel;
if (reqState != null)
reqState.Request.Abort();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
looks like you are trying to issue 3 async requests at the same time. By default, the HTTP/1.1 protocol only specifies 2 connections

How to get JSONArray which has no JSONArray keyword in Android Studio

I am new to this JSON, I am trying to get the JSON values, it is actually as JSONArray with No name. I have gone through some tutorials where they accessed through JSONArray Keyword. But in my JSON File there is no such ArrayName. Kindly help me to solve this. This is my JSON Value:
[
{"id":"4","name":"Trichy"},
{"id":"5","name":"Pondy"},
{"id":"6","name":"Kovai"},
{"id":"7","name":"Madurai"},
{"id":"8","name":"Chennai"},
{"id":"9","name":"Hyderabad"}
]
I need to get "name" from this. Here comes my MainActivity file.
try {
// Locate the NodeList name
JSONArray json=new JSONArray(???); //I dont know what to give here
for (int i = 0; i < json.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Cites worldpop = new Cites();
worldpop.setCity(jsonobject.optString("name"));
cit.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
This is my City.java file.
package com.example.user.spinnercontrol;
public class Cites {
private String city;
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city=city;
}
}
This is my JSON.java file (for reference)
package com.example.user.spinnercontrol;
import java.io.BufferedReader;
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.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONCity {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
MainActivity class should be like this ::
public class MainActivity extends Activity {
JSONObject jsonobject;
ArrayList<String> worldlist = new ArrayList<>();
ArrayList<Cites> cit = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONArray arr = JSONCity.getJSONfromURL("http://www.prateektechnosoft.com/justcall/cities/getall");
for (int i = 0; i < arr.length(); i++) {
try {
jsonobject = arr.getJSONObject(i);
Cites worldpop = new Cites();
worldpop.setCity(jsonobject.optString("name"));
cit.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}

Resources