How can i print arraylist from class AsyncTask? - android

I want to print an ArrayList. I have receive value arraylist from class AsyncTask, in MainActivity, I have value ArrayList, but when I print ArrayList, my app is not working. Please help me!
MainActivity
{
executeLoadProduct();
arraylistgroup = new ArrayList<String>();
arraylistgroup=TaskLoadProductGroup.getvaluearraylist();
String[] mStringArray = new String[arraylistgroup.size()];
mStringArray = arraylistgroup.toArray(mStringArray);
for (int i = 0; i < mStringArray.length; i++) {
System.out.println("string is2" + (String) mStringArray[i]);
}
executeLoadProduct
private void executeLoadProduct() {
// execute task load product
loadProductGroup = new TaskLoadProductGroup(MainActivity.this);
loadProductGroup.execute();
}
AsyncTask
public class TaskLoadProductGroup extends AsyncTask<String, Void, ArrayList<String>> {
private ActionBarActivity actionBarActivity;
private Context context;
private static ArrayList<String> arrayListgroup;
public TaskLoadProductGroup(ActionBarActivity actionBarActivity) {
this.actionBarActivity = actionBarActivity;
this.context = actionBarActivity.getApplicationContext();
}
#Override
protected void onPreExecute() {
///show progress loading
super.onPreExecute();
}
#Override
protected ArrayList<String> doInBackground(String... url) {
ArrayList<String> listProductgroup = null;
try {
Server server = new Server();
ResListProduct resListProduct = server.getListProducts(context);
//init list item for listview home product
listProductgroup = initItemProduct(resListProduct);
} catch (Exception e) {
}
return listProductgroup;
}
public static ArrayList<String> initItemProduct(ResListProduct rsProduct) {
List<GroupProduct> groups = rsProduct.getGroups();
arrayListgroup = new ArrayList<String>();
for (GroupProduct group : groups) {
// add header group
String s = group.getName();
arrayListgroup.add(s);
}
getvaluearraylist();
// getVarialty();
return arrayListgroup;
}
public static ArrayList<String> getvaluearraylist()
{
return arrayListgroup;
}
#Override
protected void onPostExecute(ArrayList<String> listProductgroup) {
super.onPostExecute(listProductgroup);
}
}

I couldn't identify why are you doing so complex code to print the ArrayList. You can just print that inside onPostExecute method like this,
#Override
protected void onPostExecute(ArrayList<String> listProductgroup) {
super.onPostExecute(listProductgroup);
for (String value : listProductgroup){
Log.d("myTag", value);
}
}
OR
Use loadProductGroup.execute().get() method, but remember this will freeze your UI.

Related

After pressing back button, previous activity (listview) is emtpty

In my android project i have a listview with items loaded from an online database. When i click on an item i go to another class where i can delete or update it. My problem is that when i press the back button, my listview is empty. I tried onBackPressed with intent to go to previous activity but it is empty again. I want to reload my listview when from a clicked item i press the back button. Below is my code.
The listview:
public class AllStudents extends AppCompatActivity {
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://sissy-nickels.000webhostapp.com/AllStudentData.php";
List<String> IdList = new ArrayList<>();
String LessonName;
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
String FinalJSonObject;
HashMap<String,String> ResultHash = new HashMap<>();
String ParseResult ;
List<Student> studentList;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allstudents);
StudentListView = (ListView)findViewById(R.id.listview2);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
LessonName = getIntent().getStringExtra("Lesson");
HttpWebCall(LessonName);
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(AllStudents.this,SingleStudent.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
//finish();
}
});
search = (EditText)findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
// when text is entered in search box, filter list by search text
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
filterStudents(cs);
}
#Override
public void afterTextChanged(Editable s) {
}
});
// check student's name whether contain text entered in search box
}
public void HttpWebCall(final String LessonName){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(AllStudents.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(AllStudents.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("LessonName",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpUrl);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(LessonName);
}
// JSON parse class started from here.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Student student;
studentList = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
student = new Student();
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
student.StudentName = jsonObject.getString("Regnum").toString();
studentList.add(student);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(studentList, context);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private void filterStudents (CharSequence cs) {
List<Student> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(cs)) {
// no text is entered for search, do nothing
return;
}
// build new student list which filtered by search text.
for (Student student : studentList) {
if (student.StudentName.contains(cs)) {
filteredList.add(student);
}
}
// show filtered list in listview
ListAdapter adapter = new ListAdapter(filteredList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}}
And the code from item click:
public class SingleStudent extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://sissy-nickels.000webhostapp.com/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://sissy-nickels.000webhostapp.com/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView NAME,SURNAME,DEPT,REGNUM,GRADE;
String NameHolder, SurnameHolder, DeptHolder, RegnumHolder, GradeHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlestudent);
NAME = (TextView)findViewById(R.id.name);
SURNAME = (TextView)findViewById(R.id.surname);
DEPT = (TextView)findViewById(R.id.dept);
REGNUM = (TextView)findViewById(R.id.regnum);
GRADE = (TextView)findViewById(R.id.grade);
UpdateButton = (Button)findViewById(R.id.BDel);
DeleteButton = (Button)findViewById(R.id.BUp);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ListViewValue");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SingleStudent.this,StudentUpdate.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("name", NameHolder);
intent.putExtra("surname", SurnameHolder);
intent.putExtra("dept", DeptHolder);
intent.putExtra("regnum", RegnumHolder);
intent.putExtra("grade", GradeHolder);
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(SingleStudent.this, "Φόρτωση", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(SingleStudent.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(SingleStudent.this,"Φόρτωση",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(SingleStudent.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
NameHolder = jsonObject.getString("Name").toString() ;
SurnameHolder = jsonObject.getString("Surname").toString() ;
DeptHolder = jsonObject.getString("Dept").toString() ;
RegnumHolder = jsonObject.getString("Regnum").toString() ;
GradeHolder = jsonObject.getString("Grade").toString() ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
NAME.setText(NameHolder);
SURNAME.setText(SurnameHolder);
DEPT.setText(DeptHolder);
REGNUM.setText(RegnumHolder);
GRADE.setText(GradeHolder);
}
}}
Than you in advance!
try this on AllStudents activity
#Override
protected void onResume() {
super.onResume();
if (studentList != null && studentList.size()>0) {
ListAdapter adapter = new ListAdapter(studentList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
*Note
when you make a search you run the filterStudents() method
and replace the current list in the adapter
ListAdapter adapter = new ListAdapter(filteredList, this);
but make sure that if you search for nothing .. return the original list
ListAdapter adapter = new ListAdapter(studentList, this);
or you will get an empty list view
You should not recreate from secondActivity. You just finish it when your work is done in secondActivity. Which means, simply you have to do the below in your secondActivity.
#Override
public void onBackPressed() {
super.onBackPressed();
}

Update ListView periodically

In my code, I want to update ListView periodically say after every 10 seconds. As ListView is custom and data in ListView are populated from database, I need to refresh ListView periodically so that any changes in database can be reflected in ListView. I tried using Handler concept but it didn't help me. Below is my code. What needs to be done?
public class GetFriendDeviceId extends ListActivity {
String data = "";
String title;
ListView list;
CustomDeviceId adapter;
ArrayList<String> useridarr;
ArrayList<String> namearr;
ArrayList<String> regidarr;
ArrayList<String> statusarr;
String id;
String userid, name, regid;
private static final String USERID = "user_id";
private static final String NAME = "user_name";
private static final String REGID = "regId";
DBController contoller = new DBController(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getfriend_deviceid);
useridarr = new ArrayList<String>();
namearr = new ArrayList<String>();
regidarr = new ArrayList<String>();
statusarr = new ArrayList<String>();
// get user_id using sharedpreference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
id = preferences.getString("ID", "");
new GetContent().execute();
}
// asynctask to get content for selected title
public class GetContent extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(GetFriendDeviceId.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
useridarr.clear();
namearr.clear();
regidarr.clear();
statusarr.clear();
pdLoading.setMessage("\tPlease wait...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
final GetDeviceId getdb = new GetDeviceId();
new Thread(new Runnable() {
public void run() {
data = getdb.getDataFromDB(id);
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<User_DeviceId> users = parseJSON(data);
addData(users);
}
});
}
}).start();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pdLoading.dismiss();
}
}
public ArrayList<User_DeviceId> parseJSON(String result) {
ArrayList<User_DeviceId> users = new ArrayList<User_DeviceId>();
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
User_DeviceId user = new User_DeviceId();
user.setUser_id(json_data.getString(USERID));
user.setUser_name(json_data.getString(NAME));
user.setRegId(json_data.getString(REGID));
users.add(user);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return users;
}
#SuppressWarnings({ "rawtypes" })
public void addData(ArrayList<User_DeviceId> users) {
for (Iterator i = users.iterator(); i.hasNext();) {
User_DeviceId p = (User_DeviceId) i.next();
useridarr.add(p.getUser_id());
namearr.add(p.getUser_name());
regidarr.add(p.getRegId());
}
DBController.statusArray = statusarr;
contoller.getStatus(id, useridarr, 0);
adapter = new CustomDeviceId(GetFriendDeviceId.this, namearr, useridarr, statusarr);
list.setAdapter(adapter);
}
I tried this code
final Handler handler_new = new Handler();
handler_new.postDelayed( new Runnable() {
#Override
public void run() {
DBController.statusArray = MainActivity.result;
contoller.Status("100003818200590", "100007144268382", 0);
MainActivity.adapter.notifyDataSetChanged();
handler_new.postDelayed( this, 1000);
}
}, 1000);
But didn't work...
I just Edit your code hope this helps you
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ListView;
public class GetFriendDeviceId extends ListActivity {
String data = "";
String title;
ListView list;
CustomDeviceId adapter;
ArrayList<String> useridarr;
ArrayList<String> namearr;
ArrayList<String> regidarr;
ArrayList<String> statusarr;
String id;
String userid, name, regid;
private static final String USERID = "user_id";
private static final String NAME = "user_name";
private static final String REGID = "regId";
DBController contoller;
Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getfriend_deviceid);
contoller = new DBController(this);
useridarr = new ArrayList<String>();
namearr = new ArrayList<String>();
regidarr = new ArrayList<String>();
statusarr = new ArrayList<String>();
// get user_id using sharedpreference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
id = preferences.getString("ID", "");
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
new GetContent().execute();
}
});
}
}, 0, 10000);
}
// asynctask to get content for selected title
public class GetContent extends AsyncTask<Void, Void, ArrayList<User_DeviceId>> {
ProgressDialog pdLoading = new ProgressDialog(GetFriendDeviceId.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
useridarr.clear();
namearr.clear();
regidarr.clear();
statusarr.clear();
pdLoading.setMessage("\tPlease wait...");
pdLoading.show();
}
#Override
protected ArrayList<User_DeviceId> doInBackground(Void... params) {
final GetDeviceId getdb = new GetDeviceId();
data = getdb.getDataFromDB(id);
ArrayList<User_DeviceId> users = parseJSON(data);
return users;
}
#Override
protected void onPostExecute(ArrayList<User_DeviceId> result) {
super.onPostExecute(result);
addData(result);
pdLoading.dismiss();
}
}
public ArrayList<User_DeviceId> parseJSON(String result) {
ArrayList<User_DeviceId> users = new ArrayList<User_DeviceId>();
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
User_DeviceId user = new User_DeviceId();
user.setUser_id(json_data.getString(USERID));
user.setUser_name(json_data.getString(NAME));
user.setRegId(json_data.getString(REGID));
users.add(user);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return users;
}
#SuppressWarnings({ "rawtypes" })
public void addData(ArrayList<User_DeviceId> users) {
for (Iterator i = users.iterator(); i.hasNext();) {
User_DeviceId p = (User_DeviceId) i.next();
useridarr.add(p.getUser_id());
namearr.add(p.getUser_name());
regidarr.add(p.getRegId());
}
DBController.statusArray = statusarr;
contoller.getStatus(id, useridarr, 0);
adapter = new CustomDeviceId(GetFriendDeviceId.this, namearr, useridarr, statusarr);
list.setAdapter(adapter);
}
}
Constantly/Periodically polling for a change is not a good idea in general.
You should implement some thing like push notification when DB is updated for better performance. When a piece of code changes the content of DB, it should invoke all subscriber of listener/ or broadcast a message.
Your activity/fragment should implement that listener, and refresh the listview. This way your listview will be refreshed only when some changes occur in DB instead of looking for a change in DB and refresh itself.
A listview can be refreshed by modifying the backing datasource of listview.
namearr = newnamearr;
...
newnamearr is new contents for listview.
and then calling notifyDataSetChanged().
This piece of code is working but their could be better approach available.
import java.util.ArrayList;
public class ListenerTest {
public static void main(String[] args) {
// simulation for activities.
A a = new A();
a.simulateOnCreate();
B b = new B();
b.simulateOnCreate();
DBChanger obj = new DBChanger();
obj.changeDBContent();
}
}
// this is class where all DB changes will occur.
class DBChanger{
public void changeDBContent(){
// some piece of Code that change the DB code.
ArrayList<Listenable> subcribers = ListnerManager.getInstance().getSubscribersList();
for(Listenable l: subcribers){
l.onUpadateAvailable();
}
}
}
// This class should corresponds to Activity/Fragment in Android which will implement the listener
class A implements Listenable {
public void simulateOnCreate(){
ListnerManager maneger = ListnerManager.getInstance();
maneger.setOnListenable(this);
}
#Override
public void onUpadateAvailable() {
System.out.println("A---> onUpadateAvailable");
}
}
// This class is manager of listener.
class ListnerManager {
public static ListnerManager instance = new ListnerManager();
public static ListnerManager getInstance(){
if(instance == null){
instance = new ListnerManager();
}
return instance;
}
ArrayList<Listenable> subscriberlist = new ArrayList<Listenable>();
public void setOnListenable(Listenable subcsriber) {
subscriberlist.add(subcsriber);
}
public ArrayList<Listenable> getSubscribersList() {
return subscriberlist;
}
}
// Same as class A
class B implements Listenable {
public void simulateOnCreate(){
ListnerManager maneger = ListnerManager.getInstance();
maneger.setOnListenable(this);
}
#Override
public void onUpadateAvailable() {
// TODO Auto-generated method stub
System.out.println("B---> onUpadateAvailable");
}
}
interface Listenable {
public void onUpadateAvailable();
}
Output i received on my console:
A---> onUpadateAvailable
B---> onUpadateAvailable
I agree with #GauravGupta. The best way is to implement a push notification when there is changes in the database.
But regarding your problem you can try to run this asynctask:
class refreshList extends AsyncTask<String, String, String> {
Context context
public refreshList(Context context){
this.context=context;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method sstub
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
//Since you cant invoke notify notifyDataSetChanged() inside the doInBackground. So we will use this code:
((MainActivity) context).runOnUiThread(new Runnable() {
public void run() {
//Do your code here like refreshing your adapter
MainActivity.adapter.notifyDataSetChanged();
//
}
});
}
}, 1000, 10000);
//1000= interval delay;
//10000= run every 10secs
return null;
}
}
Remember to pass your activity's context when running the asynctask.
new refreshList(this).execute();

Break AsyncTaskResult<ArrayList<HashMap<String, String>>> into another list

Is there any way to break AsyncTaskResult>>
into to list ?
or get like 30,40,.. value of it only?
i have a Async class and it return the result of webservice fetch to adapter.
now because of huge data i want to split the result into seperate segment with passing
number of result to async class.
here is myasync class :
protected AsyncTaskResult<ArrayList<HashMap<String, String>>> doInBackground(
String... arg0) {
String xml = "Get String from my web service class"
myXmlParsingClass myparser = new myXmlParsingClass (xml, "getitem");
myparser .runParser();
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresult = new AsyncTaskResult<ArrayList<HashMap<String, String>>>(myXmlParsingClass .getParsedData());
return myresult ;
}
and my asynctaskresult :
public class AsyncTaskResult<T> {
private T result = null;
private Exception error = null;
public T getResult() {
return result;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T result) {
super();
this.result = result;
}
public AsyncTaskResult() {
super();
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
this is what i have done so far :
in the getview method inside my adapter i made second method to pass a number to async class:
MyAsyncClass ma = new MyAsyncClass(myview,userid,5);
in MyAsyncClass :
public MyAsyncClass ( View context,String _id) {
this.targetCtx = context ;
id = _id;
}
public MyAsyncClass ( View context,String _id,int _ID_To_Show) {
this.targetCtx = context ;
id = _id;
ID_To_Show= _ID_To_Show;
}
and on PostExecute method :
if(ID_To_Show >0 ){
MySecondAdapter Madapter = new MySecondAdapter(targetCtx, myresult.getResult(),ID_To_Show);
mylist.setAdapter(Madapter);
}else{
MySecondAdapter Madapter = new MySecondAdapter(targetCtx, myresult.getResult());
mylist.setAdapter(Madapter);
and finally in MySecondAdapter i added this :
public MySecondAdapter(View a, ArrayList<HashMap<String, String>> id,int _ID_To_Show) {
idfromhayoolafetch = id;
myinflater = (LayoutInflater) AppContext.getAppContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ID_To_Show= _ID_To_Show;
}
public MySecondAdapter(View a, ArrayList<HashMap<String, String>> id) {
idfromhayoolafetch = id;
myinflater = (LayoutInflater) AppContext.getAppContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
if(ID_To_Show>0){
return ID_To_Show;
}else{
return idfromhayoolafetch.size();
}
}
this approch show the amount of item i want to show in each call and i can pass value to it
but is other way i can do this ?
problem is i cant ask hayoola to limit the value in respond.
Such a request should be handled by server it self.
As in server should accept number of items to return and only send that many items.
But still if you want async task to handle it you can do following:
protected AsyncTaskResult<ArrayList<HashMap<String, String>>> doInBackground(
String... arg0) {
String xml = "Get String from my web service class"
myXmlParsingClass myparser = new myXmlParsingClass (xml, "getitem");
myparser .runParser();
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresult = new AsyncTaskResult<ArrayList<HashMap<String, String>>>(myXmlParsingClass .getParsedData());
ArrayList<HashMap<String, String>> result=myresult.getResult();
myresult.setResult(result.subList(0,maxItems));//maxItems=30 set it while creating async task object
return myresult ;
}

Android HTML Parser Example

I was looking into many HTML parser for android. I tried many libraries. Can anyone please show me an example how to do it. I want to extract the content of each tag. Please help. I am stuck with this.
Please look at this list. Actually, it's lots of options outside there. For instance, I chose HtmlCleaner library for implementation. Below is an example of usage:
Project structure:
Actual source code:
public class HtmlHelper {
TagNode rootNode;
public HtmlHelper(URL htmlPage) throws IOException
{
HtmlCleaner cleaner = new HtmlCleaner();
rootNode = cleaner.clean(htmlPage);
}
List<TagNode> getLinksByClass(String CSSClassname)
{
List<TagNode> linkList = new ArrayList<TagNode>();
TagNode linkElements[] = rootNode.getElementsByName("a", true);
for (int i = 0; linkElements != null && i < linkElements.length; i++)
{
String classType = linkElements[i].getAttributeByName("class");
if (classType != null && classType.equals(CSSClassname))
{
linkList.add(linkElements[i]);
}
}
return linkList;
}
}
public class StackParser extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.parse);
button.setOnClickListener(myListener);
}
private ProgressDialog pd;
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
pd = ProgressDialog.show(StackParser.this, "Working...", "request to server", true, false);
new ParseSite().execute("http://www.stackoverflow.com");
}
};
private class ParseSite extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... arg) {
List<String> output = new ArrayList<String>();
try
{
HtmlHelper hh = new HtmlHelper(new URL(arg[0]));
List<TagNode> links = hh.getLinksByClass("question-hyperlink");
for (Iterator<TagNode> iterator = links.iterator(); iterator.hasNext();)
{
TagNode divElement = (TagNode) iterator.next();
output.add(divElement.getText().toString());
}
}
catch(Exception e)
{
e.printStackTrace();
}
return output;
}
protected void onPostExecute(List<String> output) {
pd.dismiss();
ListView listview = (ListView) findViewById(R.id.listViewData);
listview.setAdapter(new ArrayAdapter<String>(StackParser.this, android.R.layout.simple_list_item_1 , output));
}
}
}

Passing arguments to AsyncTask, and returning results

I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the AsyncTask.
In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an AsyncTask if Yes is clicked. My question is how to pass an ArrayList<String> to the AsyncTask (and work with it there), and how to get back a new ArrayList<String> like a result from the AsyncTask?
The code of the method looks like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
ArrayList<String> result = new ArrayList<String>();
new calc_stanica().execute(passing,result);
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
So, as you see, I would like to send the string array list "passing" to the AsyncTask, and to get the "result" string array list back from it. And the calc_stanica AssycTask class looks like this:
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
//Some calculations...
return something; //???
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
So my question is how to get the elements of the "passing" array list in the AsyncTask doInBackground method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
Change your method to look like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list
And change your async task implementation
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> passed = passing[0]; //get passed arraylist
//Some calculations...
return result; //return result
}
protected void onPostExecute(ArrayList<String> result) {
dialog.dismiss();
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
}
UPD:
If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:
new calc_stanica() {
protected void onPostExecute(ArrayList<String> result) {
// here you have access to the context in which execute was called in first place.
// You'll have to mark all the local variables final though..
}
}.execute(passing);
Why would you pass an ArrayList??
It should be possible to just call execute with the params directly:
String curloc = current.toString();
String itemdesc = item.mDescription;
new calc_stanica().execute(itemdesc, curloc)
That how varrargs work, right?
Making an ArrayList to pass the variable is double work.
I sort of agree with leander on this one.
call:
new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));
task:
public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... args) {
...
}
#Override
protected void onPostExecute(ArrayList<String> result) {
... //do something with the result list here
}
}
Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);
public class calc_stanica extends AsyncTask<String, Void, Boolean> {
private List<String> resultList;
#Override
protected boolean doInBackground(String... args) {
...
}
#Override
protected void onPostExecute(boolean success) {
... //if successfull, do something with the result list here
}
}
I dont do it like this. I find it easier to overload the constructor of the asychtask class ..
public class calc_stanica extends AsyncTask>
String String mWhateveryouwantToPass;
public calc_stanica( String whateveryouwantToPass)
{
this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ...
You can receive returning results like that:
AsyncTask class
#Override
protected Boolean doInBackground(Void... params) {
if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
try {
throw new SQLException("Database credentials missing");
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass);
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
receiving class:
_store.execute();
boolean result =_store.get();
Hoping it will help.

Categories

Resources