i need your help. I want to send a URL Request, get response and create a JSON Object. My first try was totally wrong. Now I found a tutorial and made a new try.
My Activity looks like:
public class Patienten extends Activity {
//Beacon Elemente
private String UUID;
private String Major;
private String Minor;
private TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patienten);
output = (TextView) findViewById(R.id.output);
UpdateBeaconInformation();
Button cmdHit = (Button) findViewById(R.id.cmd_hit);
cmdHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
}
});
setTitle(Surname + ", " + FirstName);
// output.setText(output.getText().toString() + "Gefundener Patient:\n" + "Name: " + Surname + ", " + FirstName + "\nGeb.-Dat: " + Birthdate);
}
Then I created a new Java Class and built an asyncTask with it. But I can't access to the textview output in onPostExecute to update it.
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
//http://kusber-web.de/JsonTest.txt
//http://nilsbenning.selfhost.me/PatientFinder.php?beacon_comID=5181f8a3-7354-46ac-b22d-952ec395ab06&beacon_major=12&beacon_minor=249
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
output.setText(result);
}
}
What is my mistake? Why I can't access to it? I saw it as a solution here but didn't get it to work:
https://stackoverflow.com/a/12252717/5743912
Hope you can help me now! :)
You probably want to fix this (remove leading slashes):
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
In your JSONTask you can reference members of Patienten by using Patienten.this. So in onPostExecute you should change this:
output.setText(result);
to:
Patienten.this.output.setText(result);
Related
I have a problem with parsing a tag inside a Json object.
My json code is structured like that:
{"giocatori":[{"nome":"Giovanni","cognome":"Muchacha","numero":"1","ruolo":"F-G"},
{"nome":"Giorgio","cognome":"Rossi","numero":"2","ruolo":"AG"},
{"nome":"Andrea","cognome":"Suagoloso","numero":"3","ruolo":"P"},
{"nome":"Salvatore","cognome":"Aranzulla","numero":"4","ruolo":"G"},
{"nome":"Giulio","cognome":"Muchacha","numero":"5","ruolo":"F"}]}
I got the code that let me get the Json file from here: Get JSON Data from URL Using Android? and I'm trying to parse a tag (for example the "nome" tag) into a Json object.
This is the code I got:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://api.myjson.com/bins/177dpo");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
I've never worked with this type of file so I'll really appreciate your help!
You can use something like this:
try {
String servResponse = response.toString();
JSONObject parentObj = new JSONObject(servResponse);
JSONArray parentArray = parentObj.getJSONArray("giocatori");
if (parentArray.length() == 0) {
//if it's empty, do something (or not)
} else {
//Here, finalObj will have your jsonObject
JSONObject finalObj = parentArray.getJSONObject(0);
//if you decide to store some value of the object, you can do like this (i've created a nomeGiocatori for example)
nomeGiocatori = finalObj.getString("nome");
}
} catch (Exception e) {
Log.d("Exception: ", "UnknownException");
}
I use this kind of code all the time, works like a charm.
I am so beginner about Json. I am trying to understand example on the internet. So that I am doing a translater for myself(Yandex translater). But I have problem I copied and pasted source cod to my project. To making When I clicked my button , Text will be my textview(being translated) Now I cannot get translated string for my textview.How can I get it ?
My TranslatorBackgroundTask AsyncTask (it is not inner class) :
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
#Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey =
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
bufferedReader.close();
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
String resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim() ;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
My MainActivity :
cevir_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String yazı_string = yazı_EditText.getText().toString();
// trans(yazı_string,language);
String languagePair = "en-fr";
Translate(yazı_string,languagePair);
}
});
private void Translate(String textToBeTranslated, String languagePair) {
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
AsyncTask<String, Void, String> translationResult = translatorBackgroundTask.execute(textToBeTranslated,languagePair);
try {
String translationResults = translatorBackgroundTask.execute(textToBeTranslated, languagePair).get();
cevirilmis_tTextView.setText(translationResults);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("Translation Result", String.valueOf(translationResult));
}
You could simply get the string from the AsyncTask:
String translationResult = translatorBackgroundTask.execute(textToBeTranslated, languagePair).get();
However this approach defeats the point of using an AsyncTask as you will end up blocking the UI thread as you wait for the result from .get(). Instead you should use a callback like this
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I am attempting to make an app in android studio that gets live currency rates, so I decided to use a JSON to do this. I am currently able to print out the entire JSON as a string, however I would like to be able to set the TextView to the USD conversion rate, however it doesn't work. The TextView does not change. Any help would be greatly appreciated.
public class Converter extends AppCompatActivity {
TextView txtJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_converter);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
new JsonTask().execute("https://openexchangerates.org/api/latest.json?app_id=870447ebb4d94379972250a3bdaed73f");
}
private class JsonTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
public void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jObject = new JSONObject(result);
int USD = jObject.getInt("USD");
String strUSD = Integer.toString(USD);
txtJson.setText(strUSD);
} catch (JSONException e) {
e.printStackTrace();
}
}
}}
You need to get the "rates" object before you can access the "USD" value
Also, it's not an integer. It's a double
getJSONObject("rates").getDouble("USD")
This is an rssfeed and everything compiles and I don't think i am missing anything but my app wont launch and there is a warning about my OnCreate never being used. I am unsure if this is related to the problem.
public class MainActivity extends AppCompatActivity {
private TextView src;
private Button btn;
protected void OnCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.activity_main);
src = (TextView) findViewById(R.id.text);
btn = (Button)findViewById(R.id.Fetch);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetch();
}
});
}
public void fetch() {
Downloader d = new Downloader();
d.execute("https://en.wikipedia.org/wiki/Main_Page");
try {
src.setText(d.get());
} catch (Exception e) {
Log.e("Error to thread", e.toString());
}
}
class Downloader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
result = result + line;
}
conn.disconnect();
reader.close();
} catch (Exception e) {
Log.e("error to fetching", e.toString());
}
return result;
}
}
The correct writing is onCreate, not OnCreate. Try to change that.
OnCreate --> onCreate and use #Override
I am trying to make an app which executes an image search and displays the image results in a grid. Since the Google Image Search API is deprecated and will no longer be available shortly, I am trying to use the Bing Search API.
However, I am getting the following error:
java.io.IOException: No authentication challenges found
at libcore.net.http.HttpURLConnectionImpl.getAuthorizationCredentials(HttpURLConnectionImpl.java:427)
at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:407)
at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:356)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:292)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
I am following the example in http://learn-it-stuff.blogspot.com/2012/09/using-bing-custom-search-inside-your.html. If anyone has experienced this issue, or can help me out, that would be much appreciated. Thanks!
Here is my code thus far:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncTask <Void, Void, Void> task = new AsyncTask <Void, Void, Void> () {
protected Void doInBackground(Void... args) {
// Uri uri = Uri.parse("https://www.google.com/search?tbm=isch&q=penguin");
// Intent intent = new Intent(Intent.ACTION_VIEW, uri);
// startActivity(intent);
/*-------------------------Bing search-------------------------*/
String searchText = "Hello World";
searchText = searchText.replace(" ", "%20");
String accountKey = "MY_APP_ID";
accountKey = accountKey.replace("+", "%2B");
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Bing/Search/v1/"
+ "Image?Query=%27" + searchText + "%27");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
task.execute();
}
}
The following code worked for me:
public class SearchAsyncTask extends AsyncTask<Void, Void, Void> {
private final String TAG = getClass().getName();
private String mSearchStr;
private int mNumOfResults = 0;
private Callback mCallback;
private BingSearchResults mBingSearchResults;
private Error mError;
public SearchAsyncTask(String searchStr, int numOfResults, Callback callback) {
mSearchStr = searchStr;
mNumOfResults = numOfResults;
mCallback = callback;
}
#Override
protected Void doInBackground(Void... params) {
try {
String searchStr = URLEncoder.encode(mSearchStr);
String numOfResultsStr = mNumOfResults <= 0 ? "" : "&$top=" + mNumOfResults;
String bingUrl = "https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?Query=%27" + searchStr + "%27" + numOfResultsStr + "&$format=json";
String accountKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url = null;
url = new URL(bingUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
InputStream response = urlConnection.getInputStream();
String res = readStream(response);
Gson gson = (new GsonBuilder()).create();
mBingSearchResults = gson.fromJson(res, BingSearchResults.class);
Log.d(TAG, res);
//conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
mError = new Error(e.getMessage(), e);
//Log.e(TAG, e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (mCallback != null) {
mCallback.onComplete(mBingSearchResults, mError);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
//System.out.println(line);
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public interface Callback {
void onComplete(Object o, Error error);
}
}
To parse the result:
public class BingSearchResults {
public ResultsContent d;
public static class ResultsContent {
public Result[] results;
public String __next;
}
public static class Result {
public String ID;
public String Title;
public String Description;
public String DisplayUrl;
public String Url;
public Metadata __metadata;
}
public static class Metadata {
public String uri;
public String type;
}
public Result[] getResults(){
if (d == null)
return null;
return d.results;
}
public String getNextUrl(){
if (d == null)
return null;
return d.__next;
}
public boolean isEmpty(){
return (d == null || d.results == null || d.results.length == 0);
}
public int size(){
if (d == null || d.results == null)
return 0;
return d.results.length;
}
}
You also need to include the external jars commons-codec-1.9.jar and gson-2.2.4.jar
Little bit change occur in this code sometimes compilation bug of encoder generate problem byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());