I have a listview with Textview, ImageView and Button ,what i would like is to change the background of the button when its clicked , i hope you understunded my issue .
This is the Adapter .
package com.example.mahdi.chat;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import circleview.CircleImageView;
public class FeedListAdapter extends BaseAdapter {
private static final String TAG = FeedListAdapter.class.getSimpleName();
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
JSONParser jsonParser = new JSONParser();
private String URL = "http://10.0.3.2/social/like.php";
private String user_id;
private Button like,comment;
private static final String TAG_SUCCESS = "success";
FeedItem item;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems, String user_id) {
this.activity = activity;
this.feedItems = feedItems;
this.user_id = user_id;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
public void refresh(List<FeedItem> newlist) {
feedItems.addAll(newlist);
this.notifyDataSetChanged();
}
public List<FeedItem> getData() {
return feedItems;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.posts_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.time);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.status);
TextView url = (TextView) convertView.findViewById(R.id.url);
CircleImageView profilePic = (CircleImageView) convertView
.findViewById(R.id.profile_img);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.image);
TextView nbr_likes = (TextView)convertView.findViewById(R.id.nbr_likes);
TextView nbr_comments = (TextView)convertView.findViewById(R.id.nbr_comments);
item = feedItems.get(position);
like =(Button)convertView.findViewById(R.id.like);
comment =(Button)convertView.findViewById(R.id.comment);
like.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
item = feedItems.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
params.put("user_id", user_id);
Toast.makeText(activity, item.getId(), Toast.LENGTH_SHORT).show();
Toast.makeText(activity, user_id, Toast.LENGTH_SHORT).show();
// making fresh volley request and getting json
CustomRequest jsonReq = new CustomRequest(Request.Method.POST,
URL,params , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
});
comment.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
}
});
name.setText(item.getName());
nbr_likes.setText(item.getNbrLikes()+ " Likes");
nbr_comments.setText(item.getNbrComments() + " Comments");
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
private void parseJsonFeed(JSONObject response) {
int success;
try {
success = response.getInt(TAG_SUCCESS);
if (success == 1) {
notifyDataSetChanged();
} else {
Toast.makeText(activity, "erreur", Toast.LENGTH_SHORT).show();
}
//listAdapter.addAll(feedItems);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
FeedItem Class
package com.example.mahdi.chat;
public class FeedItem {
private String id,name, status, image, profile_img, time, url,nbr_likes,nbr_comments;
public FeedItem() {
}
public FeedItem(String id, String name, String image, String status,
String profilePic, String timeStamp, String url,String nbr_likes,String nbr_comments) {
super();
this.id = id;
this.name = name;
this.image = image;
this.status = status;
this.profile_img = profilePic;
this.time = timeStamp;
this.url = url;
this.nbr_likes = nbr_likes;
this.nbr_comments = nbr_comments;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfilePic() {
return profile_img;
}
public void setProfilePic(String profilePic) {
this.profile_img = profilePic;
}
public String getTimeStamp() {
return time;
}
public void setTimeStamp(String timeStamp) {
this.time = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNbrLikes() {
return nbr_likes;
}
public void setNbrLikes(String nbr_likes) {
this.nbr_likes = nbr_likes;
}
public String getNbrComments() {
return nbr_comments;
}
public void setNbrComments(String nbr_comments) {
this.nbr_comments = nbr_comments;
}
}
The problem is the button Like , i would like to change the drawable of the button when its clicked .Thanks.
EDIT :
package com.example.mahdi.chat;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import circleview.CircleImageView;
public class FeedListAdapter extends BaseAdapter {
private static final String TAG = FeedListAdapter.class.getSimpleName();
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
JSONParser jsonParser = new JSONParser();
private String URL = "http://10.0.3.2/social/like.php";
private String user_id;
private Button like,comment;
private static final String TAG_SUCCESS = "success";
FeedItem item;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems, String user_id) {
this.activity = activity;
this.feedItems = feedItems;
this.user_id = user_id;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
public void refresh(List<FeedItem> newlist) {
feedItems.addAll(newlist);
this.notifyDataSetChanged();
}
public List<FeedItem> getData() {
return feedItems;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.posts_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.time);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.status);
TextView url = (TextView) convertView.findViewById(R.id.url);
CircleImageView profilePic = (CircleImageView) convertView
.findViewById(R.id.profile_img);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.image);
TextView nbr_likes = (TextView)convertView.findViewById(R.id.nbr_likes);
TextView nbr_comments = (TextView)convertView.findViewById(R.id.nbr_comments);
item = feedItems.get(position);
like =(Button)convertView.findViewById(R.id.like);
comment =(Button)convertView.findViewById(R.id.comment);
like.setTag(position);
like.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
like.setBackgroundColor(Color.BLACK);
item = feedItems.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
params.put("user_id", user_id);
Toast.makeText(activity, item.getId(), Toast.LENGTH_SHORT).show();
Toast.makeText(activity, user_id, Toast.LENGTH_SHORT).show();
// making fresh volley request and getting json
CustomRequest jsonReq = new CustomRequest(Request.Method.POST,
URL,params , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
});
comment.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
item = feedItems.get(position);
Intent i = new Intent(activity, Comment.class);
i.putExtra("user_id",item.getId());
i.putExtra("name",item.getName());
i.putExtra("image",item.getImge());
i.putExtra("status",item.getStatus());
i.putExtra("profile_img",item.getProfilePic());
i.putExtra("time",item.getTimeStamp());
i.putExtra("url",item.getUrl());
i.putExtra("nbr_likes",item.getNbrLikes());
i.putExtra("nbr_comments",item.getNbrComments());
activity.startActivity(i);
}
});
name.setText(item.getName());
nbr_likes.setText(item.getNbrLikes()+ " Likes");
nbr_comments.setText(item.getNbrComments() + " Comments");
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
private void parseJsonFeed(JSONObject response) {
int success;
try {
success = response.getInt(TAG_SUCCESS);
if (success == 1) {
notifyDataSetChanged();
} else {
Toast.makeText(activity, "erreur", Toast.LENGTH_SHORT).show();
}
//listAdapter.addAll(feedItems);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Assuming the button is within the listview.
First define a click listener on the button in the getView function of the adapter:
likebutton.setOnClickListener(likeButtonClickListener);
Then define the onclick listener:
private OnClickListener likeButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
}
};
There is also another way by setting the tag in the getView function:
likebutton.setTag(position);
likebutton.setOnClickListener(likeButtonClickListener);
In the button click listener, we will get the tag and find the position value.
private OnClickListener likeButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
}
};
Edit: to explain the solution of the link i mentioned in comments.
He declares a final boolean variable mHighlightedPositions which provides info if the highlighted position in the listview is selected or not.
If this variable returns true the line in the listview is selected, so what you can do is.
Declare a variable "NUM_OF_ITEMS" as integer and the "mHighlightedPositions" as a boolean in your adapter:
private int NUM_OF_ITEMS;
private final boolean[] mHighlightedPositions = new boolean[NUM_OF_ITEMS];
With this you can define if a item in the listview is selected or not and apply the background/color to your button like he did:
...
if(mHighlightedPositions[position]) {
holder.likebutton.setBackgroundResource(R.drawable.icon_yellow_star_large);
}else {
holder.likebutton.setBackgroundResource(0);
}
...
If you want to follow his example you also need to declare a ViewHolder.
holder = new ViewHolder();
The position of the items will be returned by the position variable:
int position = (Integer)view.getTag();
See below example from the link:
#Override
public void onClick(View view) {
int position = (Integer)view.getTag(); // gets current position
Log.d(TAG, "Button row pos click: " + position);
...
...
if(mHighlightedPositions[position]) { // current position is given
button.setBackgroundResource(0);
mHighlightedPositions[position] = false;
}else {
button.setBackgroundResource(R.drawable.icon_yellow_star_large);
mHighlightedPositions[position] = true;
}
}
Related
// data is fetched from card but randon data is fetched using viewholder
//how to get proper and exact data.
//here are the all codes that i am using to recycler view
1. List item
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/28/2017.
*/
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.List;
import static com.example.jains.attendencemanagementsystem.ViewHolder.IdTextView;
import static com.example.jains.attendencemanagementsystem.ViewHolder.NameTextView;
/**
* Created by JUNED on 6/16/2016.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {
Context context;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
private RadioButton lastCheckedRB = null;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
NameTextView.setText(getDataAdapter1.getName());
IdTextView.setText(String.valueOf(getDataAdapter1.getId()));
// holder.status.setText(String.valueOf());
/** holder.setButtonClickListener(new ButtonClickListener() {
#Override
public void onButtonClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
**/
View.OnClickListener rbClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton checked_rb = (RadioButton) v;
if (lastCheckedRB != null) {
lastCheckedRB.setChecked(false);
}
lastCheckedRB = checked_rb;
}
};
/** View.OnClickListener save =new View.OnClickListener() {
#Override public void onClick(View v) {
String date = dateView.getText().toString();
String mySelectedText = mySelectedRadioButton.getText().toString();
String a=getDataAdapter1.getName().toString();
String b=String.valueOf(getDataAdapter1.getId());
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(context);
backgroundWorker.execute(type, a, b, mySelectedText, date);
}
**/
holder.P.setOnClickListener(rbClick);
holder.A.setOnClickListener(rbClick);
holder.L.setOnClickListener(rbClick);
holder.S.setOnClickListener(rbClick);
// holder.button0.setOnClickListener(save);
//CLICKED
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
}
/**
cardView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Intent i = new Intent (view.getContext(), take_attendance.class);
i.putExtra("nn",NameTextView.getText().toString());
i.putExtra("ii",IdTextView.getText());
view.getContext().startActivity(i);
}
});
**/
#Override
public int getItemCount() {
return getDataAdapter.size();
}
}
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/24/2017.
*/
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by jains on 26//2017.
*/
public class BackgroundWorker_attendance_submit extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker_attendance_submit(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.43.216/a_record_submit.php";
if(type.equals("take")) {
try {
int University_roll = Integer.parseInt(params[1]);
String student_name= params[2];
String status=params[3];
String date =params[4];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("University_roll","UTF-8")+"="+URLEncoder.encode(String.valueOf(University_roll),"UTF-8")+"&"
+URLEncoder.encode("student_name","UTF-8")+"="+URLEncoder.encode(student_name,"UTF-8")+"&"
+URLEncoder.encode("status","UTF-8")+"="+URLEncoder.encode(String.valueOf(status),"UTF-8")+"&"
+URLEncoder.encode("date","UTF-8")+"="+URLEncoder.encode(date,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Registration Status...");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}`package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 7/1/2017.
*/
import android.view.View;
/**
* Created by Hp on 3/18/2016.
*/
public interface ItemClickListener {
void onItemClick(View v,int pos);
}`package com.example.jains.attendencemanagementsystem;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
/**
* Created by jains on 7/2/2017.
*/
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
ButtonClickListener buttonClickListener;
static TextView IdTextView;
static TextView NameTextView;
static RadioButton P, A, L, S;
static Button button11;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
static CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
IdTextView = (TextView) itemView.findViewById(R.id.textView2);
NameTextView = (TextView) itemView.findViewById(R.id.textView4);
itemView.setOnClickListener(this);
P = (RadioButton) itemView.findViewById(R.id.checkBoxP);
A = (RadioButton) itemView.findViewById(R.id.checkBoxA);
L = (RadioButton) itemView.findViewById(R.id.checkBoxL);
S = (RadioButton) itemView.findViewById(R.id.checkBoxS);
//this button is submit attendance button in card
button11 = (Button) itemView.findViewById(R.id.button11);
//these are the 4 radio button and radio group
myradiogroup = (RadioGroup) itemView.findViewById(R.id.myradiogroup);
int id = myradiogroup.getCheckedRadioButtonId();
mySelectedRadioButton = (RadioButton) itemView.findViewById(id);
cardView = (CardView)itemView.findViewById(R.id.cardview1);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(v, getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic) {
this.itemClickListener = ic;
}
/** #Override
public void save(View view)
{
this.buttonClickListener.onButtonClick(view ,getLayoutPosition());
}
public void setButtonClickListener(ButtonClickListener bc)
{
this.buttonClickListener=bc;
}
**/
} /**
#Override
public void onClick(View v) {
**/
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/28/2017.
*/
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.List;
import static com.example.jains.attendencemanagementsystem.ViewHolder.IdTextView;
import static com.example.jains.attendencemanagementsystem.ViewHolder.NameTextView;
/**
1. Created by JUNED on 6/16/2016.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {
Context context;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
private RadioButton lastCheckedRB = null;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
NameTextView.setText(getDataAdapter1.getName());
IdTextView.setText(String.valueOf(getDataAdapter1.getId()));
// holder.status.setText(String.valueOf());
/** holder.setButtonClickListener(new ButtonClickListener() {
#Override
public void onButtonClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
**/
View.OnClickListener rbClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton checked_rb = (RadioButton) v;
if (lastCheckedRB != null) {
lastCheckedRB.setChecked(false);
}
lastCheckedRB = checked_rb;
}
};
/** View.OnClickListener save =new View.OnClickListener() {
#Override public void onClick(View v) {
String date = dateView.getText().toString();
String mySelectedText = mySelectedRadioButton.getText().toString();
String a=getDataAdapter1.getName().toString();
String b=String.valueOf(getDataAdapter1.getId());
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(context);
backgroundWorker.execute(type, a, b, mySelectedText, date);
}
**/
holder.P.setOnClickListener(rbClick);
holder.A.setOnClickListener(rbClick);
holder.L.setOnClickListener(rbClick);
holder.S.setOnClickListener(rbClick);
// holder.button0.setOnClickListener(save);
//CLICKED
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
}
/**
cardView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Intent i = new Intent (view.getContext(), take_attendance.class);
i.putExtra("nn",NameTextView.getText().toString());
i.putExtra("ii",IdTextView.getText());
view.getContext().startActivity(i);
}
});
**/
#Override
public int getItemCount() {
return getDataAdapter.size();
}
}
2. List item
package com.example.jains.attendencemanagementsystem;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class take_attendance extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
TextView uni,name;
RadioButton radioButton_P,radioButton_A,radioButton_L,radioButton_S;
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
// SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
// String t_name= sharedPreferences.getString(Config.NAME_SHARED_PREF,"Not Available");
//TextView textView=(TextView)findViewById(R.id.showuser);
//
String GET_JSON_DATA_HTTP_URL = "http://192.168.43.216/fetch_stud.php?t_name=";
String JSON_STUDENT_NAME = "student_name";
String JSON_UNIVERSITY_ROLL = "University_roll";
Button button0;
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
RadioButton mySelectedRadioButton;
RadioGroup myradiogroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_attendance);
//uni=(TextView)findViewById(R.id.textView2);
//name=(TextView)findViewById(R.id.textView4);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button0 = (Button)findViewById(R.id.button0) ;
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//button0.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});
dateView = (TextView) findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
}
public void save(View view)
{
saving();
}
private void saving()
{
// I want to get Student name and University Roll grom the card content which button is clicked by the user
String a= ViewHolder.IdTextView.getText().toString();
String b= ViewHolder.NameTextView.getText().toString();
String date = dateView.getText().toString();
myradiogroup=(RadioGroup)findViewById(R.id.myradiogroup);
int id = myradiogroup.getCheckedRadioButtonId();
mySelectedRadioButton = (RadioButton) findViewById(id);
String mySelectedText = mySelectedRadioButton.getText().toString();
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(this);
backgroundWorker.execute(type, a,b,mySelectedText,date);
//Intent y= new Intent(register_main.this,teacher.class);
//startActivity(y);
// Toast.makeText(register_main.this, "Successfully Registered...!!!", Toast.LENGTH_LONG).show();
}
public void JSON_DATA_WEB_CALL(){
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String aa= sharedPreferences.getString(Config.NAME_SHARED_PREF,"Not Available");
final String a= GET_JSON_DATA_HTTP_URL.concat(aa);
jsonArrayRequest = new JsonArrayRequest(a,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
// button0.setVisibility(View.GONE);
Snackbar.make(recyclerView,"Note--> Take Attendance Of All Students ",1000000000).setDuration(1000000000).show();
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_UNIVERSITY_ROLL));
GetDataAdapter2.setName(json.getString(JSON_STUDENT_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
//DATE PICKER FUNCTIONS
#SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}
I'm a novice when it comes to Android + Firebase and I don't really understand about asynchronous listeners. Is there a way to add to an ArrayList inside the onDataChange() method?
I'm using this to populate my ListView. I know and I have tried the FirebaseUI's ListViewAdapter and RecyclerViewAdapter, but I want to have a customAdapter since I can control it better than the FirebaseUI's adapter.
Here is my code for the MainActivity:
package com.example.chiz.list_view_adapter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mRecipeRef = mRootRef.child("recipes");
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> urls = new ArrayList<String>();
ArrayList<String> images = new ArrayList<String>();
ListView listView;
List<Recipes> rowItems;
private static final String TAG = "Chiz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.recipe_list);
this.getData();
rowItems = new ArrayList<Recipes>();
for (int i = 0; i < titles.size(); i++) {
Recipes item = new Recipes(titles.get(i), urls.get(i), images.get(i));
rowItems.add(item);
}
RecipeListAdapter adapter = new RecipeListAdapter(this, rowItems);
listView.setAdapter(adapter);
}
public void getData(){
mRecipeRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String recipeKey = postSnapshot.getKey();
String title = postSnapshot.child("title").getValue(String.class);
String url = postSnapshot.child("url").getValue(String.class);
String image_url = postSnapshot.child("image_url").getValue(String.class);
//I want something like this:
//titles.add(title);
//urls.add(url);
//images.add(image_url);
Log.d(TAG, "recipeKey: "+recipeKey);
Log.d(TAG, "title: "+title);
Log.d(TAG, "url: "+url);
Log.d(TAG, "image_url: "+image_url);
Log.d(TAG, "-----");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
}
}
Recipes:
package com.example.chiz.list_view_adapter;
public class Recipes {
private String title;
private String url;
private String image_url;
public Recipes() {
}
public Recipes(String title, String url, String image_url){
super();
this.title = title;
this.url = url;
this.image_url = image_url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
url = url;
}
public String getImage_url() {
return image_url;
}
public void setImage(String image_url) {
image_url = image_url;
}
}
RecipeListAdapter:
package com.example.chiz.list_view_adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecipeListAdapter extends BaseAdapter {
Context context;
List<Recipes> rowItems;
public RecipeListAdapter ( Context context, List<Recipes> items ) {
this.context = context;
this.rowItems = items;
}
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtUrl;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.txtUrl = (TextView) convertView.findViewById(R.id.Text2);
holder.txtTitle = (TextView) convertView.findViewById(R.id.Text1);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Recipes rowItem = (Recipes) getItem(position);
holder.txtUrl.setText(rowItem.getUrl());
holder.txtTitle.setText(rowItem.getTitle());
Picasso.with(context).load(rowItem.getImage_url()).error(R.drawable.placeholder_error).into(holder.imageView);
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
Try this. I have used ListenerForSingleValueEvent to avoid redundancy.
mRecipeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
Recipes recipe = postSnapshot.getValue(Recipes.class);
titles.add(recipe.getTitle());
urls.add(recipe.getUrl());
images.add(recipe.getImage_url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have created a custom Adapter for list which different items and each item has a button to invite. The item should flip horizontally when the respective invite button is clicked and that is working fine. The problem is that when I click invite button of first item then invite button of 4th item is also clicked. I am attaching the code hee
package rovoltlabs.coffeechat.adapters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rovoltlabs.coffeechat.R;
import rovoltlabs.coffeechat.animation.AnimationFactory;
import rovoltlabs.coffeechat.animation.AnimationFactory.FlipDirection;
import rovoltlabs.coffeechat.volley.utils.Const;
import rovoltslabs.coffeechat.app.AppController;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
public class MyCustomAdapter extends BaseAdapter implements OnClickListener {
Context contexts;
List<String> name = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
List<String> slots = new ArrayList<String>();
List<String> heading = new ArrayList<String>();
List<String> showtime = new ArrayList<String>();
List<Bitmap> img = new ArrayList<Bitmap>();
List<ViewHolder> myview = new ArrayList<ViewHolder>();
private String tag_json_obj = "jobj_req";
private LayoutInflater mLayoutInflater;
View row;
ViewHolder holder;
public MyCustomAdapter(Context context, List<String> name,
List<Bitmap> img, List<String> heading, List<String> slots,
List<String> id) {
super();
this.contexts = context;
this.name = name;
this.img = img;
this.heading = heading;
this.slots = slots;
this.ids = id;
mLayoutInflater = ((Activity) contexts).getLayoutInflater();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
// check to see if the reused view is null or not, if is not null then
// reuse it
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.item, null);
holder.name = (TextView) view.findViewById(R.id.Name);
holder.fname = (TextView) view.findViewById(R.id.flipName);
holder.msg = (EditText) view.findViewById(R.id.fsend);
holder.heading = (TextView) view.findViewById(R.id.ddheading);
holder.distance = (TextView) view.findViewById(R.id.Distance);
holder.image = (ImageView) view.findViewById(R.id.imagecoffee);
holder.invite = (Button) view.findViewById(R.id.inviteButton);
holder.send = (Button) view.findViewById(R.id.fsendButton);
holder.time = (TextView) view.findViewById(R.id.timefree);
holder.viewAnimator = (ViewAnimator) view
.findViewById(R.id.viewFlipper);
myview.add(holder);
holder.v = view;
} else {
holder = (ViewHolder) view.getTag();
}
view.setTag(holder);
holder.invite.setOnClickListener(this);
holder.send.setOnClickListener(this);
holder.name.setText(name.get(position).split("\n")[0]);
holder.fname.setText(name.get(position).split("\n")[0]);
holder.heading.setText(heading.get(position));
String temp = "";
int sl = Integer.parseInt(slots.get(position));
if (sl % 2 == 0) {
temp = "" + ((sl / 2) - 1) + ":30 - " + ((sl / 2)) + ":00";
} else {
temp = "" + ((sl / 2)) + ":00-" + ((sl / 2)) + ":30";
}
holder.time.setText(temp);
holder.distance.setText(name.get(position).split("\n")[1] + " m");
holder.image.setImageBitmap(img.get(position));
holder.invite.setTag(position);
holder.send.setTag(position);
return view;
}
private static class ViewHolder {
protected TextView name;
protected TextView heading;
protected TextView distance, time;
protected ImageView image;
protected Button invite, send;
protected View v;
protected ViewAnimator viewAnimator;
protected TextView fname;
protected EditText msg;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.inviteButton) {
AnimationFactory.flipTransition(
myview.get((Integer) v.getTag()).viewAnimator,
FlipDirection.LEFT_RIGHT);
} else if (v.getId() == R.id.fsend) {
SharedPreferences pref = contexts.getApplicationContext()
.getSharedPreferences("MyPref", 0);
String slotsss = "{\"slots\":[" + slots.get((Integer) v.getTag())
+ "]}";
final Map<String, String> params = new HashMap<String, String>();
params.put("slot", slotsss);
Log.e("invite slots", slotsss);
params.put("to", ids.get((Integer) v.getTag()));
params.put("from", pref.getString("id", "N/A"));
params.put("message", myview.get((Integer) v.getTag()).msg
.getText().toString());
StringRequest jsonObjReq = new StringRequest(Method.POST,
Const.URL_INVITE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Slots Response: ", response.toString());
Toast.makeText(contexts, "invited" + response,
Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("invite Error:",
"Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
}
}
}
The View objects are recycling and you're using the same ViewHolder object (and other UI components) for both positions. The view being clicked has had its tag updated to the position desired, but the animation object is the same as another position due to the recycling.
I have a ListView ,In that each ListItem having some items(textViews),In which one textView is having click event.That I have put in my custom adater,And I am calling an asynctask on its cLick event,For that I want a value when I click on that textView its "queID" I want,But currently I am gettong it null..Please see my code and help me please..!
"qoute" is that textView.On which I have put click event.how to set"buyer_req_Id" and get tag on it?I currrently successfully get the tag on each "ListItem" Click event ,I want to set the same tag on ListItem's textView.Inside java class I have put only adapter,In which I want "buyer_request_id".
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
java class(asynctask)
public class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
scr_post.setVisibility(View.GONE);
scr_view.setVisibility(View.GONE);
quote_view.setVisibility(View.VISIBLE);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// String query = "?customer_id=" +
// Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "")
// + "&buyer_request_id=23";
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + buyer_request_id;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyerID = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyerID);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyerID);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
queList.add(quote);
System.out.println(":::::::::::::Buyer request ID:" + buyerID);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
quoteAdapter = new QuoteAdapter(BuyingreqActivity.this, queList);
quoteList.setAdapter(quoteAdapter);
}
}
// Try this way,hope this will help you...
localViewholder.quote.setTag(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
String buyerId = v.getTag().toString(); // user this buyerId for your requirement
System.out.println("Buyer Id Is "+buyerId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
I have solved my problem as below by changing my asynctask to void to string :
adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> reqList) {
this.mContext = paramContext;
this.BuyingRequestArray = reqList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
/* localViewholder.quote.setTag(localViewholder); */
} else {
localViewholder = (Viewholder) paramView.getTag();
/* localViewholder.quote = ((TextView) paramView.getTag()); */
}
final String reqId = BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println("::::::::::::::My reqId:::::::::::" + reqId);
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
System.out.println("Buyer Id Is " + reqId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute(reqId);
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
I hakve made a custom adaptor for binding parsed data into a listView,I have tried as below,But it only gives me 1st value .please help me.I want to bind all the values to listView but currently i only able to bind only 1\one value in it..
Registration.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.CountryAdapter;
import com.epe.yehki.adapter.WholesaleProductAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.backend.RegisterationAPI;
import com.epe.yehki.backend.ResponseListener;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Const.API_RESULT;
import com.example.yehki.R;
public class RegistrationActivity extends Activity {
public RegisterationAPI registartionAPI;
private EditText fName;
private EditText lName;
private EditText eMail;
private Button register;
private EditText contact;
private EditText password;
private ListView countrylist;
private ListView statelist;
private TextView tv_country;
private TextView state;
JSONArray countries = null;
// Fetching List
JSONObject jsonObj;
JSONArray contries = null;
ArrayList<HashMap<String, String>> countryList;
private CountryAdapter countryContent;
// Hashmap for ListView
public com.epe.yehki.uc.Menu regMenu;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_registration);
// FINDING IDS...
fName = (EditText) findViewById(R.id.et_fname);
lName = (EditText) findViewById(R.id.et_lname);
eMail = (EditText) findViewById(R.id.et_email);
contact = (EditText) findViewById(R.id.et_contact);
password = (EditText) findViewById(R.id.et_pwd);
tv_country = (TextView) findViewById(R.id.et_country);
state = (TextView) findViewById(R.id.et_state);
regMenu = (Menu) findViewById(R.id.menuReg);
register = (Button) findViewById(R.id.btn_register);
countrylist = (ListView) findViewById(R.id.country_list);
countrylist.setVisibility(View.GONE);
statelist = (ListView) findViewById(R.id.state_list);
countryList = new ArrayList<HashMap<String, String>>();
regMenu.setSelectedTab(1);
new GetCountries().execute();
countrylist.setVisibility(View.GONE);
// COUNTRY LIST CLICK EVENT...!!!
countrylist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String countryname = ((TextView) view.findViewById(R.id.name)).getText().toString();
tv_country.setText(countryname);
// countrylist.setVisibility(view.GONE);
}
});
// REGISTER BUTTOM CLICK EVENT.....!
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!fName.getText().toString().equals("") && fName.getText().toString() != null) {
if ((!lName.getText().toString().equals("") && lName.getText().toString() != null)) {
if ((!tv_country.getText().toString().equals("") && tv_country.getText().toString() != null)) {
if ((!state.getText().toString().equals("") && state.getText().toString() != null)) {
if ((!eMail.getText().toString().equals("") && eMail.getText().toString() != null)) {
if ((!password.getText().toString().equals("") && password.getText().toString() != null)) {
if ((!contact.getText().toString().equals("") && contact.getText().toString() != null)) {
} else {// CONTACT NUMBER
validation(getResources().getString(R.string.valid_number));
password.requestFocus();
}
} else {// password...
validation(getResources().getString(R.string.valid_pwd));
password.requestFocus();
}
} else {// EMAIL
validation(getResources().getString(R.string.valid_mail));
eMail.requestFocus();
}
} else {// STATE
validation(getResources().getString(R.string.valid_state));
state.requestFocus();
}
} else {// COUNTRY
validation(getResources().getString(R.string.valid_country));
tv_country.requestFocus();
}
} else {// LAST NAME
validation(getResources().getString(R.string.valid_lname));
lName.requestFocus();
}
} else {// FIRST NAME
validation(getResources().getString(R.string.valid_fname));
fName.requestFocus();
}
}
});
// COUINTRY LIST CLICK EVENT...!!!!
tv_country.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
countrylist.setVisibility(View.VISIBLE);
}
});
}
void validation(String msg) {
Toast.makeText(RegistrationActivity.this, msg, Toast.LENGTH_SHORT).show();
}
ResponseListener responseListener = new ResponseListener() {
#Override
public void onResponce(String api, API_RESULT result, Object obj) {
System.out.println("::::::::::::::inside response Listener::::::::");
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if (api.equals(Const.API_LOGIN)) {
System.out.println("::::::::::::::inside response Listener::::::::1");
if (result == Const.API_RESULT.SUCCESS) {
registartionAPI = null;
// as
// doctor
System.out.println("success Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
startActivity(new Intent(RegistrationActivity.this, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
} else {
System.out.println("failed Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
}
}
}
};
// ASYNC TASK FOR GETTING COUNTRY LIST...!!!
private class GetCountries extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(Const.API_COUTRY, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_COUNTY_LIST)) {
contries = jsonObj.getJSONArray(Const.TAG_COUNTY_LIST);
System.out.println(":::::::::PRODUCT lENGTH:::::::::::" + contries.length());
if (contries != null && contries.length() != 0) {
// looping through All Contacts
for (int i = 0; i < contries.length(); i++) {
JSONObject c = contries.getJSONObject(i);
String Con_id = c.getString(Const.TAG_COUNTRY_ID);
System.out.println("::::::::::::::::::PARSING PRODUCT ID:::::::::::::" + Con_id);
String CountryName = c.getString(Const.TAG_COUNTRY_NAME);
HashMap<String, String> country = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
country.put(Const.TAG_COUNTRY_ID, Con_id);
country.put(Const.TAG_COUNTRY_NAME, CountryName);
countryList.add(country);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
countryContent = new CountryAdapter(RegistrationActivity.this, countryList);
countrylist.setAdapter(countryContent);
}
}
}
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class CountryAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> countryArray;
private Context mContext;
public CountryAdapter(Context paramContext, ArrayList<HashMap<String, String>> countryList) {
this.mContext = paramContext;
this.countryArray = countryList;
}
public int getCount() {
return this.countryArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.con_id = ((TextView) paramView.findViewById(R.id.cat_id));
localViewholder.con_name = ((TextView) paramView.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.con_name.setText(countryArray.get(paramInt).get(Const.TAG_COUNTRY_NAME));
System.out.println("::::::::::::::::::;PRDUCT name" + countryArray.get(paramInt).get(Const.TAG_COUNTRY_NAME));
return paramView;
}
static class Viewholder {
TextView con_id;
TextView con_name;
}
}
Please try the following class:
public class CountryAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> countryArray;
private Context mContext;
public a(Context paramContext, ArrayList<HashMap<String, String>> countryList) {
this.mContext = paramContext;
this.countryArray = countryList;
}
public int getCount() {
return countryArray.size();
}
public Object getItem(int paramInt) {
return countryArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
Viewholder localViewholder;
LayoutInflater localLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.con_id = ((TextView) paramView.findViewById(R.id.cat_id));
localViewholder.con_name = ((TextView) paramView.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
HashMap<String, String> data = (HashMap<String, String>) getItem(paramInt);
localViewholder.con_name.setText(data.get(Const.TAG_COUNTRY_NAME));
return paramView;
}
static class Viewholder {
TextView con_id;
TextView con_name;
}
}
Please note you can't use System.out.println on Android, please use Log class instead: Log.d("myTag", "message").
Please update the line
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
to
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
remove localViewholder = new Viewholder(); from getView else condition. Here you are creating a new holder object every time.
It should be
else {
localViewholder = (Viewholder) paramView.getTag();
}