Have the following AsyncTask code:
private class checkChangesTask extends AsyncTask<String, Void, String> {
protected ProgressDialog mProgressDialog2;
protected String _url = "", _idautor="", _idbook="";
#Override
protected void onPreExecute() {
super.onPreExecute();
this.mProgressDialog2 = new ProgressDialog(MainActivity.this);
this.mProgressDialog2.setMessage("Check changes ...");
this.mProgressDialog2.setIndeterminate(false);
this.mProgressDialog2.setCanceledOnTouchOutside(false);
this.mProgressDialog2.setCancelable(true);
this.mProgressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.mProgressDialog2.setMax(100);
this.mProgressDialog2.setProgress(0);
this.mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[0];
_idbook = params[1];
_url = params[2];
try {
doc = Jsoup.connect(_url).userAgent("Mozilla").get();
Elements dd = doc.select("dd");
int size = dd.size();
int p = 1;
for (Element src : dd) {
this.mProgressDialog2.setProgress(p*100/size);
if (p <= size-1){
_html += src.outerHtml();
++p;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
String lastfile = readPageFile(_idautor + "_" + _idbook);
if(!lastfile.equals(result)){
savePageToFile(_idautor + "_" + _idbook, result);
}
}else{
Toast.makeText(MainActivity.this, "Error checkChangesTask", Toast.LENGTH_SHORT).show();
}
this.mProgressDialog2.dismiss();
}
the previous code I call in a loop:
public void checkChanges() {
String[][] db_books = db.selectAllBOOKS();
if (db_books.length>0){
for (int j = 0; j < db_books.length; j++){
new checkChangesTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, db_books[j][1], db_books[j][0], db_books[j][2]);
}
}
}
Everything works fine, but the dialog does not display the correct value. First, it is worth it to 0% and then abruptly switches to 100%.
AsyncTask called in sequence (...executeOnExecutor(AsyncTask.SERIAL_EXECUTOR...).
If you run a AsyncTask not in the loop, all the displays are just perfect!
android: targetSdkVersion = "14"
I ask your help.
You need to use onProgressUpdate() inside the AsyncTask. Something like this (at a guess)
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
this.mProgressDialog2.setProgress(progress[0] * 100/progress[1]);
}
And replace this line:
this.mProgressDialog2.setProgress(p*100/size);
With this:
publishProgress(new int[]{p,size})
Related
I'd like to get the string value output from AsyncTask. And store it into a variable on my main thread. How can I do so?
I tried to do store = new ReceiveData().execute().get() however it throws an execution exception error. But anyway, my question is not about the execution exception error. I just need a way to get the string out, please help!
Here is my activity code:
public class MainActivity extends AppCompatActivity { //MAIN ACTIVITIES (REMOTE)
double multiplier;
int seekbarvalue, finallumens;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); //On orientation change socket will disconnect...
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toast.makeText(MainActivity.this, LoginActivity.SERVER_IP, Toast.LENGTH_LONG).show();
//================START AFTER DEFAULT ON CREATE=================
SeekBar seekbarbrightness = (SeekBar) findViewById(R.id.seekbarbrightness);
final TextView tblumens, tbvolts, tbamps;
tblumens = (TextView) findViewById(R.id.tblumens);
seekbarvalue = seekbarbrightness.getProgress();
multiplier = (double) seekbarvalue / 100;
finallumens = (int) (multiplier * LoginActivity.enterlumens);
tblumens.setText(String.valueOf(finallumens) + " Lumens");
tbvolts = (TextView) findViewById(R.id.tbvolts);
tbamps = (TextView) findViewById(R.id.tbamps);
seekbarbrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekbarbrightness, int progress, boolean b) {
if (b == true) {
seekbarvalue = seekbarbrightness.getProgress();
multiplier = (double) seekbarvalue / 100;
finallumens = (int) (multiplier * LoginActivity.enterlumens);
tblumens.setText(String.valueOf(finallumens) + " Lumens");
if (LoginActivity.getSocket() != null) {
try {
LoginActivity.getSocket().getOutputStream().write(String.valueOf(multiplier).getBytes());
new ReceiveData().execute();
//infinite loop here to keep receiving volts and amperes.
//Do a split and assign value to volt and amp
//String[] strrecv= store.split("|");
//String volts = strrecv[0];
//String amps = strrecv[1];
//tbvolts.setText("Voltage: " + volts + " V");
//tbamps.setText("Amperes:" + amps + " A");
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "NOT connected To Socket, please disconnect and reconnect!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
And in my Asynctask I am doing this.
class ReceiveData extends AsyncTask<Void, Void, String> {
String str;
protected String doInBackground(Void... args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
str = in.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
String str = "fail";
return str;
}
}
protected void onPostExecute(String str) {
//super.onPostExecute(str);
}
}
The purpose of AsyncTask is to perform asynchronous task in a separate thread to free the main thread and avoid UX issues. For your purpose, I suggest transferring all of the work inside your try block inside the AsyncTask and update the UI after execution.
Something like this
In MainThread
new ReceiveData().execute();
In AsyncTask
class ReceiveData extends AsyncTask<Void, Void, Boolean> {
String volts;
String amps;
protected Boolean doInBackground(Void... args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
str = in.readLine();
String[] strrecv= store.split("|");
volts = strrecv[0];
amps = strrecv[1];
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
protected void onPostExecute(Boolean result) {
if (result) {
tbvolts.setText("Voltage: " + volts + " V");
tbamps.setText("Amperes:" + amps + " A");
}
}
}
Note that this only works if your AsyncTask is defined inside your Activity. If not, you need to create an interface from the AsyncTask and implement it in your activity and activate it onPostExecute
I have 2 asyncTasks. One for GetCheckLists another for GetCheckListItems.
In CheckList class, it has checkListId,Title,etc and arrayList of checkListItems.
First I get all the checkLists using GetCheckListAsyncTask. Now for each checkList I am calling GetCheckListItemsAsync task to get all the checkListItems.
Now onPostExecute method of GetCheckListItemsAsyncTask I want to set the checkListItemArrayList.
How can I make sure to add checkListItemArrayList to checkList item's object?
CheckListActivity:
public class CheckListActivity extends AppCompatActivity implements CheckListAdapter.OnItemClickListener{
private ProgressDialog progressDialog;
private RecyclerView recyclerView;
private ArrayList<CheckList> checkLists = new ArrayList<>();
private CheckList mCheckList;
private ArrayList<CheckListItem> itemList;
private ArrayList<CheckList> checkListArrayList;
private CheckListAdapter mAdapter;
JSONArray checkListsItemArray,checkListArray;
public int iterationCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_list);
checkListArrayList = new ArrayList<>();
mEventId = mIntent.getStringExtra("eventId");
mCheckList = new CheckList();
progressDialog = new ProgressDialog(CheckListActivity.this);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
mAdapter = new CheckListAdapter(checkListArrayList,CheckListActivity.this,CheckListActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
GetCheckListAsyncTask getCheckListAsyncTask = new GetCheckListAsyncTask();
getCheckListAsyncTask.execute(mEventId);
}
}
#Override
public class GetCheckListsItemAsyncTask extends AsyncTask<String, Void, JSONObject> {
private String api;
private JSONObject jsonParams;
public GetCheckListsItemAsyncTask(){}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = getResources().getString(R.string.server_url) + "api/checklist_items/getChecklistItems.php";
jsonParams = new JSONObject();
String checklistId = params[0]; // params[0] is username
jsonParams.put("checklistId", checklistId);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1) {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
checkListsItemArray = response.getJSONArray("checklistItems");
for (int i = 0; i < checkListsItemArray.length(); i++) {
int pendingTasks = 0,completedTasks = 0;
itemList = new ArrayList<>();
CheckListItem checkListItem = new CheckListItem();
JSONObject subObject = checkListsItemArray.getJSONObject(i);
String checkListItemName = subObject.getString("text");//name of the attribute in response
String checkListItemBudget = subObject.getString("budget");//name of the attribute in response
String checkListItemTimedate = subObject.getString("time_due");
String checkListItemReminder = subObject.getString("reminder");
String checkListItemId = subObject.getString("checklistItemId");
String checkListItemStatus = subObject.getString("status");
if (checkListItemStatus.equals("1")) {
completedTasks++;
}
if (checkListItemStatus.equals("0")) {
pendingTasks++;
}
checkListItem.setTitle(checkListItemName);
checkListItem.setBudget(checkListItemBudget);
checkListItem.setDateTime(checkListItemTimedate);
checkListItem.setReminder(checkListItemReminder);
checkListItem.setCheckListItemId(checkListItemId);
checkListItem.setStatus(checkListItemStatus);
checkListItem.setPendingItem(pendingTasks);
checkListItem.setCompletedItem(completedTasks);
itemList.add(checkListItem);//adding string to arraylist
}
if(checkListArrayList.size() < iterationCount) {
iterationCount++;
String checkListId =
checkListArrayList.get(iterationCount).getCheckListId();
CheckList checkList1 = checkListArrayList.get(iterationCount);
checkList1.setCheckListItemArrayList(itemList);
}
mAdapter.notifyDataSetChanged();
}
else {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(CheckListActivity.this, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
public class GetCheckListAsyncTask extends AsyncTask<String, Void, JSONObject> {
private String api;
private JSONObject jsonParams;
public GetCheckListAsyncTask(){}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = getResources().getString(R.string.server_url) + "api/checklist/getChecklists.php";
jsonParams = new JSONObject();
String eventId = params[0]; // params[0] is username
jsonParams.put("eventId", eventId);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
//Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
checkListArray = response.getJSONArray("checklists");
for (int i = 0; i < checkListArray.length(); i++) {
CheckList checkList = new CheckList();
JSONObject subObject = checkListArray.getJSONObject(i);
String checkListName = subObject.getString("checklist");//name of the attribute in response
String checkListBudget = subObject.getString("budget");//name of the attribute in response
String checkListIcon = subObject.getString("icon");
String checkListId = subObject.getString("checklistId");
checkList.setCheckListTitle(checkListName);
checkList.setBudget(checkListBudget);
checkList.setImageIcon(checkListIcon);
checkList.setCheckListId(checkListId);
checkListArrayList.add(checkList);
iterationCount++;
new GetCheckListsItemAsyncTask().execute(checkListId);
mAdapter.notifyDataSetChanged();
}
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
Toast.makeText(CheckListActivity.this, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(CheckListActivity.this, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
}
How to set CheckListItemsArrayList to the objects of checkListArrayList sequence wise? Please help. Thank you..
You need to elaborate your question. It is very confusing.
But I think that you want to add items to your AsyncTask class.
You can use the Constructor Method for this.
GetCheckListAsyncTask getCheckListAsyncTask = new GetCheckListAsyncTask(checkListsItemArray);
getCheckListAsyncTask.execute(mEventId);
And for AsyncTask Just Add:
JSONArray m_checkListsItemArray;
public GetCheckListsItemAsyncTask(JSONArray checkListsItemArray){
m_checkListsItemArray = checkListsItemArray;
//Do something here with checkListsItemArray;
}
And use m_checkListsItemArray anywhere in the AsycTask class.
Each time you start a task, you have no control when it ends. The tasks are running Asynchronously so they won't end in the order you start them. Maybe have a field level Array or ArrayList that adds results each time a task ends and then when everyhthing has ended you can work with the array results.
I have been trying to work on an app in which after clicking ,a new activity opens up and loads the data from the url.
Here is the new activity code
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
dialog.setMessage("Processing");
dialog.setIndeterminate(true);
dialog.show();
dialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
JSONObject jsonObject = new JSONObject();
String url = " http://www.trailermag.com/tsappapis/?request=featuredAdList";
JSONArray trailersJSON = jsonObject.getJSONArray(url);
for (int i = 0; i < trailersJSON.length(); i++) {
Trail aTrail = new Trail();
JSONObject contactObject = trailersJSON.getJSONObject(i);
aTrail.id = contactObject.getString(V_Id);
aTrail.image = contactObject.getString(V_Image);
aTrail.title = contactObject.getString(V_Title);
aTrail.price = contactObject.getString(V_Price);
webData.add(aTrail);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
System.out.println("IN POST EXE");
dialog.dismiss();
}
}
}
Once try and replace this code with your code this will work and i have tested it.
JSONArray mJsonArray = new JSONArray(response);
for (int i = 0; i < mJsonArray.length(); i++) {
JSONObject mJsonObject = mJsonArray.getJSONObject(i);
String idStr = mJsonObject.getString("id");
String imageStr = mJsonObject.getString("image");
String titleStr = mJsonObject.getString("title");
String priceStr = mJsonObject.getString("price");
}
Happeee...Programming....
the code i am using is working very fine for me but the problem is i am not able to fetch that data in main activity
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String firstname = c.getString("firstname");
String lastname = c.getString("lastname");
String username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
this is the code new AsyncTaskParseJson().execute(); to make this thing work
but i need to run
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
}`
I want to get the data like firstname , lastname , username as variable in main activity .
Is it possible ??
this is my other class IncomingCall.java when i want to get the variables
public class IncomingCall extends BroadcastReceiver {
private String firstname;
private String lastname;
private String username;
public void onReceive (Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, " Calling "+username, Toast.LENGTH_LONG).show();
try {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {
notifyuser=true;
}
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(context, "Error detected 1 "+e, Toast.LENGTH_LONG).show();
}
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
// loop through all users
// for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(0);
// Storing each json item in variable
firstname = c.getString("firstname");
lastname = c.getString("lastname");
username = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
// }
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//Here you use your variables
}
});
return null;
}
protected void onPostExecute(String strFromDoInBg) {
Log.e("TAG1", "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
}
this is my code
The method onPostExecute runs on the main thread, You need to use the data once the doInBackground finishes and control return to the main thread.
Better you use these data in the method
protected void onPostExecute(String strFromDoInBg) {
// use the firstname , lastname or username after this method call.
}
Put your code in your Main Activity class, and then use class variables to store what you want, e.g.:
public class MainActivity extends Activity {
private String[] firstname;
private String[] lastname;
private String[] username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskParseJson().execute();
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("Users");
firstname = new String[dataJsonArr.length()];
lastname = new String[dataJsonArr.length()];
username = new String[dataJsonArr.length()];
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
firstname[i] = c.getString("firstname");
lastname[i] = c.getString("lastname");
username[i] = c.getString("username");
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
+ ", lastname: " + lastname
+ ", username: " + username);
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//Here you use your variables
}
});
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
}
Something like this (it's without error checking, give it a try)
EDIT: be sure to have declared the internet permission in the android manifest:
<uses-permission android:name="android.permission.INTERNET" />
I have created a simple Activity. The activity is responsible for downloading data from parse.com database and populating a linear layout. In the process, I am dynamically creating the linear layout with TextViews and ImageViews according according to the content.
The problem is that, whenever I try to download an image, I use as AsyncTask Downloading class, which results in slowing down the UI thread! I am currently trying to return the bitmap file from the AsyncTask Image downloading class using: returnedBitmap = new LoadImage().execute(src).get(); which might be responsible for slowing down the UI thread. I have to do this because the caller method geneterImageView will return an imageview when it receives the bitmap file.
The complete Activity code:
public class MainActivity extends ActionBarActivity {
ArrayList<String> heightList = new ArrayList<String>();
ArrayList<String> reversedList = new ArrayList<String>();
ImageView imageView1;
Bitmap bitmap;
RelativeLayout parent_layout;
ParseObject user;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// imageView1 = (ImageView)findViewById(R.id.imageView1);
parent_layout = (RelativeLayout) findViewById(R.id.parent_layout);
login("xyz#xyz.com", "xyz");
}
private void loopThroughArrayAndAttach(){
LinearLayout llInner = new LinearLayout(this);
llInner.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
parent_layout.addView(llInner);
for (int i = 0; i < heightList.size(); i++) {
if (hasNoImagess(heightList.get(i)) == true) {
// No images.
TextView myText = geneterTextView(heightList.get(i));
llInner.addView(myText);
// geneterTextView(heightList.get(i));
} else {
ImageView myImage = geneterImageView(heightList.get(i));
llInner.addView(myImage);
// geneterImageView(heightList.get(i));
}
}
}
public static boolean hasNoImagess(String contents){
Document doc = Jsoup.parse(contents);
Element element = doc.body();
Elements elements = element.select("img");
if (elements.isEmpty()) {
return true;
} else {
return false;
}
}
public ImageView geneterImageView(String imgContent){
// Will need to run via background thread - like aysnc
// Extract the image file via jsoup
// Insert it into a imagevieww
// Inser that into a layout.
Log.d("IN IMAGE ", " " + imgContent);
Document doc = Jsoup.parse(imgContent);
Elements img = doc.getElementsByTag("img");
Bitmap returnedBitmap = null;
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("src attribute is : " + src);
// new DownloadImageTask((ImageView)
// findViewById(R.id.imageView1)).execute(src);
try {
returnedBitmap = new LoadImage().execute(src).get();
// imageView1.setImageBitmap(returnedBitmap);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageView iv = new ImageView(this);
iv.setImageBitmap(returnedBitmap);
return iv;
}
public TextView geneterTextView(String textContent){
// Will need to run via background thread.
Log.i("In TEXT ", " " + textContent);
TextView tv = new TextView(this);
tv.setText(Html.fromHtml(textContent));
return tv;
}
// to download images
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
protected Bitmap doInBackground(String... args){
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image){
if (image != null) {
} else {
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
// to login to parse
private void login(final String username, String password){
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e){
if (e == null) {
// if login sucess
// Start intent
// loginSuccess();
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
CloudCallStudentPosts(user);
} else {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
}
});
}
// //to get data from parse
public void CloudCallStudentPosts(ParseObject s){
setRichStory(s);
}
private void setRichStory(ParseObject s){
// Simialr to setStory, once implemented delete setStory()
new AddStoryAsync(s).execute();
}
class AddStoryAsync extends AsyncTask<Void, Object, Void> {
private static final String TAG = "LazyListView";
ParseObject s;
public AddStoryAsync(ParseObject s) {
this.s = s;
Log.w("In richStory", "ParseObject Id: " + s.getObjectId());
}
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... unused){
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userid", this.s.getObjectId());
params.put("skip", 0);
ParseCloud.callFunctionInBackground("studentsPosts", params, new FunctionCallback<List<List<ParseObject>>>() {
#Override
public void done(List<List<ParseObject>> postList, com.parse.ParseException arg1){
if (postList == null) {
} else {
if (postList.size() > 0) {
// CustomWebView cwb;
for (int i = 0; i < postList.size(); i++) {
// final Post post = new Post();
if (postList.get(i).get(0).get("htmlContent") == null) {
}
if (postList.get(i).get(0).get("htmlContent") != null) {
Log.e("htmlContent parse", postList.get(i).get(0).get("htmlContent").toString());
// Parse HTML String using JSoup library
String HTMLSTring = postList.get(i).get(0).get("htmlContent").toString();
Document html = Jsoup.parse(HTMLSTring);
Elements paragraphs = html.getElementsByTag("p");
for (org.jsoup.nodes.Element paragraph : paragraphs) {
String paragraphText = paragraph.toString();
Log.e("paragraphText", paragraphText);
heightList.add(paragraphText);
}
loopThroughArrayAndAttach();
}
}
}
}
}
});
return (null);
}
#Override
protected void onProgressUpdate(Object... object){
Log.w("onProgressUpdate ", " " + object[0].getClass());
Log.w("adding to arrayPostList ", " " + object[0].getClass());
}
#Override
protected void onPostExecute(Void unused){
}
}
}
Is there any substitute for getting the bitmap from the AsyncTask and set it in the imageview? Should there be a logical alteration in the approach?
try this :
dont call get() #praveen. instead pass the imageview Reference in the constructor
WorkerThread mWorkerThread = new WorkerThread(mImageView);
mWorkerThread.execute(src);
private class WorkerThread extends AsyncTask<String, String, Bitmap> {
private WeakReference<ImageView> imageViewReference;
public WorkerThread(ImageView imageView) {
super();
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... args) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null && imageViewReference.get() != null) {
imageViewReference.get().setImageBitmap(result);
}
}
}
Don't call get() method on AsyncTask it makes main thread to wait for AsyncTask to complete. If you really want to start something only after AsyncTask completes put that into onPostExecute() of your AsynTask
As others have mentioned, your code has several design flaws which makes it difficult to provide you a solution to your problem.
The whole purpose of an AsyncTask is to execute on a background thread. Executing networking and bitmap processing on the main thread will never work. You must refactor your code to accommodate this. Consider the following solution to this particular problem at least:
// to download images
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... args) {
String imgContent = args[0];
Document doc = Jsoup.parse(imgContent);
Elements img = doc.getElementsByTag("img");
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("src attribute is : " + src);
try {
return BitmapFactory.decodeStream((InputStream) new URL(src).getContent());
} catch (Exception e) {
// log
}
}
return null;
}
protected void onPostExecute(Bitmap b) {
ImageView iv = new ImageView(MainActivity.this);
iv.setImageBitmap(b);
llInner.addView(iv);
}
}
You can then do something like:
for (int i = 0; i < heightList.size(); i++) {
new LoadImage(heightList.get(i)).execute();
}
However, this may not be desirable depending on how many AsyncTasks you end up creating. But this is the idea.