This is likely a basic Java question. All in same activity, I declare a String[] data, later update it succesfully, but when I attempt to set a textview to the updated data[1] from the calling funtion that updated data[1] - nothing showing. Here is the stripped down code.
public class MyClass extends AppCompatActivity {
String[] data = new String[4];
public void populateGrid() {}
getIndexData(indices);
final TextView test = (TextView) findViewById(R.id.textView0B);
test.post(new Runnable() {
#Override
public void run() {
test.setText(data[1]);
}
});
public void getIndexData(final String[] indices){
//lots of work accomplished, data[1] is updated, Log.d() logs good!
// Tried passing data[] as a parameter from populateGrid(), but that didn't work.
// Tried returning data[] to populateGrid(), also didn't work.
}
}
What is the proper method for accomplishing this task?
As requested, getIndexData()
public void getIndexData(final String indices){
mOkHttpClient = new OkHttpClient();
HttpUrl reqUrl = HttpUrl.parse("http://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" +
indices +
"&outputsize=compact&apikey=" +
apiKey);
Request request = new Request.Builder().url(reqUrl).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// Show user error message if not connected to internet, et. al.
runOnUiThread(new Runnable() {
#Override
public void run() {
Context context = getApplicationContext();
CharSequence text = getResources().getString(R.string.Toast_1);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException {
int j = 0;
String responseBody = response.body().string();
if (responseBody.contains("\"Error Message\"")) {
data[j] = "No Data";
data[j+1] = "No Data";
data[j+2] = "No Data";
data[j+3] = "No Data";
} else { // Extract data points from json object.
try {
JSONObject baseObject = new JSONObject(responseBody);
JSONObject timeSeriesObj = baseObject.optJSONObject("Time Series (Daily)");
Iterator<String> iterator = timeSeriesObj.keys();
List<Map<String, String>> tickerData = new ArrayList<Map<String, String>>();
while (iterator.hasNext()) {
String key = iterator.next();
if (key != null) {
HashMap<String, String> m = new HashMap<String, String>();
JSONObject finalObj = timeSeriesObj.optJSONObject(key);
m.put("1. open", finalObj.optString("1. open"));
m.put("2. high", finalObj.optString("2. high"));
m.put("3. low", finalObj.optString("3. low"));
m.put("4. close", finalObj.optString("4. close"));
m.put("5. volume", finalObj.optString("5. volume"));
tickerData.add(m);
}
}
int k = 0;
String str = tickerData.get(0).toString();
data[k] = StringUtils.substringBetween(str, "open=", ", ");
//Log.d("data[0]= ", data[0]);
data[k+1] = StringUtils.substringBetween(str, "close=", ", ");
Log.d("data[1]", data[1]); // logs 2431.7700
data[k+2] = "";
data[k+3] = "";
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
It would be something like this:
public class MyClass extends AppCompatActivity {
String[] data = new String[4];
public void populateGrid() {
getIndexData(indices);
}
public void getIndexData(final String indices) {
// set up http request
mOkHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// ...
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// process the response, populate data etc.
final TextView test = (TextView) findViewById(R.id.textView0B);
test.post(new Runnable() {
#Override
public void run() {
test.setText(data[1]);
}
});
}
}
}
}
Related
I am trying to get a string response from post request. Here, I am sending a post request. where I am sending this data. I have a Model of BillReceipt. Which I pass on the request body.
public void UserTransactionReceiptReport(TransactionTypeListener<String> listener, BillReceipt billReceiptReport){
final UserSettings userSettings = getMUserSettings();
final StringBuilder url = new StringBuilder(AppConfigsManager.getTouchServerUrl());
url.append("/api/User/UserData");
JSONObject params = new JSONObject();
try{
params.put("iB_CUST_ID",billReceiptReport.getiB_CUST_ID());
params.put("transactioN_DATE",billReceiptReport.getTransactioN_DATE());
params.put("transactioN_DATE_NM",billReceiptReport.getTransactioN_DATE_NM());
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url.toString(), params
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Gson mapper = new GsonBuilder().create();
try{
Type type = new TypeToken<APIResponse<String>>() {
}.getType();
APIResponse<String> responseObject = mapper.fromJson(response.toString(), type);
if(responseObject.Status == APIStatus.OK){
listener.didFetch(responseObject.Result, responseObject.Message);
}else {
listener.didError(responseObject.Message);
}
}catch (Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.didError(error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() {
return getAuthorizationTokenHashMap(getMUserSettings());
}
};
addVolleyRequest(request);
}
and I call this api from recycler download button.Here , I globally declared the manager where i write the api code. and also declare a the model name.
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager.UserTransactionReceiptReport(listener,billReceiptReport);
}
});
}
private final TransactionTypeListener<String> listener = new TransactionTypeListener<String>() {
#Override
public void didFetch(String response, String message) {
str = response;
}
#Override
public void didError(String message) {
}
};
any one help me to solve the problem i am facing.
Try this code
<code>
JSONObject jsonObject = new JSONObject(response);
System.out.println("jsonWallet----" + jsonObject);
int status_ = jsonObject.getInt("status");
if(status_ == 1){
String incomeWalletBal = jsonObject.getString("income_wallet");
String refundWalletBal = jsonObject.getString("refund_wallet");
}else {
}
</code>
I'm doing an App that scrapes a website an get some images, that works fine, I created an ThreadPoolExecutor and some callable but when I try to get the results from a Callable that I created I'm unnable to, it goes to the ExecutionException.
This is the Scraper Class:
public class ImageScraper implements Callable<String>{
Context context = null;
public Logo logoActivity;
Document[] doc = new Document[1];
List<ImageObject> imageList = new ArrayList<ImageObject>();
int pagAnterior;
String url;
int pag;
public ImageScraper(Logo act, String url, int pag, int pagAnterior) {
this.logoActivity = act;
this.url = url;
this.pag = pag;
this.pagAnterior = pagAnterior;
context = act.getApplication();
}
#Override
public String call() throws Exception {
getResponse(url,pag);
getImages(doc[0]);
Log.i("listaaa", "listaa : "+imageList.size());
String something = "got something";
return something;
}
public void getImages(Document docfinal) {
Log.i("Documento1", "documento1 : "+docfinal);
Elements entradas = docfinal.select("img[src]");
Elements titulo = doc[0].select("title");
String tituloPagina = titulo.text();
String urlImage = "";
if(!tituloPagina.toLowerCase().contains("page "+pagAnterior)) {
for (Element elem : entradas) {
if (elem.attr("abs:src").toLowerCase().contains("mfiles")) {
urlImage = elem.attr("abs:src").replace("thumb-", "");
Log.i("GridVerticalFragment", "Pillando url: " + urlImage);
ImageObject image = new ImageObject(urlImage);
Log.i("GridVerticalFragment", "Url Pillada: " + image.getUrl());
imageList.add(image);
}
}
}
Log.i("Logo", "Lista2: "+imageList.size());
}
public void getResponse(String urlRoot, int pagina) {
Log.i("GridVerticalLayaout", "Pagina: "+pagina);
String url;
String urlFinal = "";
if(pagina==0){
url = urlRoot;
urlFinal = url;
}else{
url = urlRoot.concat("?page="+Integer.toString(pagina));
urlFinal = url;
}
RequestQueue rq = Volley.newRequestQueue(context);
Log.i("GridVerticalLayaout", "fuuck: "+url);
Log.i("GridVerticalLayaout", "lool: "+urlFinal);
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlFinal,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
doc[0] = Jsoup.parse(response);
getImages(doc[0]);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.e("ERROR", "Error occurred ", error);
}
});
rq.add(stringRequest );
}
}
And this is the main class:
public class Logo extends AppCompatActivity {
public List<ImageObject> GlobalImageList = new ArrayList<ImageObject>() ;
Document[] doc = new Document[1];
String url;
int pagAnterior = 0;
int i = 0;
Context context = null;
public ThreadPoolExecutor executor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logo);
getSupportActionBar().hide();
Collection<Callable<String>> callableList = new ArrayList<>();
context = getApplication();
int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
executor = new ThreadPoolExecutor(
NUMBER_OF_CORES*2,
NUMBER_OF_CORES*2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()
);
while(i<4){
callableList.add(new ImageScraper(this,"www.google.es,i,i-1););
i++;
}
List<Future<String>> result = null;
try {
result = executor.invokeAll(callableList);
} catch (InterruptedException e) {
Log.i("Fallo", "Fallo");
e.printStackTrace();
}
for (Future a : result) {
String SingleImageList = null;
try {
SingleImageList = (String) a.get();
Log.i("Single", "Single"+SingleImageList);
} catch (InterruptedException e) {
Log.i("Fallo3", "Fallo3");
e.printStackTrace();
} catch (ExecutionException e) {
Log.i("Fallo2", "Fallo2");
e.printStackTrace();
}
}
}
}
This doesn't return anything but the scraper do his job,( the getImages() and getResponse() do the job and updates the list , instead if in this part of the code in MainClass:
while(i<4){
callableList.add(new ImageScraper(this,"www.google.es,i,i-1););
i++;
}
If I change that for this( the class is not called the callable is created in the class), it works, the string is returned:
while(i<4){
callableList.add(new Callable<String>() {
public String call() throws Exception {
return "haha";
}
});
i++;
}
Someone can help me with this? I've been reading a lot and according to what I've read, what I have in the Scraper class is fine, but I still don't get it.
Sorry for the bad english, Im trying to :), I don't want to return an string I want to return an ArrayList, im returning a string in the code because thought it was a problem for returning ArrayList, but it seems like that is not that, and again, Thanks!
Please check this line of code
while(i<4){
callableList.add(new ImageScraper(this,"www.google.es,i,i-1););
i++;
}
You are not closing the double quotes!
Instead, try this code
while(i<4){
callableList.add(new ImageScraper(this,"www.google.es",i,i-1););
i++;
}
I am adding String returned by Callback method from Volley's onRespond method.
I have already initialized GetterAndSetter Method inside OnCreate Method.
this is my code:
onRespond(){
...
AddtoList(CreateURL, new VolleyCallback() {
#Override
public void onSuccess(String result) {
getterAndSetter.addString(result);
}
});
....
}
My GetterAndSetter Class:
public class GetterAndSetter {
ArrayList<String> strings = new ArrayList<>();
public void addString(String string) {
this.strings.add(string);
}
public ArrayList<String> getList(){
return this.strings;
}
}
I tries to get all the strings added inside of this getterandsetter's ArrayList via following code inside my another method :
void LoadImages(MainActivity mainActivity){
...
List<String> details = getterAndSetter.getList();
Log.d("gs", getterAndSetter.getList().toString());
...
}
As seen above, I tried to print log, but it print "[]"(Empty String). I have seen alot of Answers on Stackoverflow, but can't solve my problem.
Update : I am adding more code so that you guys can understand the problem.
My OnCreate Method :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
getterAndSetter = new GetterAndSetter();
LoadImages(this);
}
LoadImages :
private void LoadImages(MainActivity mainActivity) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mView.dismiss();
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
List<String> details = getterAndSetter.getList();
Log.d("gs", getterAndSetter.getList().toString());
for (String urls : urlList) {
Log.d("urls", urls);
}
for (String title : titles) {
Log.d("tts", title);
}
for (String dt : details) {
Log.d("dts", dt);
}
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
JSONObject root = new JSONObject(URL);
JSONObject photos = root.getJSONObject("photos");
JSONArray photo = photos.getJSONArray("photo");
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL, new VolleyCallback() {
#Override
public void onSuccess(String result) {
getterAndSetter.addString(result);
}
});
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
AddtoList Method :
public void AddtoList(String CreateURL, VolleyCallback volleyCallback) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject root;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String str = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
volleyCallback.onSuccess(str);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My CallBack
public interface VolleyCallback {
void onSuccess(String result);
}
The problem is that you're trying to print the list BEFORE the callback is being invoked by Volley.
You parse a Json and for each element, you make a new request. After parsing the Json you print the list, it's empty because of the calls you make aren't ended at the moment you print the list.
You need to wait until all the request you start from inside the loop have ended.
The first URL returns a list of names and IDs of farmers markets:
https://search.ams.usda.gov/farmersmarkets/v1/data.svc/locSearch?lat=" + latitude + "&lng=" + longitude
Then, the ID from the above URL must be used to get further information from each farmers market:
"https://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id
I want to display the name of the farmers markets from the first URL, and then the address of each farmers market from the second URL. How can I do this so that it all proceeds in the correct order?
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private ListView mListView;
GPSTracker gps;
Context mContext;
String marketAddress;
ArrayList<String> marketAddressArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView = (ListView) findViewById(R.id.list_view);
double latitude = 45.496481;
double longitude = -122.573462;
gps = new GPSTracker(mContext, MainActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
else {
gps.showSettingsAlert();
}
final String marketUrl = "https://search.ams.usda.gov/farmersmarkets/v1/data.svc/locSearch?lat=" + latitude + "&lng=" + longitude;
Log.d(TAG, String.valueOf(latitude));
Log.d(TAG, String.valueOf(longitude));
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(marketUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
Log.d(TAG, "failure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
final String jsonData = response.body().string();
Log.v(TAG, "THIS IS MY JSONDATA " + jsonData);
if (response.isSuccessful()) {
Log.d(TAG, marketUrl);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getCurrentDetails(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Log.v(TAG, jsonData);
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
Log.d(TAG, "Main UI code is running!");
}
private void getCurrentDetails(String jsonData) throws JSONException {
JSONObject usdaJSON = new JSONObject(jsonData);
JSONArray resultsJSON = usdaJSON.getJSONArray("results");
Market[] markets = new Market[resultsJSON.length()];
for(int i = 0; i < resultsJSON.length(); i++){
final JSONObject marketJSON = resultsJSON.getJSONObject(i);
String marketname = marketJSON.getString("marketname");
String id = marketJSON.getString("id");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
Log.d(TAG, "failure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
final String marketDetailsJsonData = response.body().string();
Log.v(TAG, "THIS IS MY JSONDATA " + marketDetailsJsonData);
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject detailsJSON = new JSONObject(marketDetailsJsonData);
JSONObject marketDetailsJSON = detailsJSON.getJSONObject("marketdetails");
marketAddress = marketDetailsJSON.getString("Address");
marketAddressArrayList.add(marketAddress);
//marketAddressArrayList.get(0);
//updateMarketAddress(); call this method for each market found - it will run 20 times if there are 20 markets
Log.d(TAG, "this is marketadress"+ marketAddress);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "broken");
}
}
});
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
Log.d(TAG, "outside of the loop"+ marketname);
Market market = new Market(marketname, id, marketAddress);
markets[i] = market;
//markets[i].setAddress(marketAddressArrayList.get(i));
}
MarketAdapter adapter = new MarketAdapter(this, markets);
mListView.setAdapter(adapter);
for(int i = 0; i < resultsJSON.length(); i++) {
Log.d(TAG, markets[i].getMarketname());
Log.d(TAG, markets[i].getId());
// Log.d(TAG, markets[i].getMarketAddress());
}
}
}
First, extract out all the JSON parsing (for example, use Retrofit instead of OkHTTP) and UI updating to a separate method.
Then, hit the first URL, from that onResponse, hit the second URL.
Basically, what you are doing now,
if (response.isSuccessful()) {
Log.d(TAG, marketUrl);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getCurrentDetails(jsonData); // Call the second URL
But it doesn't need to be on the UI thread if you aren't updating the UI
Your for loop at the end must be within the second onResponse body, where the adapter/list would be populated.
Also, MarketAdapter should probably use List<Market> instead of ArrayList<String>
I am having trouble with my listblogs=parseJSONResponse(result), result is underlined red and if I hover over it it says that, I cannot apply a parseJsonResponse JSONARRAY to a JSONARRAY[]. Does anyone know why this is being caused does it have something to do with the params?
class YourTask extends AsyncTask<JSONArray, String, ArrayList<Blogs> > {
#Override
protected ArrayList<Blogs> doInBackground(JSONArray... result) {
listblogs.clear(); // here you clear the old data
listblogs=parseJSONResponse(result);
return listblogs;
}
#Override
protected void onPostExecute(ArrayList<Blogs> blogs) {
mAdapterDashBoard.setBloglist(listblogs);
}
}
private void JsonRequestMethod() {
final long start = SystemClock.elapsedRealtime();
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.print(response);
listblogs = new YourTask().doInBackground();
listblogs.clear();
listblogs=parseJSONResponse(response);
try {
listblogs = new YourTask().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(response);
Log.d("Testing", "Time elapsed: " + (SystemClock.elapsedRealtime() - start));
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String studentId = currentQuestions.getString("studentId");
String DateCreated=currentQuestions.getString("created");
long time=Long.parseLong(DateCreated.trim());
data.append(text + "\n" + points + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
//The dateCreated was off by 1 hour so 3600000 ms where added=1hour, (UPDATE)
blogs.setDateCreated(getTimeAgo(time));
System.out.println(time + "time");
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
AsyncTask
public class MyAsyncTask extends AsyncTask<Void, Void, ArrayList> {
JsonArray myJsonArray;
#Override
protected void onPreExecute() {
super.onPreExecute();
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
listblogs.clear();
}
#Override
protected ArrayList doInBackground(Void... params) {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
myJsonArray = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(request);
return null;
}
#Override
protected void onPostExecute(ArrayList arrayList) {
super.onPostExecute(arrayList);
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < myJsonArray.length(); i++) {
JSONObject currentQuestions = myJsonArray.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String studentId = currentQuestions.getString("studentId");
String DateCreated=currentQuestions.getString("created");
long time=Long.parseLong(DateCreated.trim());
data.append(text + "\n" + points + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
//The dateCreated was off by 1 hour so 3600000 ms where added=1hour, (UPDATE)
blogs.setDateCreated(getTimeAgo(time));
System.out.println(time+"time");
blogsArrayList.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
return blogsArrayList;
}
ArrayList
synchronous:
listblogs = new MyAsyncTask().execute().get();
asynchronous:
....
} catch (JSONException e) {
e.printStackTrace();
}
listblogs = blogsArrayList;
return blogsArrayList;
}
new MyAsyncTask().execute();
you can run any code inside an async task like this:
public class YourTask extends AsyncTask<String, Void, ArrayList<Blogs> > {
private static final String TAG = YourTask.class.getSimpleName();
private JSONArray mResponse;
private Activity mActivity;
public YourTask(final Activity activity, final JSONArray response) {
super();
this.mActivity = activity;
this.mResponse = response;
}
#Override
protected ArrayList<Blogs> doInBackground(String... params) {
if (!mResponse.equals("")) {
// Your Code
}
return listblogs;
}
#Override
protected void onPostExecute(final ArrayList<Blogs> blogs) {
if (mActivity instanceOf YourActivity) {
((YourActivity) activity).finishTask(blogs);
}
}
#Override
protected void onCancelled() {}
}
call this Task from your activity like:
AsyncTask<String, Void, JSONArray> task = new YourTask(this, response);
task.executeContent();
Basically just send the JSONArray you want to parse to the Async Task and handle all the UI in den finishTask method in your Activity. The advantage is that you can extract your task in an extra file and leave your activity to just handle controlling your views.