I am working on the sunshine app from udacity tutorials. I am somewhere on lesson2. When I try to run a feature of the app I get this errors:
04-29 12:21:13.311 22025-22424/name.company.sunshine.app E/FetchWeatherTask﹕ Error
java.net.MalformedURLException: Protocol not found: "http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
at java.net.URL.<init>(URL.java:176)
at java.net.URL.<init>(URL.java:125)
at name.company.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:144)
at name.company.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:101)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
04-29 12:21:13.321 22025-22025/name.company.sunshine.app D/AbsListView﹕ unregisterIRListener() is called
04-29 12:21:13.321 22025-22025/name.company.sunshine.app E/ViewRootImpl﹕ sendUserActionEvent() mView == null
line 144 is
URL url = new URL(builtUri.toString());
I will provide the entire class if you need it.
And something else, I have this in the manifest
<uses-permission android:name="android.permission.INTERNET" />
but when I install the app it never asks for permission.
This is the file :
package name.company.sunshine.app;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id == R.id.action_refresh){
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
String forecastArray[] = {
"Today-Sunny-88/63",
"Tuesday-Foggy-14/32",
"Wednesday-Cloudy-22/33"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
#Override
protected String[] doInBackground(String... params) {
//If there's no zip code, there's nothing to look up. Verify size of params
if(params.length == 0){
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL =
"\"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM,params[0])
.appendQueryParameter(FORMAT_PARAM,format)
.appendQueryParameter(UNITS_PARAM,units)
.appendQueryParameter(DAYS_PARAM,Integer.toString(numDays)).build();
Log.v(LOG_TAG,"Built URI"+builtUri.toString());
URL url = new URL(builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
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) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try{
return getWeatherDataFromJson(forecastJsonStr,numDays);
} catch (JSONException e){
Log.e(LOG_TAG,e.getMessage(),e);
e.printStackTrace();
}
return null;
}
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
}
}
Now I don t have the error anymore after deleting "/" ", but this line is not being printed
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
probably it fails to connect or something. I can't see anything in logCat for some reason .
The issue is that you are escaping the " before the start of url and its considering it to be part of Url. since "http is not a valid protocol , valid values are http https ftp etc.
final String FORECAST_BASE_URL = "\"http://api.openweathermap.org/data/2.5/forecast/daily?";
should be
final String FORECAST_BASE_URL ="http://api.openweathermap.org/data/2.5/forecast/daily?";
Your URI is not a URI. There is no protocol component. It needs http:// or whatever other protocol you intend.
remove "/" from your FORECAST_BASE_URL
final String FORECAST_BASE_URL ="http://api.openweathermap.org/data/2.5/forecast/daily?";
Related
I am using the below code to create event in Youtube for Live Streaming. Everything works fine, my problem, I want users to live stream to our company's Channel.
At present events are getting created in users channel, this is wrong, we want to create the event in our channel and live stream should come to our company's channel. I would like to know how we should specify our company's channel to create the events.
I tried to specify
YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube
.liveBroadcasts().insert(Arrays.asList(lbInsert),
broadcast);
liveBroadcastInsert.onBehalfOfContentOwner("user#company.com");
liveBroadcastInsert.onBehalfOfContentOwnerChannel("ChannelID");
Both did not work. It gave error
"errors": [
{
"domain": "youtube.common",
"message": "The authenticated user cannot act on behalf of the specified Google account.",
"reason": "accountDelegationForbidden"
}
//// Code ///
import com.google.android.gms.common.Scopes;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.util.DateTime;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTube.LiveBroadcasts.Transition;
import com.google.api.services.youtube.YouTubeScopes;
import com.google.api.services.youtube.model.CdnSettings;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtube.model.IngestionInfo;
import com.google.api.services.youtube.model.LiveBroadcast;
import com.google.api.services.youtube.model.LiveBroadcastContentDetails;
import com.google.api.services.youtube.model.LiveBroadcastListResponse;
import com.google.api.services.youtube.model.LiveBroadcastSnippet;
import com.google.api.services.youtube.model.LiveBroadcastStatus;
import com.google.api.services.youtube.model.LiveStream;
import com.google.api.services.youtube.model.LiveStreamListResponse;
import com.google.api.services.youtube.model.LiveStreamSnippet;
import com.google.api.services.youtube.model.MonitorStreamInfo;
import com.test.tv.usb.MainActivity;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class YouTubeApi {
public static final String RTMP_URL_KEY = "rtmpUrl";
public static final String BROADCAST_ID_KEY = "broadcastId";
private static final int FUTURE_DATE_OFFSET_MILLIS = 5 * 1000;
public static void createLiveEvent(YouTube youtube, String description,
String name) {
// We need a date that's in the proper ISO format and is in the future,
// since the API won't
// create events that start in the past.
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
long futureDateMillis = System.currentTimeMillis()
+ FUTURE_DATE_OFFSET_MILLIS;
Date futureDate = new Date();
futureDate.setTime(futureDateMillis);
String date = dateFormat.format(futureDate);
Log.i(MainActivity.APP_NAME, String.format(
"Creating event: name='%s', description='%s', date='%s'.",
name, description, date));
try {
LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
broadcastSnippet.setTitle(name);
broadcastSnippet.setScheduledStartTime(new DateTime(futureDate));
LiveBroadcastContentDetails contentDetails = new LiveBroadcastContentDetails();
MonitorStreamInfo monitorStream = new MonitorStreamInfo();
monitorStream.setEnableMonitorStream(false);
contentDetails.setMonitorStream(monitorStream);
// Create LiveBroadcastStatus with privacy status.
LiveBroadcastStatus status = new LiveBroadcastStatus();
status.setPrivacyStatus("public");
LiveBroadcast broadcast = new LiveBroadcast();
broadcast.setKind("youtube#liveBroadcast");
broadcast.setSnippet(broadcastSnippet);
broadcast.setStatus(status);
broadcast.setContentDetails(contentDetails);
// Create the insert request
String[] lbInsert = {"snippet", "status","contentDetails"};
YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube
.liveBroadcasts().insert(Arrays.asList(lbInsert),
broadcast);
// Request is executed and inserted broadcast is returned
LiveBroadcast returnedBroadcast = liveBroadcastInsert.execute();
// Create a snippet with title.
LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
streamSnippet.setTitle(name);
// Create content distribution network with format and ingestion
// type.
CdnSettings cdn = new CdnSettings();
cdn.setIngestionType("rtmp");
cdn.setResolution("1080p");
cdn.setFrameRate("30fps");
LiveStream stream = new LiveStream();
stream.setKind("youtube#liveStream");
stream.setSnippet(streamSnippet);
stream.setCdn(cdn);
// Create the insert request
String[] lsInsert = {"snippet", "cdn"};
YouTube.LiveStreams.Insert liveStreamInsert = youtube.liveStreams()
.insert(Arrays.asList(lsInsert), stream);
// Request is executed and inserted stream is returned
LiveStream returnedStream = liveStreamInsert.execute();
// Create the bind request
String[] lbBind = {"id", "contentDetails"};
YouTube.LiveBroadcasts.Bind liveBroadcastBind = youtube
.liveBroadcasts().bind(returnedBroadcast.getId(),
Arrays.asList(lbBind));
// Set stream id to bind
liveBroadcastBind.setStreamId(returnedStream.getId());
// Request is executed and bound broadcast is returned
liveBroadcastBind.execute();
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: "
+ e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getStackTrace());
t.printStackTrace();
}
}
// TODO: Catch those exceptions and handle them here.
public static List<EventData> getLiveEvents(
YouTube youtube) throws IOException {
Log.i(MainActivity.APP_NAME, "Requesting live events.");
String[] yReq = {"id", "snippet", "contentDetails"};
YouTube.LiveBroadcasts.List liveBroadcastRequest = youtube
.liveBroadcasts().list(Arrays.asList(yReq));
// liveBroadcastRequest.setMine(true);
liveBroadcastRequest.setBroadcastStatus("upcoming");
// List request is executed and list of broadcasts are returned
LiveBroadcastListResponse returnedListResponse = liveBroadcastRequest.execute();
// Get the list of broadcasts associated with the user.
List<LiveBroadcast> returnedList = returnedListResponse.getItems();
List<EventData> resultList = new ArrayList<EventData>(returnedList.size());
EventData event;
for (LiveBroadcast broadcast : returnedList) {
event = new EventData();
event.setEvent(broadcast);
String streamId = broadcast.getContentDetails().getBoundStreamId();
if (streamId != null) {
String[] strID = {streamId};
String ingestionAddress = getIngestionAddress(youtube, strID);
event.setIngestionAddress(ingestionAddress);
}
resultList.add(event);
}
return resultList;
}
public static void startEvent(YouTube youtube, String broadcastId)
throws IOException {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e(MainActivity.APP_NAME, "", e);
}
String[] tReq = {"status"};
Transition transitionRequest = youtube.liveBroadcasts().transition(
"live", broadcastId, Arrays.asList(tReq));
transitionRequest.execute();
}
public static void endEvent(YouTube youtube, String broadcastId)
throws IOException {
String[] tReq = {"status"};
Transition transitionRequest = youtube.liveBroadcasts().transition(
"complete", broadcastId, Arrays.asList(tReq));
transitionRequest.execute();
}
public static String getIngestionAddress(YouTube youtube, String[] streamId)
throws IOException {
String[] tReq = {"cdn"};
YouTube.LiveStreams.List liveStreamRequest = youtube.liveStreams()
.list(Arrays.asList(tReq));
liveStreamRequest.setId(Arrays.asList(streamId));
LiveStreamListResponse returnedStream = liveStreamRequest.execute();
List<LiveStream> streamList = returnedStream.getItems();
if (streamList.isEmpty()) {
return "";
}
IngestionInfo ingestionInfo = streamList.get(0).getCdn().getIngestionInfo();
return ingestionInfo.getIngestionAddress() + "/"
+ ingestionInfo.getStreamName();
}
}
I'm working on a app that is a simple game, so here's a picture for the UI I have, the problem is when I fetch a level using Json web service, the first time I choose the level from activity_level_list, the picture and level number doesn't show, only the 4 words works but neither the image nor the level number appear like this.
NOTE: The image URL variable is null (because of the lag that happens the first time I open first level activity) so an error happen (that's why it shows ic_launcher instead of showing the level picture).
So, I said the problem was "lag" because when I go back to LevelList and click on level 1, the picture and the level number get fetched and everything becomes good.
How can I make it both the image and level ID appears in the first time I open the activity?
NOTE: I use jsonbin.io for data fetching.
Here's my Json data fetching class:
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FetchData extends AsyncTask<Void,Void,Void> {
String update = "4";
String data ="";
String id;
String img;
String w1;
String w2;
String w3;
String w4;
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/" + update);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
// for(int i = 0 ;i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(1);
id = (String) JO.get("id");
img = (String) JO.get("img");
w1 = (String) JO.get("w1");
w2 = (String) JO.get("w2");
w3 = (String) JO.get("w3");
w4 = (String) JO.get("w4");
// }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
int levelId = Integer.parseInt(id);
levelId++;
LevelActivity.levelID = String.valueOf(levelId);
LevelActivity.imageURL = img;
LevelActivity.button1Word = w1;
LevelActivity.button2Word = w2;
LevelActivity.button3Word = w3;
LevelActivity.button4Word = w4;
}
}
Thanks ^-^
I just needed to update the image and level text view number in onPostExecute method to make it load from the first time.
Answer by NIKHIL AGGARWAL
I'm doing a free course on Android development on Udacity. And this is the code of their app that is supposed to get JSON data about an earthquake from the USGS website and display it in the app. However, for some reason it doesn't. What can be the reason?
P.S. I'm using an Android Emulator and don't have a real device. Could this be a reason?
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.soonami;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
/**
* Displays information about a single earthquake.
*/
public class MainActivity extends AppCompatActivity {
/** Tag for the log messages */
public static final String LOG_TAG = MainActivity.class.getSimpleName();
/** URL to query the USGS dataset for earthquake information */
private static final String USGS_REQUEST_URL =
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-12-01&minmagnitude=7";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Kick off an {#link AsyncTask} to perform the network request
TsunamiAsyncTask task = new TsunamiAsyncTask();
task.execute();
}
/**
* Update the screen to display information from the given {#link Event}.
*/
private void updateUi(Event earthquake) {
// Display the earthquake title in the UI
TextView titleTextView = (TextView) findViewById(R.id.title);
titleTextView.setText(earthquake.title);
// Display the earthquake date in the UI
TextView dateTextView = (TextView) findViewById(R.id.date);
dateTextView.setText(getDateString(earthquake.time));
// Display whether or not there was a tsunami alert in the UI
TextView tsunamiTextView = (TextView) findViewById(R.id.tsunami_alert);
tsunamiTextView.setText(getTsunamiAlertString(earthquake.tsunamiAlert));
}
/**
* Returns a formatted date and time string for when the earthquake happened.
*/
private String getDateString(long timeInMilliseconds) {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy 'at' HH:mm:ss z");
return formatter.format(timeInMilliseconds);
}
/**
* Return the display string for whether or not there was a tsunami alert for an earthquake.
*/
private String getTsunamiAlertString(int tsunamiAlert) {
switch (tsunamiAlert) {
case 0:
return getString(R.string.alert_no);
case 1:
return getString(R.string.alert_yes);
default:
return getString(R.string.alert_not_available);
}
}
/**
* {#link AsyncTask} to perform the network request on a background thread, and then
* update the UI with the first earthquake in the response.
*/
private class TsunamiAsyncTask extends AsyncTask<URL, Void, Event> {
#Override
protected Event doInBackground(URL... urls) {
// Create URL object
URL url = createUrl(USGS_REQUEST_URL);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
// Extract relevant fields from the JSON response and create an {#link Event} object
Event earthquake = extractFeatureFromJson(jsonResponse);
// Return the {#link Event} object as the result fo the {#link TsunamiAsyncTask}
return earthquake;
}
/**
* Update the screen with the given earthquake (which was the result of the
* {#link TsunamiAsyncTask}).
*/
#Override
protected void onPostExecute(Event earthquake) {
if (earthquake == null) {
return;
}
updateUi(earthquake);
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Return an {#link Event} object by parsing out information
* about the first earthquake from the input earthquakeJSON string.
*/
private Event extractFeatureFromJson(String earthquakeJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
JSONArray featureArray = baseJsonResponse.getJSONArray("features");
// If there are results in the features array
if (featureArray.length() > 0) {
// Extract out the first feature (which is an earthquake)
JSONObject firstFeature = featureArray.getJSONObject(0);
JSONObject properties = firstFeature.getJSONObject("properties");
// Extract out the title, time, and tsunami values
String title = properties.getString("title");
long time = properties.getLong("time");
int tsunamiAlert = properties.getInt("tsunami");
// Create a new {#link Event} object
return new Event(title, time, tsunamiAlert);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
}
Try using chrome by google searching any adress to see if your Internet connection works from your Emulator. If not connect your emulator to the internet because your app needs to fetch data from the internet.
Running the code on an Actual deviceSoonami App
Again regarding the status of your intenet connection on the emulator
try this stack link here:Android emulator not able to access the internet
The Microsoft Translator API for android samples has already been deprecated since march 2017 (just this yr). So I'm having a hard time translating text on android. Can anyone help me make this work on android?. It's just that I already have this working in java but I can't make it work on Android. I already tried using asynctask , but to no avail, no translation is being outputed. Or prolly I just did a wrong asyc task?.
The Interface of the application is like this:
It just have a simple textfield with translation that should be outputed on the other textfield. The translation is from Korean to English.
Github Project File is in here
https://github.com/iamjoshuabcxvii/MSTranslateAPIforAndroid
Android code is this.
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import org.apache.commons.io.IOUtils;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
//MS Translator Key is in here
public static String key = "<The MS Assigned Translator Key>";
private TextView txtTranslatedText, txtOriginalText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOriginalText = findViewById(R.id.txtOriginalText);
txtTranslatedText = findViewById(R.id.txtTranslatedText);
}
public void translate(View view) {
// String textOrig = txtOriginalText.getText().toString();
// String textOrig ="안녕하세요 123 -)^ 친구";
String textOrig;
textOrig=txtOriginalText.getText().toString();
String output;
output=getTranslation(textOrig);
txtTranslatedText.setText(output);
}
public static String getTranslation(String translatedTextStr) {
try {
// Get the access token
// The key got from Azure portal, please see https://learn.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
// System.out.println(token); //Code to Display Token
// Using the access token to build the appid for the request url
String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
String text = URLEncoder.encode(translatedTextStr, "UTF-8");
String from = "ko";
String to = "en";
String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/GetTranslations?appid=%s&text=%s&from=%s&to=%s&maxTranslations=5", appId, text, from, to);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("POST");
translateConn.setRequestProperty("Accept", "application/xml");
translateConn.setRequestProperty("Content-Type", "text/xml");
translateConn.setDoOutput(true);
String TranslationOptions = "<TranslateOptions xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">" +
"<Category>general</Category>" +
"<ContentType>text/plain</ContentType>" +
"<IncludeMultipleMTAlternatives>True</IncludeMultipleMTAlternatives>" +
"<ReservedFlags></ReservedFlags>" +
"<State>contact with each other</State>" +
"</TranslateOptions>";
translateConn.setRequestProperty("TranslationOptions", TranslationOptions);
IOUtils.write("", translateConn.getOutputStream(), "UTF-8");
String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
// System.out.println(resp+"\n\n");
String s=resp;
Pattern assign_op=Pattern.compile("(<TranslatedText>)"
+ "|(<\\/TranslatedText>)"
+ "|[()\\\\[\\\\]{};=#.,'\\\\^:#!$%&_`*-<>]"
+ "|[a-zA-Z0-9\\s]*"
+ "");
Matcher m = assign_op.matcher(s) ;
String actualTranslation="";
Boolean endOfTransTxt=false,startOfTransTxt=false,concat=false;
String foundRegexStr="",tempStr="";
while (m.find()) {
foundRegexStr=m.group();
if(m.group().matches("(<TranslatedText>)")) {
startOfTransTxt=true;
}
else if(m.group().matches("(<\\/TranslatedText>)")) {
endOfTransTxt=true;
concat=false;
}
else{
startOfTransTxt=false;
endOfTransTxt=false;
}
if(startOfTransTxt==true) {
concat=true;
}
else if(concat==true) {
tempStr=tempStr+""+m.group();
}
else {
}
}
// System.out.println("\nTranslated Text: "+tempStr);
translatedTextStr=tempStr;
} catch (Exception e) {
e.printStackTrace();
}
return translatedTextStr;
}
}
I think you did a wrong AsyncTask.
You can do it like this:
private class TransAsynTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... strings) {
String output = getTranslation(strings[0]);
return output;
}
#Override
protected void onPostExecute(String s) {
txtTranslatedText.setText("Output: " + s);
super.onPostExecute(s);
}
}
And in the onCreate you call:
String textOrig;
textOrig = txtOriginalText.getText().toString();
new TransAsynTask().execute(textOrig);
/*String output;
output = getTranslation(textOrig);
txtTranslatedText.setText("Translated Text: " + output);*/
I am trying to parse JSON, I have done it there before but not quiet this way. I spent hours trying to solve the problem, but I dont know what is wrong with the code.I am attaching the entire code for the activity, Web Request class and the layout. Any help will be greatly appreciated.
I get this error
java.io.FileNotFoundException: /data/system/users/sdp_engine_list.xml: open failed: ENOENT (No such file or directory)
05-19 18:17:27.427 3450-3450/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
05-19 18:17:28.232 3450-3592/? W/DisplayManagerService: Failed to notify process 20004 that displays changed, assuming it died.
This is the activity Transactions class.
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import com.rectuca.iyzicodemo.Classes.Transaction;
import com.rectuca.iyzicodemo.Library.WebRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Transactions extends ListActivity {
// URL to get contacts JSON
private static String url = "http://www.mocky.io/v2/573dbd243700005f194dcdcc";
// JSON Node names
private static final String TAG_PAYMENTS= "payments";
private static final String TAG_PAYMENT_ID = "paymentId";
private static final String TAG_SENT_BY = "sentBy";
private static final String TAG_DATE_TIME = "dateTime";
private static final String TAG_SENT_TO = "sentTo";
private static final String TAG_BANK_NAME = "bankName";
private static final String TAG_INSTALLMENTS = "installments";
private static final String TAG_AMOUNT = "amount";
private static final String TAG_3DS = "threeDs";
private static final String TAG_CANCELLED = "cancelled";
private static final String TAG_RETURNED = "returned";
private static final String TAG_TRANSACTION_STATUS = "transactionStatus";
private static final String TAG_BLOCKAGE_AMOUNT = "blockage_amount";
private static final String TAG_BLOCKAGE_RELEASE_DATE = "blockageReleaseDate";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions);
// Calling async task to get json
new GetInfo().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetInfo extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> transactionInfoList;
ProgressDialog proDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(Transactions.this);
proDialog.setMessage("Please Wait...");
proDialog.setCancelable(false);
proDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
WebRequest webReq = new WebRequest();
// Making a request to url and getting response
String jsonStr = webReq.makeWebServiceCall(url, WebRequest.GET);
Log.d("Response: ", "> " + jsonStr);
transactionInfoList = ParseJSON(jsonStr);
return null;
}
#Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
transactionInfoList=new ArrayList<HashMap<String, String>>();
ListAdapter adapter = new SimpleAdapter(
Transactions.this, transactionInfoList,
R.layout.row_layout, new String[]{TAG_SENT_TO,TAG_DATE_TIME
,TAG_BANK_NAME,TAG_AMOUNT,TAG_3DS, TAG_CANCELLED,
TAG_RETURNED},
new int[]{R.id.name,R.id.dateTime ,R.id.bankName,R.id.amount,
R.id.threeDS, R.id.cancelled, R.id.returned});
setListAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> paymentList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray payments = jsonObj.getJSONArray(TAG_PAYMENTS);
// looping through All Payments
for (int i = 0; i < payments.length(); i++) {
JSONObject c = payments.getJSONObject(i);
String dateTime =c.getString(TAG_DATE_TIME);
String sentTo =c.getString(TAG_SENT_TO);
String bankName =c.getString(TAG_BANK_NAME)+" ( "+c.getString(TAG_INSTALLMENTS)+" ) " ;
String amount =c.getString(TAG_AMOUNT);
String threeDS =c.getString(TAG_3DS);
String cancelled =c.getString(TAG_CANCELLED);
String returned =c.getString(TAG_RETURNED);
// temporary hashmap for a single payment
HashMap<String, String> payment = new HashMap<String, String>();
// adding every child node to HashMap key => value
payment.put(TAG_DATE_TIME, dateTime);
payment.put(TAG_SENT_TO, sentTo);
payment.put(TAG_BANK_NAME, bankName);
payment.put(TAG_AMOUNT, amount);
payment.put(TAG_3DS, threeDS);
payment.put(TAG_CANCELLED, cancelled);
payment.put(TAG_RETURNED, returned);
// adding student to students list
paymentList.add(payment);
}
return paymentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "No data received from HTTP Request");
return null;
}
}
}
This is the WebRequest Class
package com.rectuca.iyzicodemo.Library;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class WebRequest {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public WebRequest() {
}
/**
* Making web service call
*
* #url - url to make request
* #requestmethod - http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making service call
*
* #url - url to make request
* #requestmethod - http request method
* #params - http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod,
HashMap<String, String> params) {
URL url;
String response = "";
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POST) {
conn.setRequestMethod("POST");
} else if (requestmethod == GET) {
conn.setRequestMethod("GET");
}
if (params != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
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"));
}
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
This is what I am trying to do
http://lh3.googleusercontent.com/JqcySZU2Pz067NutlDvPP5Zq_3n_WSAllIuEdjQjOjyeGkKguaMNCrltaKbjBCi16g=h900-rw
I would suggest you to use
VOLLEY networking library by google
You should try to use Volley JSONOBJECTREQUEST() and you won't have any issue after that parsing will be easier.
add this to dependency section of your app
dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}