How to parse data from two json by using AssyncTask method? - android

I have seen one similar question to this, but i couldn't solve my problem like he did.
Here i'm getting data from url:
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP Ok
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
if (result == 1) {
giftListAdapter = new GiftListAdapter(GiftsActivity.this, gifts);
recyclerView.setAdapter(giftListAdapter);
} else {
SuperActivityToast.create(GiftsActivity.this, getString(R.string.no_internet_connection),
SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.FLYIN)).show();
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("gifts");
gifts = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
GiftItem item = new GiftItem();
item.setThumbnail(post.optString("image"));
item.setTitle(post.optString("title"));
item.setDescription(post.optString("description"));
item.setSource(getString(R.string.source) + " " + post.optString("source"));
item.setTotalRating(post.optInt("rating"));
item.setPrice(post.optDouble("price"));
gifts.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And here i'm executing that url. I'm trying now to parse this second url and load all items after first data is loaded:
new AsyncHttpTask().execute(url_movies);
new AsyncHttpTask().execute(url_books); // This is the second url i'm trying to get
How could i do that?

I'm trying now to parse this second url and load all items after first
data is loaded:
Then instead of calling execute method just after first, call it inside onPostExecute method when first url all items are loaded successfully.
Also add second call in if-else block to avoid it execute again :
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
... your code here
if(params[0].equals(url_movies)){
new AsyncHttpTask().execute(url_books);
}
}
also add

If you want both urls than send them as an String array like this
String urls[] = new String[]{"url1" , "url2"};
new AsyncHttpTask().execute(urls);
and in doinbackground method exec them like
url1 = params[0];
url2 = params[1];

Related

How to get response from url in json for android and than after reponse i want to parse it

I am trying to fetch data from thingspeak api and I am taking Input for channel id and passing it on URL. But I have to check if the url is responding or not, if it is responding than go ahead with the code else user have to change channel id.
Error I am getting is 'int java.lang.String.length()' on a null object reference
and
W/System.err: java.io.FileNotFoundException: https://api.thingspeak.com/channels/497971/feeds.json?results=1
This is invalid url if I change it to
https://api.thingspeak.com/channels/497970/feeds.json?results=1
This will work
Code I am trying is
public class MainActivity extends AppCompatActivity {
TextView a, b;
String result = "";
String field1,field2,field3;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = (TextView) findViewById(R.id.a);
b = (TextView) findViewById(R.id.b);
new CountDownTimer(100000, 10000) {
#Override
public void onTick(long l) {
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/497970/feeds.json?results=1");
}
#Override
public void onFinish() {
}
}.start();
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
search(result);
}
public void search(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject fieldinfo = jsonObject.getJSONObject("channel");
String ff1 = fieldinfo.optString("field1","No Value");
String ff2 = fieldinfo.optString("field2","No Value");
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
field1 = legsobject.getString("field1");
field2 = legsobject.getString("field2");
a.setText(ff1);
c.setText(field1);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
}
Here is the Image of error
The issue here is that you are not taking into account that HTTP connections sometimes do fail, like in this case. And it fails because the channel id does not exist.
When you set a correct channel id, the URL is also correct because the resource exists and therefore you get the desired results.
However, when you set a wrong channel id the HTTP request fails (because that URL does not exist). Regardless of this, you are attempting to read the response and that's when it all blows up.
When you make an HTTP request to a server, it responds with a status code indicating what happened with your request. You are completely ignoring this status code.
Look at the headers that a request to that URL throws using:
curl -i https://api.thingspeak.com/channels/497971/feeds.json?results=1:
HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 400 Bad Request
... [Shortened] ...
You can learn all about HTTP status codes in a simple Google search but the summary is that it is a number between 100 and 599 that indicates:
Request successfully handled: when it is between 200 and 299.
Request could not be handled, it failed: when it is between 400 and 499.
The request failed because the server basically blew up: (> 500).
In order to retrieve this status code, you need to call the getResponseCode() method of the urlConnection instance.
Only when the status code is successful (between 200 and 299) the call to urlConnection.getInputStream() will succeed. In case of error you need to call urlConnection.getErrorStream().
So in order to fix your code, you need to do something like this:
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
// Open the conection
urlConnection = (HttpURLConnection) url.openConnection();
// Retrieve status code
int statusCode = urlConnection.getResponseCode();
// Determine whether the request was handled successfully or not
boolean success = (statusCode >= 200) && (statusCode < 300);
InputStream in;
if(success) {
// Read the response when request was handled successfully
in = urlConnection.getInputStream();
} else {
// Read the error stream when the request failed
in = urlConnection.getErrorStream();
}
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
// Close the connection
if(urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
First of all, don't forget to close the connection once you are done (I included the disconnection in the finally {} block).
If you debug or log that code, you will see that the status code you are receiving is 400. That is the HTTP status code for Bad Request, indicating that your request is not correct and you need to fix it. If you analyze the content of the result variable, you will see that the value equals to -1.
Therefore in the onPostExecute callback you should make sure the value is different than -1 before attempting to deserialize it, since otherwise it will blow up again.
You can fix your onPostExecute callback like this:
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
if(result.equals(-1)) {
// Do something else, show an error to the user indicating the channel id is wrong
} else {
// Since there is no error, you can proceed with the deserialization of the response
search(result);
}
}
I hope it helps and that it was clear enough.
Cheers!
As you described you need to update your code like
public class MainActivity extends AppCompatActivity {
TextView a, b;
String result = "";
String field1,field2,field3;
private int count = 0;
int channelId=497970;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = (TextView) findViewById(R.id.a);
b = (TextView) findViewById(R.id.b);
startCounter(channelId);
}
public void startCounter(int channelId){
new CountDownTimer(100000, 10000) {
#Override
public void onTick(long l) {
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/"+channelId+"/feeds.json?results=1");
}
#Override
public void onFinish() {
}
}.start();
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (FileNotFoundException e){
startCounter(channelId+1);
}
catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
search(result);
}
public void search(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject fieldinfo = jsonObject.getJSONObject("channel");
String ff1 = fieldinfo.optString("field1","No Value");
String ff2 = fieldinfo.optString("field2","No Value");
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
field1 = legsobject.getString("field1");
field2 = legsobject.getString("field2");
a.setText(ff1);
c.setText(field1);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
}

Android Duplicate list view due to onResume

Hello I'm new at android. There is a arrayList and a ListView. I used AsyncTask class to invoke the database from MYSQL DB. This AsyncTask class sets mArrayList(this is the arrayList). To update the list view when I return from another activity, I used onResume(). This is the part.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mold_breakage_history);
brokenMoldListView = findViewById(R.id.brokenMoldListView);
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
}
#Override
protected void onResume() {
super.onResume();
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
In onResume(), I initialized the mArrayList and invoke AsyncTask again to update ListView. The problem is when this activity was first executed, the ListView was duplicated. But, when I back from next page of this Activity, the problem is disappeared. I hope that this issue is not present when activity is first executed. Please help.
This is code of AsyncTask class.
#SuppressLint("StaticFieldLeak")
private class GetData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String errorString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MoldBreakageHistoryActivity.this,
"Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Log.d(TAG, "response - " + result);
mJsonString = result;
showResult();
}
#Override
protected String doInBackground(String... params) {
String serverURL = params[0];
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.connect();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "response code - " + responseStatusCode);
InputStream inputStream;
if (responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
} else {
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
return sb.toString().trim();
} catch (Exception e) {
Log.d(TAG, "InsertData: Error ", e);
errorString = e.toString();
return null;
}
}
}
private void showResult() {
try {
JSONObject jsonObject = new JSONObject(mJsonString);
JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
String brokenDate = item.getString(TAG_BROKEN_DATE);
String moldCode = item.getString(TAG_MOLD_CODE);
String finalHitting = item.getString(TAG_FINAL_HITTING_TIMES);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(TAG_BROKEN_DATE, brokenDate);
hashMap.put(TAG_MOLD_CODE, moldCode);
hashMap.put(TAG_FINAL_HITTING_TIMES, finalHitting);
mArrayList.add(hashMap);
}
ListAdapter adapter = new SimpleAdapter(
MoldBreakageHistoryActivity.this, mArrayList, R.layout.list_item_broken_mold,
new String[]{TAG_BROKEN_DATE, TAG_MOLD_CODE, TAG_FINAL_HITTING_TIMES},
new int[]{R.id.brokenDateListItem, R.id.brokenMoldListItem, R.id.finalHittingTimesListItem}
);
brokenMoldListView.setAdapter(adapter);
} catch (JSONException e) {
Log.d(TAG, "showResult : ", e);
}
}
Remove this:
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
from onCreate. onResume is executed right after onCreate and your async task was executing twice, that's why it was duplicated in the first place. When you hit the back only the onResume was executed, so the problem would happen then.
please just remove
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
From your onCreate method. but, if you need to do som scenario in onCreate and other one in onResume you can use mArrayList.clear(); before execute the new task only.

Simplest straight forward way to get a JSON String from a REST URL

I am trying to get a JSON string from a url and save it into SQLite in my android app.
I was trying some tutorials then realize the suggested methods has a void return type. Are there a more simple straight forward way of getting a JSON String and putting it into an arraylist ready to be saved into SQLite?
Below is what I was stuck at a helper class that gets the data from the url
as they said that the main thread OnCreate does not allow a background process like this. Is there a way to change the return type of AsyncTask or is there a more simple way to fetch JSON String with android?
public class FetchData extends AsyncTask<Void, Void, Void> {
#Override
protected void doInBackground(ArrayList<String>... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(inputStream));
String line ="";
while (line != null) {
line = bufferedReader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Go with Volley API. Check the code below which demonstrate POST request. Hope you'll get useful information.
public void getAddress(final String uid) {
String url = "Add Url Here"; // Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray dataArray;
JSONObject jsonObject;
address_ids = new ArrayList<>();
address_names = new ArrayList<>();
address_line1 = new ArrayList<>();
address_line2 = new ArrayList<>();
address_state = new ArrayList<>();
address_district = new ArrayList<>();
address_taluka = new ArrayList<>();
address_pincode = new ArrayList<>();
address_status = new ArrayList<>();
address_default = new ArrayList<>();
try {
jsonObject = new JSONObject(response);
dataArray = jsonObject.getJSONArray(JSON_ARRAY);
//adding response values to respective array
for (int i = 0; i < dataArray.length(); i++) {
//Creating a json object of the current index
JSONObject obj;
try {
//getting json object from current index
obj = dataArray.getJSONObject(i);
address_ids.add(obj.getString(TAG_ADDRESS_ID));
address_names.add(obj.getString(TAG_ADDRESS_NAME));
address_line1.add(obj.getString(TAG_ADDRESSLINE_FIRST));
address_line2.add(obj.getString(TAG_ADDRESSLINE_SECOND));
address_state.add(obj.getString(TAG_STATE));
address_district.add(obj.getString(TAG_DISTRICT));
address_taluka.add(obj.getString(TAG_TALUKA));
address_pincode.add(obj.getString(TAG_PINCODE));
address_status.add(obj.getString(TAG_ADDRESS_STATUS));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//setting up response values to the fragment
//Toast.makeText(getActivity(), "Error:"+response, Toast.LENGTH_LONG).show();
Log.e(TAG, "onResponse: " + response);
address_name.setText("Name : " + address_names.get(0));
address.setText("Address : " + address_line1.get(0) + "," + address_line2.get(0) + "-" + address_pincode.get(0));
taluka.setText("Taluka : " + address_taluka.get(0));
district.setText("District : " + address_district.get(0));
state.setText("State : " + address_state.get(0));
mCircularProgressBar.setIndeterminate(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), "Taking bit longer", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("mk_address_id", address_id);
return params;
}
};
queue.add(stringRequest);
}
Check this link from Android developer, you can find more info their.
In your code change the "extends" from
AsyncTask<Void, Void, Void>
to
AsyncTask<Void, Void, String>
and the doInBackground method to
protected String doInBackground(ArrayList<String>... voids)
and you will get the string back in the onPostExecute method
Yes there is a way to change the return types: Have a look at your extends AsyncTask: It says AsyncTask<Void, Void, Void>.
According to Android Developers, this means <Params, Progress, Result>.
This means that your
ArrayList<String>... voids won't work too, because you have the Params part set to Void but try to get an ArrayList<String>.
So, to solve your problem, change the three Voids to whatever you need it to input and output.
However, to deserialize JSON you should use an external library (or use a 3rd party library for REST calls altogether).
//AsyncTask has onPostExecute which will be called after background execution, where you will get the result in mainthread
class FetchData extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
//Your result String is here which runs on MAIN THREAD
super.onPostExecute(result);
}
}
Retrofit 2 will help you - easy and simple
Edit : For Async task see the top answer here
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
In your code snippet , you specified AsyncTask params types are Void. Void means , it does't have any return value. As per AsyncTask Syntax,
You have to specify three arguments.
1- InputType- DoInBanckground
2- ProgressType - Publish Progress.
3- OutputType - OnPostExecute.
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
In your snippet doInBackground method and AsycTask types are mismatching .
For more information : https://developer.android.com/reference/android/os/AsyncTask.html

Cannot evaluate com.android.okhttp.HttpUrl$Builder.toString()

The following code seems to cause this exception to be thrown:
public static String GET(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { <--**Here**
....
}
.....
}
This is the method in the MainActivity that calls this function:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void,Void,List<Client>>(){
#Override
protected void onPostExecute(List<Client> clients) {
super.onPostExecute(clients);
myList=clients;
}
#Override
protected List<Client> doInBackground(Void... voids) {
return getClients();
}
}.execute();
if(myList == null)
Log.v("Tag", "its null");
else
Log.v("Tag", "it works");
}
public List<Client> getClients() {
List<Client> result = new ArrayList<Client>();
try {
String str = PHPtools.GET(WEB_URL + "Client.php");
JSONArray array = new JSONObject(str).getJSONArray("Client");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
Client client = new Client();
client.setLastName(jsonObject.getString("lastName"));
client.setFirstName(jsonObject.getString("firstName"));
client.setId(jsonObject.getInt("_id"));
client.setPhoneNumber(jsonObject.getString("phoneNumber"));
client.setEmail(jsonObject.getString("email"));
client.setCreditCardNumber(jsonObject.getLong("creditCardNumber"));
result.add(client);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The URL I am passing has been tested and works fine. I tried it on Chrome and the JSON I am trying to parse displays perfectly fine.
but the problem starts when trying to establish connection at the line mentioned above.
I am calling this method from an AsyncTask and also added an Internet permission to the Manifest file.
This is the full error I am receiving:
"Method threw 'java.lang.NullPointerException' exception. Cannot evaluate com.android.okhttp.HttpUrl$Builder.toString()"
Thanks in advance

Using same AsyncTask subclass to make API call to different URLs

I am storing the data that I parsed from the JSON that is returned by my API request into the Firebase database.
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String APIURL = "https://api.github.com/users/" + idInput.getText().toString();
String repoURL = "https://api.github.com/users/" + idInput.getText().toString() + "/repos";
new JSONTask().execute(APIURL);
//new JSONTask().execute(repoURL);
String parsedUserID = idInput.getText().toString();
SM.sendDataToProfile(parsedUserID);
viewPager.setCurrentItem(1);
//addUser(parsedUserID);
}
});
When the button is clicked, it calls a new JSONTask (asynctask) on the APIURL.
JSONTask
public class JSONTask extends AsyncTask<String, String, String> {
#Override
// Any non-UI thread process is running in this method. After completion, it sends the result to OnPostExecute
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
// Pass in a String and convert to URL
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
// Reads the data line by line
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer strBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
strBuffer.append(line);
}
// If we are able to get the data do below :
String retreivedJson = strBuffer.toString();
return retreivedJson;
// When we are not able to retreive the Data
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
// close both connection and the reader
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
And it does parsing in another function.
My question is, as you can see on my setOnClickListener, I tried to make two JSONTask on two different URLs because the first URL gives me the information of the user and the second URL (repoURL) gives me the information of the user's repositories. I tried to fetch the repo info of the user and store it into the DB, but it seems like this is a wrong approach.
What is a right way to call two separate AsyncTasks on two different URLs?
EDIT
private void addUserRepo(final String githubID, final String[] repoList) {
DatabaseReference users = databaseReference.child("users");
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List list = new ArrayList<String>(Arrays.asList(repoList));
databaseReference.child("users").child(githubID).child("Repos").setValue(list);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Using data parsed from
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
RepoInfo[] repoList = new RepoInfo[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
repoList[i].setRepoName(jsonObject.getString("name"));
//repoNameList.add(jsonObject.getString("name"));
}
if(jsonObject.optString("description") != null) {
repoList[i].setDescription(jsonObject.getString("description"));
//descriptionList.add(jsonObject.getString("description"));
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
repoList[i].setOwner(ownerObject.getString("login"));
//userNameList.add(ownerObject.getString("login"));
}
}
}
} catch (JSONException jsonException){
}
}
The response of two different URLs will surely not be similar. So you need different parse methods for them.
One lazy way would be to use two different AsyncTasks subclasses for two different urls.
Another way would be to store a flag inside the asynctask indicating whether it is dealing with user or repo.
public class JSONTask extends AsyncTask <String , String , String> {
boolean fetchingRepo;
#Override
protected String doInBackground (String... params) {
fetchingRepo = params[0].endsWith("/repos");
//other statements
}
Now inside onPostExecute:
if(fetchingRepo){
//parse one way
} else {
//parse another way
}

Categories

Resources