400 error - The given location is invalid - json

I am trying to retrieve JSON data via an API and parsing it into my Android. I am trying to log the JSON data retrieved but I keep getting a "400 error - given location is invalid." The parameters to access the API seem correct but I am not sure why I can't retrieve the data.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temperatureLabel = (TextView) findViewById(R.id.temperatureLabel);
timeLabel = (TextView) findViewById(R.id.timeLabel);
refreshButton = (ImageView) findViewById(R.id.refreshImage);
final double latitude = -104.8319;
final double longtitude = 39.7294;
refreshButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherForecast(latitude, longtitude);
}
});
getWeatherForecast(latitude, longtitude);
}
public void getWeatherForecast(double latitude, double longtitude) {
String apiKey = "SECRET-KEY;
String forecastURL = "https://api.darksky.net/forecast/" + apiKey + "/" + latitude + ","
+ longtitude;
if (isNetworkAvailable()) {
//Build and HTTP request
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastURL).build();
//Make an Api call
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
alertUserError();
}
});
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.e(TAG, "JASON DATA" + jsonData);
if (response.isSuccessful()) {
mcurrentWeather = getCurrentWeatherDetails(jsonData);
// You want to update the display In the UI.
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "API call failed", Toast.LENGTH_LONG).show();
}
});
}
} catch (IOException e) {
Log.e(TAG, "Exception Caught");
} catch (JSONException e) {
Log.e(TAG, "JSONexception Caught");
}
}
});
} else {
alertUserError();
}
}

If you are trying to check what request you send to the API and what the API sends to you, then you should implement OkHttp logging interceptor. It's simple and easy to work with it.

First of all, I have deleted your secret key from your answer and replaced it with "SECRET-KEY". DarkSky is only free 1000 requests per day, so someone could grab that key and reuse it. You'd have to pay for it.
I would to go to https://darksky.net/dev/account and reset the secret key to avoid risks.
Second, your coordinates are swapped. You currently have
final double latitude = -104.8319;
final double longtitude = 39.7294;
String forecastURL = "https://api.darksky.net/forecast/" + apiKey + "/"
+ latitude + ","
+ longtitude;
That result of:
https://api.darksky.net/forecast/SECRET-KEY/-104.8319,39.7294?exclude=minutely,hourly,daily,flags,alerts
is then "400, Location invalid" because there is no location in the world with latitude -104 and longitude 39.
The correct one is
final double latitude = 39.7294;
final double longtitude = -104.8319;
Then your urlString is:
https://api.darksky.net/forecast/SECRET-KEY/39.7294,-104.8319?exclude=minutely,hourly,daily,flags,alerts
which outputs in the browser:
{
"latitude":39.7294,
"longitude":-104.8319,
"timezone":"America/Denver",
"currently":{
"time":1583068320,
"summary":"Mostly Cloudy",
"icon":"partly-cloudy-night",
"nearestStormDistance":9,
"nearestStormBearing":145,
"precipIntensity":0,
"precipProbability":0,
"temperature":37.32,
"apparentTemperature":33.14,
"dewPoint":18.62,
"humidity":0.46,
"pressure":1011.5,
"windSpeed":5.24,
"windGust":7.61,
"windBearing":157,
"cloudCover":0.87,
"uvIndex":0,
"visibility":10,
"ozone":309},
"offset":-7
}
P.S: Notice I included the exclude query item to shorten the response to show the example. Delete that part and you will have all the response, with minutely, daily and so on fields.

Related

okhttp returns null response

```protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
ctx=getApplicationContext();
txtString= (TextView)findViewById(R.id.txtString);
httpClient = new OkHttpClient();
try {
sendGETT();
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected void sendGETT() throws IOException {
httpClient = new OkHttpClient();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://devru-gaana-v1.p.rapidapi.com/featuredAlbums.php")
.get()
.addHeader("x-rapidapi-host", "devru-gaana-v1.p.rapidapi.com")
.addHeader("x-rapidapi-key", "my api key")
.build();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response.body().string());
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " +
responseHeaders.value(i));
Main3Activity.txtString.setText(response.header("Server"));
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.body().charStream());
final String prettyJsonString = gson.toJson(je);
runOnUiThread(new Runnable() {
#Override
public void run() {
txtString.setText(prettyJsonString);
}
});
}
}
});
}
}```
I'm trying to use okhttpclient with okhttp3, but it return a null value.i tried another url with headers which work fine but when i try this it gives null respone.I tried many solutions from net but I can't figured this out.hope for the help.thanks
This code works fine, for example,
for
Response response = client.newCall(request).execute();
Request request = new Request.Builder()
.url("https://httpbin.org/get")
.addHeader("custom-key", "mkyong") // add request headers
.addHeader("User-Agent", "OkHttp Bot")
.build();
or any other website but I want to get the content of website using rapid api with add headers
```Request request = new Request.Builder()
.url("https://devru-gaana-v1.p.rapidapi.com/featuredAlbums.php")
.get()
.addHeader("x-rapidapi-host", "devru-gaana-v1.p.rapidapi.com")
.addHeader("x-rapidapi-key", "mine api for site")
.build();```

org.json.JSONException: No value for opening_hours ,how to handle this type of error

logcat screenshot
**after parsing json if there is no value for opening_hours nothing is displaying how to handle that please help me.
url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY" **
I did all techniques but not got success in that please help me to resolve this error
public class Details extends AppCompatActivity {
private ImageView image_details, open, close;
private TextView text_mobile, openNow;
private RequestQueue mRequestQueue;
String place_id, img_url, mobile, open_now;
ArrayList<DetailsPojo> mDetailsList;
private Context mContext;
LinearLayout openingLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
findViewByIds();
mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
Intent intent = getIntent();
//if (getIntent().hasExtra("PLACE_ID"))
place_id = intent.getStringExtra("PLACE_ID");
Toast.makeText(this, "Place ID :" + place_id.toString(), Toast.LENGTH_SHORT).show();
parseJson();
}
private void parseJson() {
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place_id + "&key=" + KEY;
Log.d("DetailedURL",url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject resultObject = response.getJSONObject("result");
mobile = resultObject.optString("formatted_phone_number", "not available");
if (resultObject.has("formatted_phone_number")) {
text_mobile.setText(mobile);
} else {
text_mobile.setText("not available");
}
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
open_now = openingObject.optString("open_now", "Not provided");
if(resultObject.has("opening_hours")) {
if (open_now.equalsIgnoreCase("true")) {
open.setVisibility(View.VISIBLE);
openNow.setText("Open");
} else {
close.setVisibility(View.VISIBLE);
openNow.setText("Closed");
}
}else {
openNow.setText("no information provided for Open/Close");
}
if(resultObject.has("photos")){
JSONArray photosArray = resultObject.getJSONArray("photos");
for (int i = 0; i < photosArray.length(); i++) {
JSONObject photosObject = photosArray.getJSONObject(i);
img_url = URL_PHOTO + photosObject.optString("photo_reference","No image available") + "&key=" + KEY;
if (img_url.isEmpty()) {
image_details.setImageResource(R.drawable.hospital);
} else {
Picasso.with(mContext).load(img_url).fit().centerInside().into(image_details);
}
}
}else{
image_details.setImageResource(R.drawable.no_image_available);
}
// mDetailsList.add(new DetailsPojo(img_url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
private void findViewByIds() {
image_details = findViewById(R.id.image_view);
open = findViewById(R.id.open);
close = findViewById(R.id.closed);
text_mobile = findViewById(R.id.text_mobile);
openNow = findViewById(R.id.text_open_now);
openingLayout=findViewById(R.id.Openinglayout);
}
}
Please check your JSON that is coming from the Google APIs https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=AIzaSyBB8VIJUlcVwYC2EnEQATSMIa9S1cDguDg
as you can see in Logcat that it is saying that No value for "opening_hours".
& you are trying to get that JSONObject without checking it that it exists or not.
here you can see your code :-
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
So first validate it that it is coming or not as per the documentation it can even throw the exception if the mapping does not go well.
https://developer.android.com/reference/org/json/JSONObject#getJSONObject(java.lang.String)

send latitude, longitude to mysql by JDBC every 30 seconds

currently I want to send my GPS latitude and longitude to MYSQL by use of JDBC.
To retrieve GPS lat, long I've used the code below and I have GPS tracker code in GPSTracker class. This would toast Latitude and Longitude by any time pressing the button.
public class MainActivity extends Activity {
Button btnShowLocation;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//testDB();
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
// txtv = (TextView) findViewById(R.id.txtv);
// btnShowLocation.setOnClickListener(this);
// txtv.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
// txtv = getText().getApplicationContext(this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
}
}
To send JDBC data to MYSQL, I've used the code below which can only send the values that I giving to it in parenthesis:
public class MainActivity extends Activity {
static final String USER = "root";
static final String PASS = "root";
GPSTracker gps;
double tmplat = 0;
double tmplong = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appDB();
}
public void appDB() {
// TextView tv = (TextView) this.findViewById(R.id.txtv);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
//connection to data base.
Connection con = DriverManager.getConnection("jdbc:mysql://192.168.1.6:3306/k_sql1", USER, PASS);
//create a statement
// String result = "Database connection successfull !\n";
Statement statement = con.createStatement();
// execute sql query
String sql = ("INSERT INTO `gps-data2`(`ID`,`Latitude`,`Longitude`) VALUES (1,123.45678, 345.678901);");
// String sql = (" CREATE TABLE IF NOT EXISTS GPS_data ( ID int, Latitude Double, Longitude Double ); INSERT INTO GPS_data (`ID`,`Latitude`,`Longitude`) VALUES (1,1234.5678,56789.123456); ");
statement.executeUpdate(sql);
// System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
enter code here
Please tell me how to combine these 2 systems and send GPS data (lat, lng) to mysql by use of JDBC method. I know it maybe better to use PHP but for this project I want it by use of JDBC. Appreciate if can give me a simple applicable solution.
This is the answer what I was looking for to retrieve GPS parameters programmatically and send it to database directly by use of onClickListener.
static final String USER = "root";
static final String PASS = "root";
String sql = null;
GPSTracker gps;
double tmplat = 0;
double tmplong = 0;
Button btnShowLocation;
double latitude;
double longitude;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
appDB();
} else {
gps.showSettingsAlert();
}
}
});
}
protected void appDB() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/k_sql1", USER, PASS);
String result = "Database connection successfull !\n";
Statement statement = con.createStatement();
String sql = ("INSERT INTO `gps-data2`(`Latitude`,`Longitude`) VALUES (" + latitude + ", " + longitude + ");");
statement.executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
f

Android ListView Volley FATAL EXCEPTION error

I'm developing an Android App and i create a slide menu. In the slide menu i have item "Search". This is a fragment that call a json (using volley) and input the result into custom list view.
Now when i call the fragment (using debug mode) the fragment start to download some data but after some record of json download the app crash and i receive this error:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.firstproject.fragment.SearchFragment.loadListView(SearchFragment.java:175)
at com.firstproject.fragment.SearchFragment.access$000(SearchFragment.java:46)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:105)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:98)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
I attach my code where i call a json file (for privacy delete the url json)
Any help please?
Thanks
public class SearchFragment extends Fragment {
public SearchFragment(){}
private static final String url = "http://<server_name>/<folder>/data.json";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search, container, false);
}
ListView geoJSON;
String globalResponse="";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String tag_string_req = "string_req";
final ProgressDialog pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
RequestQueue mRequestQueue;
Network network = new BasicNetwork(new HurlStack());
//Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Instantiate the RequestQueue with the cache and network.
Cache cache = AppController.getInstance().getRequestQueue().getCache();
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
Cache.Entry entry = cache.get(url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
//loadListView(gobalResponse,0,1000);
//Toast.makeText(getActivity(), "Cache utilized!", 0).show();
// handle data, like converting it to xml, json, bitmap etc.,
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else{
// Cached response doesn't exists. Make network call here
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
globalResponse=response;
Globals.GlobalResponse=globalResponse;
Log.d("", response.toString());
loadListView(globalResponse,0,1000);
//loadListView(response,0,1000);
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(), error.getMessage()+"", 0).show();
pDialog.hide();
}
});
strReq.setShouldCache(true);
//strReq.
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
private ArrayList<GeoJsonResponse> globalResponseObject;//=new ArrayList<GeoJsonResposne>();
private void loadListView(String response,float lowerLimit,float upperLimit)
{
try {
JSONObject featureCollection=new JSONObject(response);
globalResponseObject=new ArrayList<GeoJsonResponse>();
JSONArray features=featureCollection.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject properties=features.getJSONObject(i);
float mag=Float.parseFloat(properties.getJSONObject("properties").getString("mag"));
if(!(mag>=lowerLimit&&mag<upperLimit)) continue;
Log.d("",properties.getJSONObject("properties").getString("author")
+ properties.getJSONObject("properties").getString("mag")
+ properties.getJSONObject("properties").getString("place")
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)
);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date1 = format.parse(properties.getJSONObject("properties").getString("time"));
GeoJsonResponse obj=new GeoJsonResponse(
properties.getJSONObject("properties").getString("eventId"),
properties.getJSONObject("properties").getString("author"),
properties.getJSONObject("properties").getString("place"),
Double.parseDouble(properties.getJSONObject("properties").getString("mag")),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)),
properties.getJSONObject("properties").getString("time"),date1,
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1))
);
globalResponseObject.add(obj);}
if(lowerLimit==0)
Globals.geoJsonResponse=globalResponseObject;
// Collections.sort(globalResponseObject, new DateSorter());
CustomListAdapter adpater=new CustomListAdapter(getActivity()
, globalResponseObject);
adpater.notifyDataSetChanged();
geoJSON.setAdapter(adpater);
geoJSON.invalidate();
geoJSON.invalidateViews();
//, author, place, magnitude, distance, date)
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Null map returned from supportmapfragment

I am trying to use Google Maps API v2 in my Android application. I have added the map fragment programmatically using following code and then I try getting the GoogleMap from my SupportMapFragment, but I always get null result back even though the map shows up on screen fine...Any help is highly appreciated!!!!!!!
Thanks
public class MapActivity extends BaseFragmentActivity {
private SchoolType mSchoolType=SchoolType.ALL;
private GoogleMap mMap;
private UiSettings mUiSettings;
private SupportMapFragment mMapFragment;
private static final String MAP_FRAGMENT_TAG = "map";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.map_activity);
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
if(mMapFragment==null)
addMapFragment();
setUpMapIfNeeded();
}
catch(Exception ex){
System.err.println("Exception: " + ex.getMessage());
}
}
private void addMapFragment(){
try{
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.zoomControlsEnabled(true) ;
mMapFragment = SupportMapFragment.newInstance(options);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_map_content, mMapFragment,MAP_FRAGMENT_TAG);
//transaction.addToBackStack(null);
transaction.commit();
}
catch(Exception ex){
System.err.println("Exception: " + ex.getMessage());
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = mMapFragment.getMap(); ***//ALWAYS RETUN NULL***
//mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
call setUpMapIfNeeded in onResume(), like this.
#Override
protected void onResume() {
super.onResume();
// In case Google Play services has since become available.
setUpMapIfNeeded();
}