Android: Store the ratings in database - android

List view of ratings I am getting from web service I need to store the response of ratings in database. Ratings are storing but not according to the position if I given ratings to 1st person it is storing it to another please help me out.
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty()) {
// courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
// convertView = null;
if (convertView == null) {
TabviewHolder = new ViewHolder();
//LayoutInflater inflater = getLayoutInflater();
inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
// TabviewHolder.rating.setOnRatingBarChangeListener(setOnRatingBarChangeListener(TabviewHolder, position));
TabviewHolder.rating.setTag(position);
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.FacultyName.setTag(position);
my_name = mFac.getEmployeename().toString();
my_email = mFac.getEmployeeid().toString();
feedbackresult = String.valueOf(rating);
// ratingBar.setRating(rating);
//my_rating = mFac.getRatingStar();
TabviewHolder.rating.setRating(mFac.getRatingStar());
// TabviewHolder.rating.setTag(position);
// my_rating = hi.toString();
// rating.setOnRatingBarChangeListener(getApplicationContext());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult = String.valueOf(rating);
hi = feedbackresult;
// if(!fromUser) return;
// Faculty item = getItem(position);
// item.setRatingStar(rating);
int index = (Integer) (ratingBar.getTag());
mFac.setRatingStar(Float.parseFloat(feedbackresult));
//amount=Float.parseFloat(feedbackresult);
// TabviewHolder.rating.setRating(Float.parseFloat(feedbackresult));
Log.d("feedback", "feedback is: " + feedbackresult);
}
});
return convertView;
}
/*private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final ViewHolder holder, final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
FacultyName item = getItem(position);
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}*/
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Faculty getItem(int position) {
return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
progressDialog = ProgressDialog.show(Feedback.this, "Faculty Feedback!", "Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
} else {
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
/* #Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end**/
//**************************SECOND ASYNC TASK*********************************
private class SendFeedbackSyncerBg extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Feedback.this, "Faculty Feedback!", "Uploading your ratings", true);
}
#Override
protected Void doInBackground(String... params) {
//Call Web Method from webService
// FeedBackResponse=WebService.sendfeedback(programtype,employeemailid,employeename,feedbackresult);
// uploaddata = parid(faculty_name, email, rate, "getUserInfo");
uploaddata = parid(rate, my_name, my_email, "getUserInfo");
return null;
}// doInBackground Process
#Override
//Once WebService returns response
protected void onPostExecute(Void result) {
progressDialog.dismiss();
if (uploaddata == false) {
Toast.makeText(getApplicationContext(), "Not Done!", Toast.LENGTH_SHORT).show();
} else {
courseEmptyLayout.setVisibility(LinearLayout.GONE);
Toast.makeText(getApplicationContext(), "Thanks for Feedback!!", Toast.LENGTH_SHORT).show();
}
}// End of onPostExecute
/* #Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getApplicationContext(), "Faculty Feedback!", "Uploading your ratings", true);
}*/
}

Related

android rating bar in listview:How to save rating of multiple list in object?

I am designing faculty feedback activity.Below is my Fragment activity where i get faculty names from webservice as object and dispaly them in listview.And there is Rating bar infront every faculty.
I want to collect value of rating and faculty name in array of object and want to send feedback of every faculty to webservice to store when i click submit button.How can i do it?
FragmentTab2.java
public class TabFragment2 extends android.support.v4.app.Fragment implements View.OnClickListener {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
Button upButton;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
upButton = (Button) rootView.findViewById(R.id.btnSubmit);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
//FEEDBACK SUBMISSION BUTTON
#Override
public void onClick(View v) {
new SendFeedbackSyncerBg().execute("");
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
TabviewHolder.rating.setRating(mFac.getRatingStar());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
TabviewHolder.rating.setRating(Float.parseFloat(feedbackresult));
Log.d("feedback","feedback is: "+ feedbackresult);
}
});
return convertView;
}
/*private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final ViewHolder holder, final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
FacultyName item = getItem(position);
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}*/
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
And here is my object class
Faculty.java
public class Faculty {
private float ratingStar;
String employeeid;
String employeename;
//public List<Faculty> facultylist= new ArrayList<>();
public Faculty()
{
}
public Faculty(int ratingStar,String employeeid,String employeename)
{
this.ratingStar = ratingStar;
this.employeeid =employeeid;
this.employeename =employeename;
}
public float getRatingStar() {
return ratingStar;
}
public void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
public void setEmployeeid(String employeeid)
{
this.employeeid = employeeid;
}
public String getEmployeeid()
{
return this.employeeid;
}
public void setEmployeename(String employeename)
{
this.employeename = employeename;
}
public String getEmployeename()
{
return this.employeename;
}
}
Any kind of knowledge and information will be thankful
EDIT
My list of ratings look like this.
Image

Android:Receive Array of Objects and display in listView

Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});

Refresh list in Baseadaptor in Android

Hi,
I try to refresh my data with a tweet app which I am making. When I delete a following person by cliking on the button "following_del", I want that my list view being refreshed without the user I just deleted. Do you have any idea do to this? I am in a baseAdaptor class. Thanks
public class UsersAdapter extends BaseAdapter implements DialogInterface.OnShowListener {
private List<User> mUsers;
Integer BUTTON_ACTIVATE = 0;
public List<User> getUsers() {
return mUsers;
}
public Context context;
public void setUsers(List<User> users) {
mUsers = users;
}
public UsersAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return mUsers != null ? mUsers.size() : 0;
}
#Override
public User getItem(int position) {
return mUsers.get(position);
}
#Override
public long getItemId(int position) {
// if (getItem(position).getId() == null) {
return 0;
// } else {
// return getItem(position).getId().hashCode();
// }
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.follower_item, parent, false);
BUTTON_ACTIVATE = 0;
}
final User user = getItem(position);
TextView handleView = (TextView) convertView.findViewById(R.id.handle);
handleView.setText(user.getHandle());
TextView statusView = (TextView) convertView.findViewById(R.id.status);
Log.i(context.getClass().getName(), "Je suis dans ce context2");
ImageButton button_del = (ImageButton) convertView.findViewById(R.id.add_following);
button_del.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (AccountManager.isConnected(context)) {
new AsyncTask<String, Void, Integer>() {
#Override
protected Integer doInBackground(String... arg) {
try {
String handle = AccountManager.getUserHandle(context);
String token = AccountManager.getUserToken(context);
String content = user.getHandle();
if (handle.compareTo(content) != 0) {
new ApiClient().postdelFollowing(handle, token, content);
return 1;
}
} catch (IOException e) {
return 0;
}
}
#Override
protected void onPostExecute(Integer success) {
if (success == 1) {
Toast.makeText(context, "Vous ne suivez plus " + user.getHandle(), Toast.LENGTH_SHORT).show();
if (context.getClass().getName().compareTo(FollowingActivity.class.getName()) == 0) {
Intent intent = new Intent(context, FollowingActivity.class);
intent.putExtras(FollowingFragment.newArgument(UsersFragment.user));
context.startActivity(intent);
}
} else {
Toast.makeText(context, "Une erreur s'est produite", Toast.LENGTH_SHORT).show();
}
}
}.execute();
} else {
new AlertDialog.Builder(context)
.setMessage("Veuillez vous connecter")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
}
});
return convertView;
}
}

Return value from AsyncTask class onPostExecute method initialization value

Im reusing an Integer value that is calculated in th AsyncTask class and i need to create new instances of this class very often because the function calculated in the background needs to be done for every element of a ListView.
Im initializing a new BackgroundTask so i use this code in the main method called ShowItems(final Item item)
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)3);
Till here it works. then i need to create a new mBackgroundTask in a ToggleButton and this is where the problem arrises. i can't use this while defining the new class as i'll be getting the instance of the ToggleButton and not the original AsyncResponse
Here is my complete code
public interface AsyncResponse {
Integer processFinish(Integer result);
}
and
public class ItemView extends LinearLayout implements AsyncResponse{
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
public ToggleButton followButton;
public String nextFollowAction = "";
public Integer result1 = 77;
public BackgroundTask mBackgroundTask = null;
public ItemView(Context context, AttributeSet attrs) {
super(context, attrs);
//mBackgroundTask.delegate = this;
// TODO Auto-generated constructor stub
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
prezzo = (TextView)findViewById(R.id.tvPrezzo);
scadenza = (TextView)findViewById(R.id.tvScadenza);
followers = (TextView)findViewById(R.id.tvFollowers);
ic_thumbnail = (ImageView)findViewById(R.id.ic_thumbnail);
hProgressBar = (ProgressBar)findViewById(R.id.hProgressBar);
followButton = (ToggleButton)findViewById(R.id.btnFollow);
}
public void showItems(final Item item) {
prezzo.setText(item.getPrezzo());
ic_thumbnail.setImageBitmap(item.getIcon());
scadenza.setText(item.getPrezzo());
followers.setText("Followers: " + item.getFollowers());
hProgressBar.setProgress(item.getCoefficient());
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)3);
if (result1 != null){
Log.i("result1 = ", Integer.toString(result1));
askForFollowing(result1, nextFollowAction, item);
}
followButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
Log.i("followButton", "toggle enabled");
followButton.getTextOn();
//error
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)1);
//askForFollowing(statusCode, nextFollowAction, item);
//increaseFollowers(item);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
} else {
// The toggle is disabled
Log.i("followButton", "toggle disabled");
mBackgroundTask = new BackgroundTask(this);
mBackgroundTask.execute(item.getId(), (long)2);
followButton.getTextOff();
followButton.setBackgroundResource(R.drawable.action_object_button_green);
}
}
});
}
public void askForFollowing(int statusCode, String nextFollowAction, Item item){
//Status code: 0 --> OK
if(statusCode == 0) {
Log.i("changeFollowStatus(nextFollowAction);", "changeFollowStatus(nextFollowAction);");
changeFollowStatus(nextFollowAction, item);
}
// Status code 108 --> Oggetto giĆ  seguito
else if ((statusCode == 108) && (nextFollowAction.contains("kCheckFollowAction"))) {
Log.i("statusCode == 108", "statusCode == 108");
nextFollowAction = "kUnfollowAction";
followButton.setEnabled(true);
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
}
// Status code 122 --> Oggetto non ancora seguito
else if ((statusCode == 122) && (nextFollowAction.contains("kCheckFollowAction"))) {
Log.i("statusCode == 122", "statusCode == 122");
nextFollowAction = "kFollowAction";
followButton.setEnabled(false);
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
}
else {
// Altrimenti gestisco l'errore
Log.i("errore status code LVA", "devo gestire l'errore");
}
}
public void changeFollowStatus(String action, Item item){
Log.i("changeFollowStatus action", action);
if(action.contains("kFollowAction")) {
Log.i("changeFollowStatus", "1");
nextFollowAction = "kUnfollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_gray);
followButton.setText("seguito");
followButton.getTextOn();
increaseFollowers(item);
}
else if(action.contains("kUnfollowAction")){
Log.i("changeFollowStatus", "2");
nextFollowAction = "kFollowAction";
followButton.setBackgroundResource(R.drawable.action_object_button_green);
followButton.setText("segui");
followButton.getTextOff();
decreaseFollowers(item);
}
}
public void increaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) + 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
public void decreaseFollowers(Item item){
int updatedFollowers = Integer.parseInt(item.getFollowers()) - 1;
item.setFollowers(Integer.toString(updatedFollowers));
followers.setText("Followers: " + item.getFollowers());
}
#Override
public Integer processFinish(Integer result) {
Log.i("method processFinish", Integer.toString(result));
Log.i("method processFinish", "method");
return result;
}
/**
* Represents an asynchronous task used to download
* information from the webserver and display the results
*/
public class BackgroundTask extends AsyncTask<Long, Void, Integer> {
//public AsyncResponse delegate;
private AsyncResponse listener;
public BackgroundTask(AsyncResponse listener){
this.listener = listener;
}
#Override
protected Integer doInBackground(Long... params) {
// TODO: attempt authentication against a network service.
int i = MVPFunctions.getInstance().followItem(SessionManager.getUserDetails().get("login"), SessionManager.getUserDetails().get("password"), params[0], params[1].intValue());
Log.i("doInBackground", Integer.toString(i));
return i;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
}
#Override
protected void onPostExecute(Integer result) {
mBackgroundTask = null;
result1 = listener.processFinish(result);
//delegate.processFinish(result);
//ItemView
//Log.i("onPostExecute statusCode", Integer.toString(success) + " = " + Integer.toString(statusCode));
}
#Override
protected void onCancelled() {
mBackgroundTask = null;
//showProgress(false);
}
}
}
more code
public class ListViewAdapter extends ArrayAdapter<String> {
private LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList<Item> items;
public Bitmap icon;
//private ViewHolder viewHolder = new ViewHolder();
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<Item> items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
#Override
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ItemView view;
if (convertView == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (ItemView) inflater.inflate(R.layout.listview_item_row, null);
} else {
view = (ItemView) convertView;
}
Item item = items.get(position);
view.showItems(item);
return view;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View v) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
}
If i understood this correctly, i think ItemView.this will solve your issue here.
Note: As pointed out in comment, you should run single AsyncTask to loop through all list items instead of creating new AsyncTask for each item.

How to access a list item in on PostExecute in android

I have a BaseAdapter in that, I have a Button. When a user clicks on that button, I need to call a Service and I need to set the data to that button in onpostExecute()
public class MenuTagsAdapter extends BaseAdapter {
View v;
#Override
public int getCount() {
// TODO Auto-generated method stub
return BaseApp.getTagsAroundMeList().size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.menutaglistitem, null);
TextView textViewName = (TextView) v
.findViewById(R.id.textViewName);
final Button buttonAction = (Button) v
.findViewById(R.id.buttonAction);
textViewName.setText("#"
+ BaseApp.getTagsAroundMeList().get(position).name);
buttonAction
.setText(BaseApp.getTagsAroundMeList().get(position).action);
buttonAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (buttonAction.getText().toString()
.equalsIgnoreCase("follow")) {
buttonAction.setBackgroundResource(R.drawable.followbutton);
if (appUtils.getNetworkInfo(AmgonnaHome.this)) {
new FollowInterestAsyTask().execute();
} else {
NetworkDialogClass.createDAlertDialog(
AmgonnaHome.this,
getString(R.string.network_error));
}
} else {
buttonAction.setBackgroundResource(R.drawable.unfollowbutton);
if (appUtils.getNetworkInfo(AmgonnaHome.this)) {
new UnfollowInterestAsyTask().execute();
} else {
NetworkDialogClass.createDAlertDialog(
AmgonnaHome.this,
getString(R.string.network_error));
}
}
}
});
return v;
}
}
public class FollowInterestAsyTask extends AsyncTask<Void, Void, Void> {
boolean progressDialogStatus = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(AmgonnaHome.this,
"Please Wait", "Connecting to Server");
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
progressDialogStatus = false;
}
});
}
#Override
protected Void doInBackground(Void... params) {
TaskUrl = BaseApp.baseUrl + BaseApp.followInterest;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("user_id=" + amgonnaUserId);
// stringBuilder.append("&interestName="+);
stringBuilder.append("&interestName=");
ConnectionManager connectionManager = new ConnectionManager();
String response = connectionManager.setUpHttpPost(TaskUrl,
stringBuilder.toString());
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
errStatus = jsonObject.getInt("errStatus");
status = jsonObject.getString("status");
} catch (Exception e) {
// TODO: handle exception
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialogStatus) {
progressDialog.dismiss();
if (errStatus == 0) {
// here i need to set the status message to button on adapter list item
}
}
}
}
Just save the string you want to show in button in a variable.
eg :
String temp=btnText;
Then call your list adapter again.
And make a change in your getView() as
buttonAction.setText(temp);

Categories

Resources