AsyncTask getting called everytime - android

I have a navigation drawer containing 2 items. Now in my first item click, I load data using asynctask and the loaded data is populated in a listview in the corresponding fragment. Now when I switch to 2nd item, again I load data using AsyncTask for the 2nd fragment and show it in in listview.
Now the problem starts. When I go back to the 1st fragment, my
asyncTask is called again and the data is again fetched from the
server, I want to prevent this and load my data directly if it has
been already loaded once.
Please suggest
P.S - Please ask for the code if anyone needs it.
USERPAYFRAGMENT
public class UserPay extends Fragment {
ProgressDialog prg;
Properties prop;
private PrefSingleton mMyPreferences;
private JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> RequestList;
HashMap<String, String> map;
UserAdapter req_adp;
ListView req;
private boolean flag;
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Toast.makeText(getActivity(), "ATTACHED", 1000).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Toast.makeText(getActivity(), "CREATE", 1000).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.user_pay, container, false);
initViews(rootView);
Toast.makeText(getActivity(), "ONCREATEVIEW", 1000).show();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "ONACTIVITYCREATED", 1000).show();
mMyPreferences = PrefSingleton.getInstance();
mMyPreferences.Initialize(getActivity());
RequestList = new ArrayList<HashMap<String, String>>();
Resources resources = this.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("jsonURL.properties");
prop = new Properties();
prop.load(inputStream);
} catch (IOException e) {
System.err.println("Failed to open jsonURL property file");
e.printStackTrace();
}
req_adp = new UserAdapter(getActivity(), RequestList);
req.setAdapter(req_adp);
if (!flag) {
new GetRequests().execute();
} else {
}
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getActivity(), "ONSTART", 1000).show();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getActivity(), "ONRESUME", 1000).show();
}
private void initViews(View v) {
req = (ListView) v.findViewById(R.id.req_list);
}
private class GetRequests extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
prg = new ProgressDialog(getActivity());
prg.setIndeterminate(true);
prg.setMessage("Fetching Pending Requests...");
prg.setCanceledOnTouchOutside(false);
prg.show();
}
#Override
protected Integer doInBackground(Void... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("userID", mMyPreferences
.getPreference("LoginId")));
String error_code = null;
Log.e("URL ", "is" + prop.getProperty("GET_REQUESTS_URL"));
try {
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(
Appconstant.GET_REQUESTS_URL, "POST", params1);
// Check your log cat for JSON response
Log.d("Inbox JSON: ", json.toString());
JSONObject jsonObj = json.getJSONObject("data");
error_code = jsonObj.getString("Error_Code");
RequestList.clear();
if ("1".equals(error_code)) {
JSONArray jArray = jsonObj.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject jsonObj1 = jArray.getJSONObject(i);
String FBankId = jsonObj1
.getString("payment_from_bank_id");
String DestBankId = jsonObj1
.getString("payment_to_bank_id");
String FBank = jsonObj1.getString("fBank");
String TBank = jsonObj1.getString("tBank");
String reason = jsonObj1.getString("payment_reason");
String amt = jsonObj1.getString("amount");
String p_type = jsonObj1.getString("payment_type");
String status = jsonObj1.getString("status");
String r_date = jsonObj1
.getString("request_created_date");
map.put("FBankId", FBankId);
map.put("TBankId", DestBankId);
map.put("SourceBank", FBank);
map.put("DestBank", TBank);
map.put("ReqDate", r_date);
map.put("PayReason", reason);
map.put("Amt", amt);
map.put("PayType", p_type);
map.put("Status", status);
if (status.equals("pending")) {
if (p_type.equals("cheque")
|| p_type.equals("Net Banking")) {
RequestList.add(map);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return Integer.parseInt(error_code);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (prg.isShowing()) {
prg.cancel();
}
if (result == 2) {
Toast.makeText(getActivity(),
"No User Request Details Available.Please Try Again",
Toast.LENGTH_SHORT).show();
}
req_adp.notifyDataSetChanged();
flag = true;
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getActivity(), "ONPAUSE",1000).show();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(getActivity(), "ONSTOP", 1000).show();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Toast.makeText(getActivity(), "ONDESTROYVIEW", 1000).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getActivity(), "ONDESTROY", 1000).show();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Toast.makeText(getActivity(), "ONDETACH", 1000).show();
}
}

There are 2 ways to solve
1 - store the data locally and make use stored data based on appropriate condition checks
2 - If your app is based on this 2 fragments, just create the instance of these fragments and store in in member variable of parent activity. do not give chance to recreate again and again

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();
}

Showing status for the last list item in a ListView using ViewHolder

int globalPosition ;
..............
buttonAllData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new UploadBulkData(globalPosition).execute();
}
});
........
class UploadBulkData extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
int dataPosition;
public UploadBulkData(int position){
this.dataPosition = position;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadActivity.this);
pDialog.setMessage("Uploading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
.......
String url = "http://web/uploadBulk.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("UserData", st));
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
strStatusID = "0";
strError = "";
JSONObject jsonObject;
try {
jsonObject = new JSONObject(resultServer);
strStatusID = jsonObject.getString("StatusID");
strError = jsonObject.getString("Message");
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
fileNameDB=ImageList.get(globalPosition).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
if(strStatusID.equals("1"))
{
Toast.makeText(UploadActivity.this, "Data Uploaded Successfully", Toast.LENGTH_SHORT).show();
long saveImge = myDbbv.InsertData(fileNameDB);
Log.d("fileNameDB:UP", String.valueOf(saveImge));
}
else
{
Toast.makeText(UploadActivity.this, "Unable to upload Data", Toast.LENGTH_SHORT).show();
}
if (file_url != null){
Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
And in getView i am using something like this:
public View getView(final int position, View convertView, ViewGroup parent) {
holder.dataImageView.setImageResource(R.drawable.bullet_button);
try {
// check data exist or not
boolean strDataExistU = myDbbv.Exists(fileNameDB);
if(strDataExistU)
{
holder.dataImageView.setImageResource(R.drawable.online);
}
else
{
boolean strDataExist = myDb.Exists(fileNameDB);
if(strDataExist)
{
holder.dataImageView.setImageResource(R.drawable.local);
}
else
{
holder.dataImageView.setImageResource(R.drawable.default);
}
}
} catch (Exception e) {
}
}
As you can see in getView(...) method, I am using three different kind of drawables (namely:- online, local, default)
Where online shows data has been uploaded to online server, local shows this has been added to local database and default..(neither uploaded to server nor stored to local database)
Problem:
Whenever I am doing bulk upload, getting online drawable only for the last row item in a list, whereas I have uploaded whole list item data to server
I just want to show online drawable for all the list items, those I have uploaded to server, else my code works just fine...
Almost complete code:
public class UploadActivity extends Activity {
int globalPosition ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
ImageButton buttonAllData = (ImageButton) findViewById(R.id.btnMenus);
buttonAllData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new UploadBulkData(globalPosition).execute();
}
});
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
totalItems = ""+ lstView.getAdapter().getCount();
}
public static List <String> getSD()
{
List <String> it = new ArrayList <String>();
String string = "/mnt/sdcard/Pictures/Joseph/";
f = new File (string+ CameraLauncherActivity.folder+ "/");
files = f.listFiles ();
/***
* to show last taken image on top using lastModified
* to sort data
* to refresh data after (remove or update)
*/
Arrays.sort(files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
// <<<<<<<<< END >>>>>>>>>>>
for (int i = 0; i < files.length; i++)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
return it;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView imageNameTextView;
ImageView sdCardImageView, statusImageView, dataImageView;
ProgressBar uploadProgressBar;
ImageButton uploadImageButton, dataImageButton;
boolean isUploading = false;
}
public class ImageAdapter extends BaseAdapter
{
public ImageAdapter(Context c)
{
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row, which is expensive!
holder = null;
// If this item is to be synced
if(flags.get(position)) {
startUpload(position);
// Mark as synced
flags.put(position, false);
}
/*
* If convertView is not null, we can reuse it directly, no inflation required!
* We only inflate a new View when the convertView is null.
*/
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_upload, null);
holder = new ViewHolder(convertView);
// Create a ViewHolder and store references to the children views
holder.imageNameTextView = (TextView) convertView.findViewById(R.id.ColImgName);
holder.sdCardImageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
holder.statusImageView = (ImageView) convertView.findViewById(R.id.ColStatus);
holder.uploadProgressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
holder.uploadImageButton = (ImageButton) convertView.findViewById(R.id.btnUpload);
holder.dataImageButton = (ImageButton) convertView.findViewById(R.id.btnData);
holder.dataImageView = (ImageView) convertView.findViewById(R.id.dataExist);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
strPath = ImageList.get(position).toString();
// Get File Name
fileName = strPath.substring( strPath.lastIndexOf('_')+1, strPath.length() );
file = new File(strPath);
#SuppressWarnings("unused")
long length = file.length();
holder.imageNameTextView.setText(fileName);
fileName=ImageList.get(position).toString().substring
(strPath.lastIndexOf('_')+1, strPath.length());
fileNameDB=ImageList.get(position).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bm = BitmapFactory.decodeFile(strPath,options);
holder.sdCardImageView.setImageBitmap(bm);
if(holder.isUploading) {
holder.uploadProgressBar.setVisibility(View.VISIBLE);
} else {
holder.uploadProgressBar.setVisibility(View.GONE);
}
holder.dataImageView.setImageResource(R.drawable.bullet_button);
try {
// check data exist or not
boolean strDataExistU = myDbbv.Exists(fileNameDB);
if(strDataExistU)
{
holder.dataImageView.setImageResource(R.drawable.online);
}
else
{
// check data exist or not
boolean strDataExist = myDb.Exists(fileNameDB);
if(strDataExist)
{
holder.dataImageView.setImageResource(R.drawable.database);
}
else
{
holder.dataImageView.setImageResource(R.drawable.default);
}
}
} catch (Exception e) {
// TODO: handle exception
}
fileName = ImageList.get(position).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
try {
boolean strExist = myDbb.Exists(fileName);
if(strExist)
{
holder.statusImageView.setImageResource(R.drawable.onl);
}
else
{
holder.statusImageView.setImageResource(R.drawable.bullet_button);
}
} catch (Exception e) {
// TODO: handle exception
}
// btnData
holder.dataImageButton.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// Print
globalPosition = position;
fileName=ImageList.get(position).toString().substring
(strPath.lastIndexOf('_')+1, strPath.length());
fileNameDB=ImageList.get(position).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
showDialog(DIALOG_LOGIN);
}
});
return convertView;
}
}
class UploadData extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadActivity.this);
pDialog.setMessage("Uploading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String url = "http://web/uploadData.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sImageName", fileNameDB));
Log.d("sImageName::", fileNameDB);
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
strStatusID = "0";
strError = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
fileName=ImageList.get(globalPosition).toString().substring
(strPath.lastIndexOf('_')+1, strPath.length());
fileNameDB=ImageList.get(globalPosition).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
// prepare save data
if(strStatusID.equals("0"))
{
Toast.makeText(getApplicationContext(), "Unable to upload Data",
Toast.LENGTH_LONG).show();
}
else if (strStatusID.equals("1"))
{
Toast.makeText(getApplicationContext(), "Data Uploaded Successfully!",
Toast.LENGTH_SHORT).show();
// Save Data
long saveImge = myDbbv.InsertData(fileNameDB);
Log.d("fileNameDB:UP", String.valueOf(saveImge));
} else {
Toast.makeText(getApplicationContext(), "Unable to upload Data",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO: handle exception
}
if (file_url != null){
Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
});
cancelButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
closeButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}
}
class UploadBulkData extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
int dataPosition;
//constructor to pass position of row, on which button was clicked to class
public UploadBulkData(int position){
this.dataPosition = position;
}
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadActivity.this);
pDialog.setMessage("Uploading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String url = "http://web/uploadBulk.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("EventData", st));
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
strStatusID = "0";
strError = "";
JSONObject jsonObject;
try {
jsonObject = new JSONObject(resultServer);
strStatusID = jsonObject.getString("StatusID");
strError = jsonObject.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
// Prepare Save Data
if(strStatusID.equals("1"))
{
Toast.makeText(UploadActivity.this, "Data Uploaded Successfully", Toast.LENGTH_SHORT).show();
fileNameDB=ImageList.get(dataPosition).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
// Save Data
long saveImge = myDbbv.InsertData(fileNameDB);
Log.d("fileNameDB:UP", String.valueOf(saveImge));
}
else
{
Toast.makeText(UploadActivity.this, "Unable to upload Data", Toast.LENGTH_SHORT).show();
}
if (file_url != null){
Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
Issue is in holder.dataImageButton.setOnClickListener method block, position value you are assigning to globalPosition (globalPosition = position;) is the one passed to getView method (getView is called every time view is recycled). So you should set position to holder.dataImageButton tag and retrieve from it inside your setOnClickListener method block.
So set the position in holder.dataImageButton tag
holder.dataImageButton.setTag(position);
after your code line
holder.dataImageView.setImageResource(R.drawable.bullet_button);
and modify your setOnClickListener method as
holder.dataImageButton.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// Print
globalPosition = (Integer)v.getTag(); //modified
fileName=ImageList.get(position).toString().substring
(strPath.lastIndexOf('_')+1, strPath.length());
fileNameDB=ImageList.get(position).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
showDialog(DIALOG_LOGIN);
}
});
It appears that in both UploadData and UploadBulkData the exact same code is used for updating the uploaded database: myDbbv.InsertData(fileNameDB). This would have the effect of only marking the last file of UploadBulkData as being uploaded, which is consistent with the problematic behavior you are seeing.
Try updating myDbbv for each file being uploaded in UploadData and see if it helps.
There could be multiple customizable ways to achieve this. One of them is already answered. Correct me if I'm wrong about your requirement, you need to be notified when the list reached its last item. Afterwards, you're going to perform an operation with the last item index.
[UPDATE]
For this solution: You have to migrate to Recycler View as it's more flexible, fast and optimised for bulk data.
int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition(); // This function could be the one you're looking for.
int findLastCompletelyVisibleItemPosition();
Usage:
// In Java
GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
Reference: https://stackoverflow.com/a/25053500/16176653

Async Task Loader, Google Cloud Messaging , Sync Adapter not connected properly, Array Adapter

I am working on an application that requires data to be displayed on a listview. The data to be displayed on the listview needs to be updated frequently so i created a sync-adapter which will be triggered my a broadcast message from gcm. When this occurs my AsyncTask loader.onContentChanged is called which call the loadinbackground method and all this works properly. The issues i am having is displaying the new data on the listview without restarting the activity. i am trying to get it to work like facebook news feed listview.
Please help me
My codes are as follows
SyncAdapter
#Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
// TODO Auto-generated method stub
Log.d(TAG, "onPerformSync for account[" + account.name + "]");
String theValue = mAccountManager.getUserData(account, "User_ID");
mContentResolver = mContext.getContentResolver();
final RoomListLoader mLoader = new RoomListLoader(mContext, theValue);
mLoader.onContentChanged();
}
Loader
public class RoomListLoader extends AsyncTaskLoader<List<RoomList>> {
private static String url = "********************";
int success;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
JSONParser jsonParser = new JSONParser();
JSONObject json;
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
RoomList details;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
Context mContext;
//private final Handler observerHandler;
public RoomListLoader(Context context,String nuser_id) {
super(context);
// TODO Auto-generated constructor stub
//mRoomList = nRoomList;
this.user_id = nuser_id;
this.mContext = context;
//observerHandler = new Handler();
}
#Override
public List<RoomList> loadInBackground() {
// TODO Auto-generated method stub
mRoomList.clear();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", user_id));
json = jsonParser.makeHttpRequest(url, "POST", params);
// final Context context = getContext();
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
rooms = json.getJSONArray(TAG_ROOMS);
// counter = json.getInt("counter");
counterOnGetRooms = json.getInt("count");
Log.d("counterOnGetRooms", "" + counterOnGetRooms);
// Log.v("counter", "" + counter);
for (int i = 0; i < rooms.length(); i++) {
tryme2++;
JSONObject c = rooms.getJSONObject(i);
// get room titles
roomTitle = c.getString("room_title");
retrievedRoomId = c.getString("room_id");
created_at = c.getString("created_at");
username = c.getString("username");
numOfComments = c.getString("counters");
filePath = c.getString("filePath");
Log.i("filePath", filePath);
details = new RoomList(retrievedRoomId, roomTitle,
created_at, username, numOfComments, filePath);
mRoomList.add(details);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//MostRecentRooms Room;
//deliverResult(mRoomList);
return mRoomList;
}
#Override
public void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
loadInBackground();
//deliverResult(mRoomList);
}
#Override
public void onCanceled(List<RoomList> data) {
// TODO Auto-generated method stub
super.onCanceled(data);
}
#Override
public void deliverResult(List<RoomList> data) {
// TODO Auto-generated method stub
Log.d("Deliver Result",""+data.size());
super.deliverResult(data);
}
#Override
protected void onReset() {
// TODO Auto-generated method stub
super.onReset();
onStopLoading();
}
#Override
protected void onStartLoading() {
// TODO Auto-generated method stub
if (mRoomList != null) {
//deliverResult(mRoomList);
}
super.onStartLoading();
}
#Override
protected void onStopLoading() {
// TODO Auto-generated method stub
cancelLoad();
}
}
Activity
public class MostRecentRooms extends ListActivity implements LoaderManager.LoaderCallbacks<List<RoomList>> {
// progress dialog
ProgressDialog pDialog;
// json parser object
JSONParser jsonParser = new JSONParser();
int decrement = 0;
int success;
int s = 0;
Activity mActivity;
// url to view most recent rooms
private static String url = "************8";
// url to load more rooms
private static String url3 = "***************";
// url to check status of user
private static String url2 = "*****************";
// url to get profile images
private static String url4 = "****************88";
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
int Loader_ID =0x3;
int counter = 0;
HashMap<String, String> map;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
RoomList details;
ListAdapter adapter;
public static RoomListAdapter mAdapter;
public static LoaderManager mLoadManager;
// json arrays
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
// Array list to hold room titles
ArrayList<HashMap<String, String>> allRooms;
// ArrayList<String> allRooms;
// List view to show room titles of an arraylist
public ListView lv;
// json Object
JSONObject json;
int limit = 20;
// strings
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
// buttons
Button back, loadMore, refresh;
Bitmap img_bitmap;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_most_recent_rooms);
mLoadManager = getLoaderManager();
mAdapter = new RoomListAdapter(this, getApplicationContext());
lv= getListView();
lv.setAdapter(mAdapter);
// back button
back = (Button) findViewById(R.id.backToMainMenu);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
// end back button
// get user id from View rooms class
if (getIntent().getExtras().getString("user_id_value") != null)
user_id = getIntent().getExtras().getString("user_id_value");
else
Log.e("Error", "Missing user_id");
mLoadManager.initLoader(Loader_ID,null,MostRecentRooms.this);
//allRooms = new ArrayList<HashMap<String, String>>();
// allRooms = new ArrayList<String>();
// call class GetAllRooms
//new GetAllRooms().execute();
// get room_id
if (getIntent().getExtras().getString("room_id_to_send") != null)
room_id = getIntent().getExtras().getString("room_id_to_send");
else
Log.e("Error", "Missing room id");
loadMore = (Button) findViewById(R.id.loadMore);
loadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//new LoadMoreRooms().execute();
// counter -= 5;
}
});
refresh = (Button) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mRoomList.clear();
allRooms.clear();
limit = 20;
tryme = 0;
img_bitmap.recycle();
//new GetAllRooms().execute();
}
});
}
/**
* This class get users status whether deleted or not
*/
class GetUserStatus extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
backGroundProcess(user_id);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("i is", "" + i);
if (i == 2) {
// decativatedPage();
Toast.makeText(getApplicationContext(), "noooo",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(getApplicationContext(), RoomPage.class);
i.putExtra("room_id_to_send", clickedOnRoomId);
i.putExtra("user_id_value", user_id);
startActivity(i);
}
}
}// end class
private void backGroundProcess(String string) {
// build parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", string));
json = jsonParser.makeHttpRequest(url2, "POST", params);
int success;
try {
success = json.getInt("success");
if (success == 1) {
i = 1;
Log.i("status", json.getString("message").toString());
} else if (success == 2) {
i = 2;
} else {
Log.d("Error", "Something went wrong");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Loader<List<RoomList>> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
Log.d("Tsg", "here");
RoomListLoader mRoomloader = new RoomListLoader(getApplicationContext(), user_id);
mRoomloader.forceLoad();
return mRoomloader ;
}
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
// TODO Auto-generated method stub
Log.i("tag","list loaded");
if(data != null){
mAdapter.SetData(data);
mAdapter.notifyDataSetChanged();
}
//mAdapter.SetData(data);
Log.i("Tag",""+data.size());
//lv.setAdapter(mAdapter);
}
#Override
public void onLoaderReset(Loader<List<RoomList>> arg0) {
// TODO Auto-generated method stub
Log.d("Loader", "Loader Reset");
mAdapter.SetData(null);
}
}
Adapter
public class RoomListAdapter extends ArrayAdapter<RoomList> {
ImageLoader imageLoader = null;
private Activity activity;
String TAG = "RoomListAdapter";
private final LayoutInflater mInflator;
List<RoomList> nRoomList;
public RoomListAdapter(Activity a, Context context) {
// TODO Auto-generated constructor stub
super(context, R.layout.viewroom_layout);
activity = a;
mInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(a.getApplicationContext());
//nRoomList = mRoomList;
//SetData(nRoomList);
}
public void SetData(List<RoomList> data) {
clear();
if (data != null) {
addAll(data);
}
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
#Override
public void setNotifyOnChange(boolean notifyOnChange) {
// TODO Auto-generated method stub
super.setNotifyOnChange(notifyOnChange);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi;
if (convertView == null) {
vi = mInflator.inflate(R.layout.viewroom_layout, null);
} else {
vi = convertView;
}
TextView room_id = (TextView) vi.findViewById(R.id.roomsIDHidden);
TextView room_title = (TextView) vi.findViewById(R.id.roomsName);
TextView created_at = (TextView) vi.findViewById(R.id.createdTime);
TextView username = (TextView) vi.findViewById(R.id.creatorName);
TextView numOfComments = (TextView) vi.findViewById(R.id.numComments);
ImageView image = (ImageView) vi.findViewById(R.id.userPic);
//Log.d(TAG, "Within the room list adapter");
RoomList info = getItem(position);
room_id.setText(info.getmRoom_id());
room_title.setText(info.getmRoomTitle());
created_at.setText(info.getmCreated_at());
username.setText(info.getmUsername());
numOfComments.setText(info.getmNumberOfComments());
imageLoader.DisplayImage(info.getmFilePath(), image);
return vi;
}
}
with the help of venkat and monica i solved it didn't need the Syncadpter all i needed was a broadcast receiver this i did by
1) creating a broad cast intent when GCM receives the message
Intent intent1 = new Intent();
intent1.setAction("com.gcm.updatecame");
this.sendBroadcast(intent1);
2) in my Activity i register the receiver and create the class
filter1= new IntentFilter("com.gcm.updatecame");
registerReceiver(myReceiver, filter1);
Broadcast Receiver
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// write your code here to update the listview.
if(mLoadManager != null){
Reload.setVisibility(View.VISIBLE);
Reload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mLoadManager.destroyLoader(Loader_ID);
mAdapter.notifyDataSetChanged();
mAdapter.SetData(null);
mRoomList.clear();
mLoadManager.initLoader(Loader_ID, null, MostRecentRooms.this);
Reload.setVisibility(View.INVISIBLE);
}
});
}
}
};
Replace you onLoadFinished method with this one:
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
if(data != null){
mAdapter = new RoomListAdapter(this, getApplicationContext());
mAdapter.SetData(data);
lv.setAdapter(mAdapter);
}
}

How to refresh a listview in android using asynctask?

There are two Activities. The first Activity is having the list view to see what is being shared and the second activity has an edit text box (to input inorder to share) and a button. On clicking the button, it returns me the string which is the json response and I need to add this in the previous activity.
Now the problem is, when I refresh the first page fully hitting the server it gets the response but this is not what I want. It should not go back to the server. It should simply add in the list view adapter.
I have commented the code in the PostExecute(). I have tried the everyway but it is not reflecting. I am also posting my code for your reference.
public class ShareAsyncTask extends AsyncTask<String, Void, ArrayList<EventsStreamBean>> {
public ProgressDialog pd = new ProgressDialog(EventStreamActivity.this);
String success_share_val;
#Override
protected ArrayList<EventsStreamBean> doInBackground(
String... result) {
// TODO Auto-generated method stub
JSONObject jsonobj = new JSONObject(result[0].toString());
success_share_val = jsonobj.getString(Constants.SUCCESS);
//checks the success value
if(success_share_val.equalsIgnoreCase("1")) {
JSONArray events_stream_share_array = jsonobj.getJSONArray("streamArray");
if(events_stream_share_array.length() > 0) {
for(int i=0; i<events_stream_share_array.length(); i++) {
EventsStreamBean events_stream_bean = new EventsStreamBean();
JSONObject events_stream_object = events_stream_share_array.getJSONObject(i);
events_stream_bean.setStreamId(events_stream_object.getString(Constants.STREAM_ID));
events_stream_bean.setStreamType(events_stream_object.getString(Constants.STREAM_TYPE));
events_stream_bean.setUserId(events_stream_object.getString(Constants.USER_ID));
events_stream_bean.setUserName(events_stream_object.getString(Constants.USER_NAME));
events_stream_bean.setUserType(events_stream_object.getString(Constants.USER_TYPE));
events_stream_bean.setUserAvatar(events_stream_object.getString(Constants.USER_AVATAR));
arraylist_events_stream.add(events_stream_bean);
}
}else {
Log.i("Test", "No Events Streams Available");
}
}
}catch(Exception e) {}
return arraylist_events_stream;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.pd.setMessage("Loading....");
pd.setCanceledOnTouchOutside(false);
pd.setCancelable(false);
this.pd.show();
}
#Override
protected void onPostExecute(final ArrayList<EventsStreamBean> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.pd.isShowing()) {
this.pd.dismiss();
}
Toast.makeText(EventStreamActivity.this, "Post shared successfully", Toast.LENGTH_SHORT).show();
new EventsStreamAsyncTask().execute(temp_val);
/*runOnUiThread(new Runnable() {
public void run() {
//EventStream_Customadapter adapter = (EventStream_Customadapter) list_view.getAdapter();
//adapter.clearData();
adapter.updateData(result);
//adapter = new EventStream_Customadapter(EventStreamActivity.this, arraylist_events_stream);
//list_view.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});*/
}
}
Thank you

External AsyncTask populating ListView from Fragment

I am developing an app based off fragments. A lot of the content of these fragments is collected from a database utilizing an AsyncTask. As such I'm trying to externalize the 'getting data' class so it can be reused. My fragment is as follows:
public class LocalFragment extends SherlockListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
LoadDataFromURL url_data = new LoadDataFromURL();
url_data.setContext(getSherlockActivity());
url_data.setURL("http://url.com/get_data/");
url_data.execute();
}
}
My LoadDataFromURL class is as follows:
class LoadDataFromURL extends AsyncTask<String, String, String>{
String our_url;
ListActivity our_context;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray results = null;
List<PubListDetails> pubs = new ArrayList<PubListDetails>();
Handler mHandler;
public void setContext(ListActivity context){
our_context = context;
}
public void setURL(String url){
our_url = url;
}
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler = new Handler();
pDialog = new ProgressDialog(our_context);
pDialog.setMessage("Loading pubs please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray json = jParser.makeHttpRequest(our_url, "GET", params);
Log.d("All Products: ", json.toString());
try {
int success = json.length();
if (success != 0){
results = json;
pubs.clear();
for (int i = 0; i <results.length(); i++){
JSONObject c = results.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String town = c.getString("town");
String county = c.getString("county");
//HashMap<String, String> map = new HashMap<String, String>();
pubs.add(new PubListDetails(id,name,town,county));
//map.put(TAG_PID, id);
//map.put(TAG_NAME, name);
//productsList.add(map);
}
}else{
Intent i = new Intent(our_context,MainMenu.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
our_context.startActivity(i);
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(our_context, "ff", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
pDialog.dismiss();
our_context.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
ListAdapter adapter = new PubListAdapter(our_context, pubs);
our_context.setListAdapter(adapter);
}});
}
}
It is giving me errors on the basis that getSherlockActivity does not pass a ListActivity, which setListAdapter requires.
Independent of this, I am feeling more and more that I have conceptually missed the point and this isn't the ideal way to achieve what I want.
Could someone advise how from a fragment I can call an external AsyncTask which will collect data and then populate a ListView with it?
First, you want to set the data on the SherlockListFragment so your business it's not with the Activity .
Independent of this, I am feeling more and more that I have
conceptually missed the point and this isn't the ideal way to achieve
what I want.
Could someone advise how from a fragment I can call an external
AsyncTask which will collect data and then populate a list view with
it..?
Simply implement a callback interface.
public interface OnLoadDataListener {
public onLoadComplete(List<PubListDetails> data);
}
Let your fragment class implement this interface:
public class LocalFragment extends SherlockListFragment implements OnLoadDataListener {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LoadDataFromURL url_data = new LoadDataFromURL();
url_data.setContext(getSherlockActivity());
url_data.setURL("http://url.com/get_data/");
url_data.setListener(this); // you could unite the setContext() method in the listener registration
url_data.execute();
}
#Override
public void onLoadComplete(List<PubListDetails> data) {
ListAdapter adapter = new PubListAdapter(getSherlockActivity(), pubs);
our_context.setListAdapter(adapter);
}
}
And in your AsyncTask:
private OnLoadDataListener mListener
public void setListener(OnLoadDataListener listener){
mListener = listener;
}
and in the onPostExecute you send the data to the listener:
#Override
protected void onPostExecute(String result) {
Toast.makeText(our_context, "ff", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
pDialog.dismiss();
if (mListener != null) {
mListener.onLoadComplete(pubs);
}
}

Categories

Resources