Im trying to have a few getter methods for a few strings to get returned after getting them from an online JSON. In order to save space I decided to put that all in an object and call them from there.
Object:
public class InventoryItem extends AsyncTask<Void,Void,Void>{
String imageURL = "";
String itemName = "";
String itemDesc = "";
String itemRarity = "";
String itemType = "";
JSONObject itemJson = null;
InventoryItem(JSONObject json){
itemJson = json;
Log.d("StringSubclass","Inventory Item");
}
#Override
protected Void doInBackground(Void... voids) {
Log.d("StringSubclass","doInBG Inventory Item");
try {
imageURL = "http://www.bungie.net"+itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("icon");
Log.d("StringSubclass",imageURL);
itemName = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemName");
itemDesc = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemDescription");
itemRarity = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("tierTypeName");
itemType = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemTypeName");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public String getItemType() {
return itemType;
}
public String getItemRarity() {
return itemRarity;
}
public String getItemDesc() {
return itemDesc;
}
public String getItemName() {
return itemName;
}
public String getImageURL() {
return imageURL;
}
}
The problem is that the getter methods at the end send back "" even though I changed their value in doInBackground.
This is how I called getImageURL():
InventoryItem subclass = new InventoryItem(makeJSON(HOST+"Manifest/6/"+subclassHash+"/"));
subclass.execute();
Log.d("StringSubclass",subclass.getImageURL());
intentHome.putExtra("SubclassImageURL",subclass.getImageURL());
makeJSON():
public JSONObject makeJSON(String url){
JSONObject json = null;
String apiKey = "36c346318fa54fc6bc659ad6321a6d41";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-API-KEY", apiKey);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
String response = "";
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
in.close();
JsonParser parser = new JsonParser();
JsonObject gson = (JsonObject) parser.parse(response);
json = new JSONObject(gson.toString());
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
I checked the URL and it is working fine in chrome.
Any help will be appreciated.
I kind of new to this so please explain as much as possible.
Thanks
Related
I am new on JAVA, how to parse the countryname using this API: https://iplist.cc/api
Use JAVA to parse the JSON: https://iplist.cc/api
Get ONLY the "countryname" value.
For example,
If the country name is "countryname": "Germany",
The OUTPUT should be only:
Germany
I tried this but did not work :(
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
// url to make request
private static String url = "https://iplist.cc/api";
// JSON Node names
private static final String COUNTRY_NAME = "countryname";
// contacts JSONArray
JSONArray contacts = null;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
country = json.getString(COUNTRY_NAME);
}
} catch (JSONException e) {
e.printStackTrace();
}
Thank You!
For such deserialization purpose, I would recommend you to use Gson (or another of this kind).
implementation 'com.google.code.gson:gson:2.8.6'
Prepare IP class for deserialization:
public class IP {
public final String ip;
public final String registry;
public final String countrycode;
public final String countryname;
public final String detail;
public final boolean spam;
public final boolean tor;
public IP(String ip, String registry,
String countrycode, String countryname,
String detail, boolean spam, boolean tor) {
this.ip = ip;
this.registry = registry;
this.countrycode = countrycode;
this.countryname = countryname;
this.detail = detail;
this.spam = spam;
this.tor = tor;
}
}
Deserialize from JSON String with Gson:
IP ip = new Gson().fromJson(json, IP.class);
System.out.println(ip.countryname);
First add org.json library to your project. this is for converting String to JSONObject.
public class HttpGet {
public static String readGetRequestData(String urlToRead) throws IOException {
// System.setProperty("https.proxyHost", "ip");
// System.setProperty("https.proxyPort", "port"); if you got some proxy set it
URL url = new URL(urlToRead);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
return new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String data = readGetRequestData("https://iplist.cc/api");
try {
JSONObject jsonObject = new JSONObject(data);
System.out.println(jsonObject.get("countryname"));
} catch (JSONException err) {
err.printStackTrace();
}
}
}
result is: Germany
it my method call
if(guest){
new JsonTask().execute("URL");
}else{
new AsyncTaskGetMareker().execute();
}
This is my method:
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
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); //here u ll get whole response...... :-)
}
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 (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
JSONObject json = new JSONObject(result);
JSONObject jsonResponse = json.getJSONObject("response");
String name = jsonResponse.getString("store_name");
String lat = jsonResponse.getString("latitude");
String lang=jsonResponse.getString("longitude");
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
This is my error
org.json.JSONException: Value [{"id":1,"store":"дом","category_id":11,"latitude":
2020-02-10 14:24:01.689 13767-13767/? W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
I found this code on this site and am trying to implement it in my project.
I make sure that when checking, either a local or external file is loaded.
What i do wrong in my code?Please help me...I don't understand English well, please understand and forgive me
The answer that helped me from: mrgrechkinn
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result !=null){
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObject= null;
try {
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("store_name");
String lat = obj.getString("latitude");
String lang=obj.getString("longitude");
String desc=obj.getString("store_desc");
String oxr=obj.getString("telephone");
String sost=obj.getString("keywords");
int cat=obj.getInt("category_id");
int id=obj.getInt("id");
Log.e("100rad",""+i);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class PerformNetworkTasks extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<String>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo.toString();
/*
right now I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException 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);
inputDataTV.setText(result);
}
I need to return some data individually. So I need to return an array (i think) so that I can set the TextView as e.g. arrays.get(number).
Is there some other way that I am not realizing here, or should I continue with what I am doing to get the data individually?
Just to add, I am getting the info from a website.
You can return any data type you want
but your AsyncTask structure should be based on result data type
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>/*resultParam*/> {
#Override
protected List<String>/*will same as result parma*/ doInBackground(String... params) {
return null;/*now you can return list of string*/
}
#Override
protected void onPostExecute(List<String>/*finally receive result*/ result) {
super.onPostExecute(result);
}
}
so your code will be
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>> {
#Override
protected List<String> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo;
/*
right now
I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException 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(List<String> result) {
super.onPostExecute(result);
inputDataTV.setText(result.get(0));
}
}
please i am having some issues parsing a list of data form the this link(https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23) i am able to get the data from the json array(articles) but how can i get the data from the josn array(sources)
private void getWebApiData() {
String WebDataUrl = "https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONObject("articles");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is code I am using the get the data of the articles.
To get the sources I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONArray("articles");
JSONObject response3 = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I think I am not getting the code correctly
Here is the second option I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But this only gives me empty text Fields the spaces for the data is populated but it is blank
Please any help will be greatly appreciated
I don't know how your code works. You have tried to get JSONObject as articles which is actually JSONArray. Besides this I don't find any key in your json like sources instead I have found source. To parse source try below way:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("source");
String name = sourceObject.optString("name");
String url = sourceObject.optString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
As Md. Asaduzzaman stated it is actually an JSON array ("articles" to be exact).
I have tested it on my phone and it works no prob. You will have to try and figure out how u want the JSONArray to be parsed thou.
private class AsyncTaskExample extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
stringURL = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) stringURL.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
//render string stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != is) {
is.close();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String js) {
super.onPostExecute(js);
try {
JSONObject jay = new JSONObject (js);
JSONObject source = jay.getJSONObject("articles");
String s = source.getString("title");
System.out.println(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here you will find all you need for JSON.
Best of luck to you :)
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray articles = jsonObject.getJSONArray("articles");
for(int i=0; i<articles.length(); i++){
JSONObject obj1 = (JSONObject) articles.get(i);
JSONObject source = obj1.getJSONObject("source");
Log.i(TAG, "onResponse: " + source.toString()); }
Hope that help you !
I have been working on this and I have hit a point where I dont know what to do. What I am trying to do is use one class to download and parse out a file into a string and then send that string to another class to parse out the JSON stuff. All the parts work fine by themselves and I have tested everything separately. I just dont know how to send the value to the Json parses to start the parsing.
So this is my filedownloader class.
public class JsonFileDownloader extends AsyncTask<String, Void, String> {
//used to access the website
String username = "admin";
String password = "admin";
public String ret = "";
#Override
protected String doInBackground(String... params) {
Log.d("Params ", params[0].toString());
readFromFile(params[0]);
return ret;
}
private String readFromFile(String myWebpage) {
HttpURLConnection urlConnection = null;
try {
//Get the url connection
URL url = new URL(myWebpage);
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
ret = streamToString(inputStream);
inputStream.close();
Log.d("Final String", ret);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
return ret;
}
}
public static String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
public String getJsonData()
{
return ret;
}
}
This works fine I have tested it over and over with no errors.
The next is the Json parser which is like this.
public class JSONParser {
JSONObject jsonResponse;
String jsonData;
//Consturctor
public JSONParser()
{
//this.jsonData = jsonData;
// this.OutputData = outPutData;
}
public void parsesData(String promo,
ArrayList<String> pictureHTTP,
ArrayList<String> pathHTTP,
ArrayList<String> labelText) throws IOException {
//Build the Json String
JsonFileDownloader jfd = new JsonFileDownloader();
// jsonData = String.valueOf(jfd.execute(promo));
jfd.execute(promo);
//jfd.getResuts(jsonData);
//jsonData = jfd.ret;
Log.d("JsonData String = " , jsonData);
//Try to parse the data
try
{
Log.d("Jsondata " , jsonData);
//Creaate a new JSONObject ith the name/value mapping from the JSON string
jsonResponse = new JSONObject(jsonData);
//Returns the value mapped by the name if it exists and is a JSONArry
JSONArray jsonMainNode = jsonResponse.optJSONArray("");
//Proccess the JSON node
int lenghtJsonArrar = jsonMainNode.length();
for (int i = 0; i<lenghtJsonArrar; i++)
{
//Get object for each json node
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//Get the node values
//int song_id = Integer.parseInt(jsonChildNode.optString("song_id").toString());
String picture = jsonChildNode.optString("picture").toString();
String pathName = jsonChildNode.optString("path").toString();
String lableName = jsonChildNode.optString("label".toString());
//Debug Testing code
pictureHTTP.add(picture);
pathHTTP.add(pathName);
labelText.add(lableName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Now I know where the problem is occurring. When i try to assign a value to the jsonData it never is assigned so it is null and the system fails.
I have tried a few things after the jfd.exicute() but I just dont know how to get the value from the final string output into the jsonData.
Thank you for any help with this.
Alright, here is a pretty flexible pattern for the overall usage of using AsyncTask to download web content and getting the results from it back to the UI thread.
Step 1 Define an interface that will act as a message bus between the AsyncTask and where you want the data.
public interface AsyncResponse<T> {
void onResponse(T response);
}
Step 2 Create a generic AsyncTask extension that will take any URL and return the results from it. You basically had this already, but I made some tweaks. Most importantly, allowing the setting of the AsyncResponse callback interface.
public class WebDownloadTask extends AsyncTask<String, Void, String> {
private AsyncResponse<String> callback;
// Optional parameters
private String username;
private String password;
// Make a constuctor to store the parameters
public WebDownloadTask(String username, String password) {
this.username = username;
this.password = password;
}
// Don't forget to call this
public void setCallback(AsyncResponse<String> callback) {
this.callback = callback;
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
return readFromFile(url);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (callback != null) {
callback.onResponse(s);
} else {
Log.w(WebDownloadTask.class.getSimpleName(), "The response was ignored");
}
}
/******* private helper methods *******/
private String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
private String readFromFile(String myWebpage) {
String response = null;
HttpURLConnection urlConnection = null;
try {
//Get the url connection
URL url = new URL(myWebpage);
// Unnecessary for general AsyncTask usage
/*
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
*/
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
response = streamToString(inputStream);
inputStream.close();
Log.d("Final String", response);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return response;
}
}
Step 3 Go forth and use that AsyncTask wherever you wish. Here is an example. Note that if you do not use setCallback, you will be unable to get the data that came from the AsyncTask.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebDownloadTask task = new WebDownloadTask("username", "password");
task.setCallback(new AsyncResponse<String>() {
#Override
public void onResponse(String response) {
// Handle response here. E.g. parse into a JSON object
// Then put objects into some list, then place into an adapter...
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
});
// Use any URL, this one returns a list of 10 users in JSON
task.execute("http://jsonplaceholder.typicode.com/users");
}
}