ListVew Repeating same row from MySql database in Android - android

I had an ListVew where I have to show the orders List from Database.I have Multiple orders in Mysql Database but only one order is continuously repeating in ListVew.Any help regarding this is Appreciated.
Here is my Adapter Class
public class OrderApprovalAdapter extends ArrayAdapter
{
List list1 = new ArrayList();
Context context;
public OrderApprovalAdapter(#NonNull Context context, #NonNull int Resource)
{
super(context, Resource);
this.context = context;
}
#Override
public void add(#Nullable Object object)
{
super.add(object);
list1.add(object);
}
#Override
public int getCount()
{
return list1.size();
}
#Override
public Object getItem(int position)
{
return list1.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final OrderApprovalAdapter.ContactHolder contactHolder;
View row;
row = convertView;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.order_approval_format, parent, false);
contactHolder = new ContactHolder();
contactHolder.date = (TextView) row.findViewById(R.id.invoice_date);
contactHolder.orderid = (TextView) row.findViewById(R.id.invoice_no);
contactHolder.shopname = (TextView) row.findViewById(R.id.shop_name);
contactHolder.ownername = (TextView) row.findViewById(R.id.owner_name);
contactHolder.mobile=(TextView) row.findViewById(R.id.mobile_noo);
contactHolder.location=(TextView)row.findViewById(R.id.location);
contactHolder.itemscount=(TextView)row.findViewById(R.id.items);
contactHolder.amount=(TextView)row.findViewById(R.id.total);
contactHolder.Approval=(Button)row.findViewById(R.id.Approve_btn);
contactHolder.Decline=(Button)row.findViewById(R.id.decline_btn);
row.setTag(contactHolder);
} else
{
contactHolder = (ContactHolder) row.getTag();
}
final OrderApprovalDetails contacts = (OrderApprovalDetails) this.getItem(position);
contactHolder.date.setText(contacts.getDate());
contactHolder.orderid.setText(contacts.getOrderid());
contactHolder.shopname.setText(contacts.getShopname());
contactHolder.ownername.setText(contacts.getOwnername());
contactHolder.mobile.setText(contacts.getMobile());
contactHolder.location.setText(contacts.getLocation());
contactHolder.itemscount.setText(contacts.getItemscount());
contactHolder.amount.setText(contacts.getAmount());
contactHolder.Approval.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Approved", Toast.LENGTH_SHORT).show();
}
});
contactHolder.Decline.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Decline", Toast.LENGTH_SHORT).show();
}
});
return row;
}
static class ContactHolder
{
TextView date,orderid,shopname,ownername,mobile,location,itemscount,amount;
Button Approval,Decline;
}
}
Retriving Data From Database
class OrdersListBackgroundTask extends AsyncTask<Void,Void,String>
{
#Override
protected void onPreExecute()
{
OrdersList_url="http://10.0.2.2/accounts/OrderForm2.php";
}
#Override
protected String doInBackground(Void... params)
{
try {
URL url=new URL(OrdersList_url);
HttpURLConnection httpURLConnection=
(HttpURLConnection)url.openConnection();
InputStream is= httpURLConnection.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
StringBuilder sb=new StringBuilder();
while ((JSON_STRING4=br.readLine())!=null)
{
sb.append(JSON_STRING4+ "");
}
br.close();
is.close();
httpURLConnection.disconnect();
return sb.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
//TextView tv=(TextView)findViewById(R.id.tv);
//tv.setText(result);
json_string4=result;
}
}
Sending Through intent to Next Page
public void Orders_List(View v)//Button click
{
if (json_string4==null)
{
Toast.makeText(this, "Get Orders First", Toast.LENGTH_SHORT).show();
}else
{
Intent i1=new Intent(this,OrdersList.class);
i1.putExtra("json_data4",json_string4);
startActivity(i1);
}
}
Usage in MainActivity
json_string4=getIntent().getExtras().getString("json_data4");
listView_Orders=(ListView)findViewById(R.id.listViewOrderlist);
listView_Orders.setItemsCanFocus(true);
search_filter=(EditText)findViewById(R.id.search_et);
orderApprovalAdapter=new
OrderApprovalAdapter(this,R.layout.order_approval_format);
listView_Orders.setAdapter(orderApprovalAdapter);
//listView_Orders.setTextFilterEnabled(true);
try
{
jsonObject=new JSONObject(json_string4);
jsonArray=jsonObject.getJSONArray("orders");
int count=0;
for (int i=0;i<jsonArray.length();i++)
{
JSONObject jo=jsonArray.getJSONObject(i);
date=jo.getString("date");
orderid=jo.getString("orderid");
shopname=jo.getString("shopname");
ownername=jo.getString("ownername");
mobile=jo.getString("mobile");
location=jo.getString("location");
items=jo.getString("items_count");
amount=jo.getString("amount");
OrderApprovalDetails orderApprovalDetails=new OrderApprovalDetails(date,orderid,shopname,ownername,mobile,location,items,amount,Approve,Decline);
orderApprovalAdapter.add(orderApprovalDetails);
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
OrderApprovalDetails Class
public class OrderApprovalDetails
{
public static String
date,orderid,shopname,ownername,mobile,location,itemscount,amount;
public static Button Approval,Decline;
public OrderApprovalDetails(String date,String orderid,String shopname,String ownername,String mobile,String location,String itemscount,String amount,Button Approval,Button Decline)
{
this.setDate(date);
this.setOrderid(orderid);
this.setShopname(shopname);
this.setOwnername(ownername);
this.setMobile(mobile);
this.setLocation(location);
this.setItemscount(itemscount);
this.setAmount(amount);
this.setApproval(Approval);
this.setDecline(Decline);
}
public String getDate()
{
return date;
}
public static Button getApproval() {
return Approval;
}
public static void setApproval(Button approval) {
Approval = approval;
}
public static Button getDecline() {
return Decline;
}
public static void setDecline(Button decline) {
Decline = decline;
}
public void setDate(String date) {
this.date = date;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
public String getShopname() {
return shopname;
}
public void setShopname(String shopname) {
this.shopname = shopname;
}
public String getOwnername() {
return ownername;
}
public void setOwnername(String ownername) {
this.ownername = ownername;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getItemscount() {
return itemscount;
}
public void setItemscount(String itemscount) {
this.itemscount = itemscount;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Don't know where I did Mistake,Please Help me to findout that,Thanks in Advance.

You class members should never be declared static as you have done here -
public class OrderApprovalDetails
{
public static String date,orderid,shopname,ownername,mobile,location,itemscount,amount;
change this to
public class OrderApprovalDetails
{
public String date,orderid,shopname,ownername,mobile,location,itemscount,amount;

Related

display json data letest record as per user id

i wont to display the list of chats of clients.the data is come from json,
the last message of chat is display on chat.but it displays all message of all clients in list.like
here is my ListMessage.class activity
public class ListMessage extends AppCompatActivity implements View.OnClickListener {
ImageButton btnFooter_Home, btnFooter_Message, btnFooter_Notification, btnFooter_More;
EditText textUser;
List<Msg_data> msgList;
ListView lv;
String uri = "http://staging.talentslist.com/api/user/23/chat";
LinearLayout linear_Home, linear_Message, linear_Notification, linear_More;
GlobalClass myGlog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_message);
myGlog = new GlobalClass(getApplicationContext());
setFooter();
lv = (ListView) findViewById(R.id.listView);
textUser = (EditText) findViewById(R.id.textUser);
// textUser.isFocused()
boolean inConnected = myGlog.isNetworkConnected();
if (inConnected) {
requestData(uri);
}
}
public void requestData(String uri) {
StringRequest request = new StringRequest(uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
lv.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ListMessage.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
}
MsgAdapter.java class
public class MsgAdapter extends BaseAdapter{
private Context context;
private List<Msg_data> nList;
private LayoutInflater inflater = null;
private LruCache<Integer, Bitmap> imageCache;
private RequestQueue queue;
String isread;
public MsgAdapter(Context context, List<Msg_data> list) {
this.context = context;
this.nList = list;
inflater = LayoutInflater.from(context);
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
imageCache = new LruCache<>(cacheSize);
queue = Volley.newRequestQueue(context);
}
public class ViewHolder {
TextView __isread;
TextView _username;
TextView _detais;
TextView _time;
ImageView _image;
}
#Override
public int getCount() {
return nList.size();
}
#Override
public Object getItem(int position) {
return nList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
final Msg_data msg = nList.get(position);
final ViewHolder holder;
isread = msg.getIs_read();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_notification, null);
if (isread.equals("0")) {
convertView.setBackgroundColor(Color.parseColor("#009999"));
}
holder = new ViewHolder();
holder._username = (TextView) convertView.findViewById(R.id.tvtitle);
holder._detais = (TextView) convertView.findViewById(R.id.tvdesc);
holder.__isread = (TextView) convertView.findViewById(R.id.tvplateform);
holder._time = (TextView) convertView.findViewById(R.id.createdTime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._username.setText(msg.getUser_name().toString());
holder._detais.setText(msg.getMessage().toString());
holder._time.setText(msg.getCreated_at().toString());
// holder.__isread.setText(notifi.getIs_read().toString());
holder._image = (ImageView) convertView.findViewById(R.id.gameImage);
Glide.with(context)
.load(msg.getImage_link().toString()) // Set image url
.diskCacheStrategy(DiskCacheStrategy.ALL) // Cache for image
.into(holder._image);
return convertView;
}
}
Msg_data.java class
public class Msg_data {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
}
MsgJSONParser.java class
public class MsgJSONParser {
static List<Msg_data> notiList;
public static List<Msg_data> parseData(String content) {
JSONArray noti_arry = null;
Msg_data noti = null;
try {
JSONObject jsonObject = new JSONObject(content);
noti_arry = jsonObject.getJSONArray("data");
notiList = new ArrayList<>();
for (int i = 0; i < noti_arry.length(); i++) {
JSONObject obj = noti_arry.getJSONObject(i);
//JSONObject obj = noti_arry.getJSONObject(i);
noti = new Msg_data();
noti.setId(obj.getInt("id"));
noti.setMessage(obj.getString("message"));
noti.setUser_name(obj.getString("user_name"));
noti.setFrom(obj.getString("from"));
noti.setTo(obj.getString("to"));
noti.setCreated_at(obj.getString("created_at"));
noti.setImage_link(obj.getString("image_link"));
noti.setIs_read(obj.getString("is_read"));
notiList.add(noti);
}
return notiList;
} catch (JSONException ex) {
ex.printStackTrace();
return null;
}
}
}
please give me some idea what to do and how to do
i guess, you should replace
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
with
msgList = MsgJSONParser.parseData(response);
ArrayList<Msg_data> userList=new ArrayList();
for (int i=0;i<msgList.size();i++){
if (!userList.contains(msgList.get(i)))
userList.add(msgList.get(i));
else {
int index=userList.indexOf(msgList.get(i));
if (userList.get(index).compareTo(msgList.get(i))>0)
userList.add(msgList.get(i));
}
}
MsgAdapter adapter = new MsgAdapter(ListMessage.this, userList);`
and implement Comparable and override equals method in your Msg_data class
public class Msg_data implements Comparable {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
try
{
return (this.getUser_id().equals(( (Msg_data)obj).getUser_id()));
}
catch(NullPointerException e){
return false;
}
}
#Override
public int compareTo(#NonNull Object o) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("your pattern here");
try {
Date date=simpleDateFormat.parse(created_at);
Date dateOtherObject=simpleDateFormat.parse(((Msg_data)o).getCreated_at());
return date.compareTo(dateOtherObject);
}
catch (ParseException e){
return -1;
}
}
something like this:) Dont forget replace simple date format in compare method

Recyclerview sort by time ascending

I have a recyclerview that display news.
News is composed by name_news,image_news,time_news.
I am getting the data from mysqldatabse.
This is my adapter class:
public class PostAdapter2 extends RecyclerView.Adapter<PostAdapter2.ViewHolder>{
public Context c;
public FragmentManager mContext;
public ArrayList<News_data> original_items = new ArrayList<>();
public ArrayList<News_data> filtered_items = new ArrayList<>();
public ArrayList<Simplenews_data> original_items2 = new ArrayList<>();
public ArrayList<Simplenews_data> filtered_items2 = new ArrayList<>();
// ItemFilter mFilters = new ItemFilter();
public PostAdapter2(Context c, ArrayList<News_data> postList) {
this.c = c;
this.original_items = postList;
this.filtered_items = postList;
}
public PostAdapter2(FragmentManager mContext, ArrayList<Simplenews_data> postList) {
this.mContext = mContext;
this.original_items2 = postList;
this.filtered_items2 = postList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_news, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
try {
final Simplenews_data post = filtered_items2.get(position);
PicassoClient.downloadImage(c, post.getImage_simplenews(), holder.image_news);
holder.txt_news_title.setText(post.getName_simplenews());
holder.txt_date.setText(post.getTime_simplenews());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick() {
Bundle x = new Bundle();
x.putString("news_title", post.getName_simplenews());
x.putString("news", post.getDesc_simplenews());
x.putString("image",post.getImage_simplenews());
x.putString("time",post.getTime_simplenews());
x.putString("date",post.getDate_simplenews());
Fragment descriptionFragment = new DescriptionFragment();
FragmentTransaction transaction = mContext.beginTransaction();
descriptionFragment.setArguments(x);
transaction.replace(R.id.framelayout, descriptionFragment).addToBackStack(null).commit();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return filtered_items2.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
TextView txt_news_title,txt_date;
ImageView image_news;
public ViewHolder(View itemView) {
super(itemView);
txt_news_title = (TextView) itemView.findViewById(R.id.txt_news_title);
txt_date = (TextView) itemView.findViewById(R.id.txt_timedate);
image_news = (ImageView) itemView.findViewById(R.id.image_news);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
try {
this.itemClickListener.onItemClick();
}catch (Exception e)
{
e.printStackTrace();
}
}
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener=itemClickListener;
}
}
}
I am using a PHP interface to add news.
The getTime_simplenews() contains the news sumbmitted time format as : 14:00
So i want to display the immediate news in Top of recyclerview not under the previous news.
Thanks a lot.
UPDATED :
public class Simplenews_data {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
Fragment Code:
public void parseJson2(String response) {
try {
JSONArray array = new JSONArray(response);
JSONObject jsonObject = null;
post_array2.clear();
Simplenews_data p;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
int id_simplenews = jsonObject.getInt("id_simplenews");
String name_simplenews = jsonObject.getString("name_simplenews");
String image_simplenews = jsonObject.getString("image_simplenews");
String desc_simplenews = jsonObject.getString("desc_simplenews");
String time_simplenews = jsonObject.getString("time_simplenews");
String date_simplenews = jsonObject.getString("date_simplenews");
p = new Simplenews_data();
p.setId_simplenews(id_simplenews);
p.setName_simplenews(name_simplenews);
p.setImage_simplenews(image_simplenews);
p.setDesc_simplenews(desc_simplenews);
p.setTime_simplenews(time_simplenews);
p.setDate_simplenews(date_simplenews);
post_array2.add(p);
}
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
e.printStackTrace();
}
adapter = new PostAdapter2(getFragmentManager(), post_array2);
recycler_post.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
I have updated your model class and implemented Comparable to it
public class Simplenews_data implements Comparable<Simplenews_data> {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
#Override
public int compareTo(MyObject o) {
Date newDate = formatDateTime(o.getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
Date inputDate = formatDateTime(getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
return inputDate.compareTo(newDate);
}
public Date formatDateTime(String date, String fromFormat, String toFormat) {
Date d = null;
try {
d = new SimpleDateFormat(fromFormat, Locale.US).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new SimpleDateFormat(toFormat, Locale.US).parse(d);
}
}
Sort the list using below code
Collections.sort(yourList);

Android List View Custom Adapter with Checkbox multiple selection and Search Listview

I Have implemented the ListView with Custom Adopter class and Multiple check box selection . Its working fine . After that I have given search the name in ListView. If I checked row item then I search the name in search , Search positioned was changed . Kindly help me to fix this.
Model Class
public class FullUser {
String name=null;
String id=null;
boolean checked;
public FullUser(String name, String id,boolean checked){
this.name=name;
this.id = id;
this.checked = checked;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getId(){
return this.id;
}
public void setId(String id){
this.id = id;
}
public Boolean getChecked(){
return this.checked;
}
public void setChecked(Boolean checked){
this.checked = checked;
}
#Override
public String toString() {
return this.name;
}
}
Adapter Class
public class FullUserAdapter extends ArrayAdapter<FullUser> {
private ArrayList<FullUser> originalList;
private ArrayList<FullUser> fullUsers;
private SubjectFilter filter;
public FullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
super(context, resource, fullUsers);
this.fullUsers = new ArrayList<FullUser>();
this.fullUsers.addAll(fullUsers);
this.originalList = new ArrayList<FullUser>();
this.originalList.addAll(fullUsers);
}
#Override
public int getCount() {
return fullUsers.size();
}
#Override
public FullUser getItem(int position) {
return fullUsers.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new SubjectFilter();
}
return filter;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("UserConvertView", String.valueOf(position));
View row;
if (convertView == null) {
row = LayoutInflater.from(getContext()).inflate(R.layout.list_row_with_checkbox, parent, false);
}else{
row = convertView;
}
holder = new ViewHolder();
holder.name_view = (TextView) row.findViewById(R.id.nameText);
holder.firstchar_view = (TextView) row.findViewById(R.id.first_char);
holder.groupid = (TextView) row.findViewById(R.id.rowid);
holder.checkBox =(CheckBox) row.findViewById(R.id.cbBox);
final FullUser group =getItem(position);
holder.groupid.setText(group.getId());
//holder.checkBox.setChecked(checkedHolder[position]);
String communityname_text = group.getName();
holder.name_view.setText(group.getName());
String firstchar = communityname_text.substring(0, 1);
holder.firstchar_view.setText(firstchar);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true)
group.setChecked(true);
else
group.setChecked(false);
}
});
row.setTag(holder);
return row;
}
private class SubjectFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
constraint = constraint.toString().toLowerCase();
ArrayList<FullUser> filteredItems = new ArrayList<FullUser>();
for(int i = 0, l = fullUsers.size(); i < l; i++)
{
FullUser group = fullUsers.get(i);
if(group.toString().toLowerCase().contains(constraint)) {
FullUser grouplistss = new FullUser(group.getName(),group.id,group.getChecked());
filteredItems.add(grouplistss);
}
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,Filter.FilterResults results) {
if(results.count > 0) {
fullUsers = (ArrayList<FullUser>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = fullUsers.size(); i < l; i++)
add(fullUsers.get(i));
} else {
notifyDataSetInvalidated();
}
}
}
private class ViewHolder {
TextView name_view;
TextView firstchar_view;
TextView groupid;
CheckBox checkBox;
}
}
Thanks in advance.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
group.setChecked(true);
int pos = originalList.indexOf(group)
originalList.get(pos).setChecked(true);
fullUsers.get(position).setChecked(true);
}else{
group.setChecked(false);
int pos = originalList.indexOf(group)
originalList.get(pos).setChecked(true);
fullUsers.get(position).setChecked(false);
}
}
update your adapter use SparseBooleanArray
public class FullUserAdapter extends ArrayAdapter<FullUser> {
private ArrayList<FullUser> originalList;
private ArrayList<FullUser> fullUsers;
private SubjectFilter filter;
SparseBooleanArray booleanArray ;
public FullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
super(context, resource, fullUsers);
this.fullUsers = new ArrayList<FullUser>();
this.fullUsers.addAll(fullUsers);
this.originalList = new ArrayList<FullUser>();
this.originalList.addAll(fullUsers);
booleanArray = new SparseBooleanArray();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
.
.
.
final FullUser group =getItem(position);
holder.groupid.setText(group.getId());
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(booleanArray.get(group.getId().hashCode(),false));
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
booleanArray.put(group.getId().hashCode(), isChecked);
}
});
.
.
.
return row;
}
public ArrayList<FullUser> getSelectedItems() {
ArrayList<FullUser> list = new ArrayList<>();
for(FullUser group:fullUsers){
if(booleanArray.get(group.getId().hashCode(), false)){
list.add(group);
}
}
return list;
};
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".dashboard.VoterListActivity">
<ProgressBar
android:id="#+id/reqprogressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
<ListView
android:id="#+id/voter_lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btn_show_me"
android:divider="#null"/>
<Button
android:id="#+id/btn_show_me"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:background="#drawable/n_btn"
android:text="#string/add_family_numbers"
android:visibility="gone"
android:textColor="#ffffff"
android:textSize="20sp" />
</RelativeLayout>
Java Code
public Class Actvity extends AppCompatActivity {
ProgressBar progressBar;
ListView listView;
VoterDao voterDao;
String Token, Userid, Appid, Deviceid;
MenuItem searchview;
VoterListAdapter adapter;
String pid;
VoterDatum friend;
String value;
CheckBox mCheckBox;
Button btn_show_me;
ArrayList<VoterDatum> friends;
ListView1Adapter adapter1;
VoterDatum Model;
StringBuilder stringBuilder;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voter_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.voter_list);
stringBuilder = new StringBuilder();
Token = Util.getStringFromSP(this, "token");
Userid = Util.getStringFromSP(this, "user_id");
Appid = Util.getStringFromSP(this, "app_id");
Deviceid = Util.getStringFromSP(this, "device_id");
initViews();
getVoterData();
btn_show_me.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
if (friends.size() == i) { //do nothing
}
while (friends.size() > i) {
int count = friends.size();
Model = friends.get(i);
if (Model.isChecked()) {
Log.i("ListActivity", "here" + friends.get(i).getCitizenId());
stringBuilder.append("," + friends.get(i).getCitizenId());
name = stringBuilder.toString();
String joinedString = Model.getCitizenId().toString();
Log.d("ls", "" + name);
name = name.substring(1);
Log.d("fs", name);
sendToServer();
}
i++; // rise i
}
}
});
}
private void sendToServer() {
Intent intent = new Intent(VoterListActivity.this, AddFamilyNuberByVoterList.class);
intent.putParcelableArrayListExtra("CheckedList", friends);
startActivity(intent);
finish();
}
private void getVoterData() {
if (Util.isNetworkAvailable(this)) {
progressBar.setVisibility(View.VISIBLE);
SendRequestToServer();
} else {
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_connection, Snackbar.LENGTH_SHORT).show();
return;
}
}
private void SendRequestToServer() {
try {
RegistrationApi api = ServiceGenerator.createService(RegistrationApi.class);
retrofit2.Call<VoterDao> call = api.togetVoters(Userid, Token, Appid, Deviceid);
call.enqueue(new Callback<VoterDao>() {
#Override
public void onResponse(Call<VoterDao> call, Response<VoterDao> response) {
if (response.isSuccessful()) {
voterDao = response.body();
if (voterDao.getAddData().getStatus().equals(1)) {
searchview.setVisible(true);
progressBar.setVisibility(View.GONE);
friends = (ArrayList<VoterDatum>) voterDao.getAddData().getData();
adapter1 = new ListView1Adapter(getApplicationContext(), R.layout.list_voter, friends);
listView.setAdapter(adapter1);
btn_show_me.setVisibility(View.VISIBLE);
} else {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_data_found, Snackbar.LENGTH_SHORT).show();
}
} else {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_data_found + response.message(), Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<VoterDao> call, Throwable t) {
try {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, "" + t.getMessage(), Snackbar.LENGTH_SHORT).show();
Log.d("message", "" + t.getMessage());
System.out.println("onFAilureExecute" + t.getMessage());
if (t != null)
t.printStackTrace();
} catch (Throwable th) {
th.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void initViews() {
progressBar = findViewById(R.id.reqprogressbar);
listView = findViewById(R.id.voter_lv);
btn_show_me = findViewById(R.id.btn_show_me);
}
#Override
public boolean onSupportNavigateUp() {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
return true;
}
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
searchview = menu.findItem(R.id.action_search);
final SearchView searchViewAndroidActionBar = (SearchView) MenuItemCompat.getActionView(searchview);
searchViewAndroidActionBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter1.getFilter().filter(newText);
return false;
}
});
View closeButton = searchViewAndroidActionBar.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click
searchViewAndroidActionBar.setIconified(true);
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocalHelper.onAttach(base));
}
private class ListView1Adapter extends BaseAdapter {
ListView1Adapter.ViewHolder holder;
private Context activity;
private ArrayList<VoterDatum> Friends;
private ArrayList<VoterDatum> mList;
private final String TAG = ListViewAdapter.class.getSimpleName();
boolean[] checkedItems;
public ListView1Adapter(Context applicationContext, int list_voter, ArrayList<VoterDatum> list) {
this.activity = applicationContext;
this.Friends = list;
this.mList = list;
Log.i(TAG, "init adapter");
checkedItems = new boolean[mList.size()];
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
holder = null;
final int pos = position;
// inflate layout from xml
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.list_voter, parent, false);
// get all UI view
holder = new ListView1Adapter.ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ListView1Adapter.ViewHolder) convertView.getTag();
}
friend = mList.get(position);
String nameS = friend.getFirstname() + " " + friend.getLastname();
String namesS = friend.getVoterId();
String lname = friend.getLfname() + " " + friend.getLlastname();
//set Friend data to views
String Photo = friend.getPhoto();
if (Photo.isEmpty() || Photo == null) {
holder.image.setImageResource(R.mipmap.ic_launcher);
} else {
Picasso.with(activity).load(Photo).transform(new CircleTransform()).into(holder.image);
}
holder.name.setText(nameS);
holder.lanname.setText(lname);
holder.voterid_tv.setText(namesS);
holder.check.setChecked(friend.isChecked());
holder.check.setTag(friend);
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
VoterDatum itemobj = (VoterDatum) cb.getTag();
if (mList.get(Integer.valueOf(pos)).isChecked()) {
cb.setSelected(false);
mList.get(Integer.valueOf(pos)).setIsChecked(false);
notifyDataSetChanged();
} else {
cb.setSelected(true);
mList.get(Integer.valueOf(pos)).setIsChecked(true);
notifyDataSetChanged();
}
}
});
return convertView;
}
private class ViewHolder {
private ImageView image;
private TextView name, lanname, voterid_tv;
private CheckBox check;
public ViewHolder(View v) {
image = v.findViewById(R.id.profile_iv);
name = (TextView) v.findViewById(R.id.name_tv);
lanname = (TextView) v.findViewById(R.id.desig_tv);
voterid_tv = (TextView) v.findViewById(R.id.voterid_tv);
check = (CheckBox) v.findViewById(R.id.chkEnable);
}
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<VoterDatum> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = Friends;
} else {
filteredResults = (ArrayList<VoterDatum>) getFilteredResults(constraint.toString().toLowerCase());
}
results.values = filteredResults;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
mList = (ArrayList<VoterDatum>) results.values;
notifyDataSetChanged();
}
};
}
protected List<VoterDatum> getFilteredResults(String s) {
ArrayList<VoterDatum> results = new ArrayList<>();
for (VoterDatum item : Friends) {
String TotalSearch = item.getFirstname() + " " + item.getLastname();
if (TotalSearch.toLowerCase().contains(s) || item.getVoterId().toLowerCase().contains(s)) {
results.add(item);
}
}
return results;
}
public ArrayList<VoterDatum> getAllData() {
return mList;
}
}
}
Model Class
public class VoterDatum implements Parcelable {
#SerializedName("citizen_id")
#Expose
private String citizenId;
private boolean isChecked;
public static final Parcelable.Creator<VoterDatum> CREATOR = new Parcelable.Creator<VoterDatum>() {
public VoterDatum createFromParcel(Parcel in) {
return new VoterDatum(in);
}
public VoterDatum[] newArray(int size) {
return new VoterDatum[size];
}
};
public VoterDatum(Parcel in) {
this.citizenId = in.readString();
this.isChecked = in.readByte() != 0;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.citizenId);
dest.writeByte((byte) (this.isChecked ? 1 : 0));
}
public VoterDatum(String citizenId, boolean gender) {
this.citizenId = citizenId;
this.isChecked = false; // not selected when create
}
#SerializedName("status")
#Expose
private String status;
#SerializedName("firstname")
#Expose
private String firstname;
#SerializedName("lastname")
public boolean isChecked() {
return isChecked;
}
public void setIsChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCitizenId() {
return citizenId;
}
public void setCitizenId(String citizenId) {
this.citizenId = citizenId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLfname() {
return lfname;
}
public void setLfname(String lfname) {
this.lfname = lfname;
}
}
Get Data From Other Class
public class ACtivity extends AppCompatActivity implements View.OnClickListener {
String Mvoterid;
GPSTracker gps;
String Token, Userid, Deviceid, Appid, Language;
Button submit_btn;
ProgressBar progressBar;
AddFamilynumberbyvoterDao addFamilynumberbyvoterDao;
// ArrayList<VoterDatum> checkedList;
List<VoterDatum> checkedList;
LinearLayout container;
VoterDatum Model;
ListView list_item;
String join;
int position;
String userName;
String name;
StringBuilder stringBuilder;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_family_nuber_by_voter_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.add_family_numbers);
VoterID = getIntent().getStringExtra("voterIDs");
stringBuilder= new StringBuilder();
checkedList = new ArrayList<VoterDatum>(); // initializing list
container = (LinearLayout) findViewById(R.id.layout);
getLocation();
initViews();
initListeners();
getDataFromIntent();
generateDataToContainerLayout();
}
#RequiresApi(api = Build.VERSION_CODES.O)
#SuppressLint("InflateParams")
private void generateDataToContainerLayout() {
int i = 0;
if (checkedList.size() == i) { //do nothing
}
while (checkedList.size() > i) {
int count = checkedList.size();
Model = checkedList.get(i);
if (Model.isChecked()) {
Log.i("ListActivity", "here" + checkedList.get(i).getCitizenId());
stringBuilder.append(","+checkedList.get(i).getCitizenId());
name=stringBuilder.toString();
String joinedString = Model.getCitizenId().toString();
Log.d("ls", "" + name);
name=name.substring(1);
Log.d("fs",name);
}
i++; // rise i
}
}
private void getDataFromIntent() {
checkedList = getIntent().getParcelableArrayListExtra("CheckedList");
}

Struggling to get data from a rss file into an array list in android

I am creating a app that requires information that is in an rss file (will eventually be an actual feed but it doesn't exist yet) to be put into a recycler view, with each separate card showing only a snippet of information and when the user clicks onto the card it opens into another activity to show all the info. However I am not sure how to access the local file as I would an actual live feed. Any help would be much appreciated.
My rss file is in xml format and called dummy_RSS.rss.
I have a class to specify the the strings needed
public class EventViewDetails {
private String title;
private String location;
private String locLat;
private String locLong;
private String date;
private String timeStart;
private String timeFinish;
private String desc;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocLat() {
return locLat;
}
public void setLocLat(String locLat) {
this.locLat = locLat;
}
public String getLocLong() {
return locLong;
}
public void setLocLong(String locLong) {
this.locLong = locLong;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTimeStart() {
return timeStart;
}
public void setTimeStart(String timeStart) {
this.timeStart = timeStart;
}
public String getTimeFinish() {
return timeFinish;
}
public void setTimeFinish(String timeFinish) {
this.timeFinish = timeFinish;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
I have a class to parse the data from the feed into the above strings
public class ParseEventDetails {
private String data;
private ArrayList<EventViewDetails> events;
public ParseEventDetails(String xmlData) {
data = xmlData;
events = new ArrayList<EventViewDetails>();
}
public ArrayList<EventViewDetails> getEvents() {
return events;
}
public boolean process() {
boolean operationStatus = true;
EventViewDetails currentEvent = null;
boolean inEntry = false;
String textValue = "";
XmlPullParserFactory factory = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(this.data));
int type = xpp.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
String tagName = xpp.getName();
if (type == XmlPullParser.START_TAG) {
if (tagName.equalsIgnoreCase("event")) {
inEntry = true;
currentEvent = new EventViewDetails();
}
} else if (type == XmlPullParser.TEXT) {
textValue = xpp.getText();
} else if (type == XmlPullParser.END_TAG) {
if (inEntry) {
if (tagName.equalsIgnoreCase("event")) {
events.add(currentEvent);
inEntry = false;
}
if (tagName.equalsIgnoreCase("title")) {
currentEvent.setTitle(textValue);
} else if (tagName.equalsIgnoreCase("location")) {
currentEvent.setLocation(textValue);
} else if (tagName.equalsIgnoreCase("date")) {
currentEvent.setDate(textValue);
} else if (tagName.equalsIgnoreCase("timestart")) {
currentEvent.setTimeStart(textValue);
} else if (tagName.equalsIgnoreCase("timefinish")) {
currentEvent.setTimeFinish(textValue);
} else if (tagName.equalsIgnoreCase("loclat")) {
currentEvent.setLocLat(textValue);
} else if (tagName.equalsIgnoreCase("loclong")) {
currentEvent.setLocLong(textValue);
} else if (tagName.equalsIgnoreCase("description")) {
currentEvent.setDesc(textValue);
}
}
}
}
type = xpp.next();
} catch (Exception e) {
e.printStackTrace();
operationStatus = false;
}
return operationStatus;
}
}
I have the adapter for the recycler view
public class EventCalenderAdapter extends RecyclerView.Adapter<EventCalenderAdapter.ViewHolder> {
String xmlData;
static class ViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView titleView;
public ViewHolder(CardView card) {
super(card);
cardView = card;
titleView = (TextView) card.findViewById(R.id.text1);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
CardView v = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.event_task, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
final Context context = viewHolder.titleView.getContext();
viewHolder.titleView.setText(xmlData[i]);
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((OnEventView) context).eventView(i);
}
});
}
#Override
public int getItemCount() {
return xmlData.length;
}
}
and I have my fragment
public class EventCalenderFragment extends Fragment {
RecyclerView recyclerView;
EventCalenderAdapter adapter;
public EventCalenderFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new EventCalenderAdapter();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_event_calender, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return v;
}
}
As I have said I'm not sure how to access the local file or where to put the initial access.
you must change access configuration in your phpmyadmin configuration to "allow any" and then the url will be something like that : localhost/your_php_project_name/your_php_file
note that the file your_php_file must return xml data or file

I want to pass hashmap from custom arrayadapter to activity?

I want to pass HashMap or ArrayList Object from Custom ArrayAdapter to activity which fills the ListView.I want to send checked records recordId field.I m new To Android.Any Suggestion Plz
Pass the adapter a reference to the activity. Then provide a method in the activity that the adapter can call.
In adapter:
private MyActivity activity;
public void setActivity(MyActivity activity) {
this.activity = activity;
}
In Activity:
// create adapter
adapter.setActvity(this);
In adapter (when you want to pass parameters back to activity):
activity.setHashMap(mymap);
My CustomAdapter Class::
class SearchResultAdapter extends ArrayAdapter{
Context context;
int layoutResourceId;
private ArrayList<SearchResultModel> results;
public SearchResultAdapter(Context context, int layoutResourceId, ArrayList<SearchResultModel> results) {
super(context, layoutResourceId, results);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.results = results;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
SearchResultHolder holder=null;
if(row == null)
{
LayoutInflater vi = ((Activity)context).getLayoutInflater();
row = vi.inflate(R.layout.listitemrow, null);
holder = new SearchResultHolder();
holder.jobdetails = (TextView)row.findViewById(R.id.jobdetails);
row.setTag(holder);
}
else
{
holder = (SearchResultHolder)row.getTag();
}
SearchResultModel model = results.get(position);
if (model != null)
{
row.setId(Integer.parseInt(model.getjob_id()));
String result=
"<font color=#5D2E8C>"+model.getjob_title()+"</font><br>" +
"<font color=#737373>"+model.getpost_date()+"</font><br>"+model.getuser_name()+"<br>" +
"<font color=#3C5A98>"+model.getsalary()+" Rs (Per Annum)</font><br>"+
"<font color=#97AB40>"+model.getjob_location()+"," +
" "+model.getjob_exp_min()+"-"+model.getjob_exp_max()+" year";
holder.jobdetails.setText(Html.fromHtml(result));
}
return row;
}
class SearchResultHolder
{
TextView jobdetails;
}
}
My ListView in the Main Method That would use the Above ArrayAdapter.
SearchResultAdapter adapter;
ListView lv;
adapter=new SearchResultAdapter(this, R.layout.listitemrow, model);
//Here model is the ArrayList<SearchResultModel>
lv=getListView();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View v,int arg2, long arg3)
{
}
}
My SearchResultModel Class
package com.cws.model;
public class SearchResultModel {
private String job_id,userdetail_id,user_name,subuser_id,
job_title,search_keyword,job_skill,
job_exp_min,job_exp_max,
job_description,salary,
job_location,education,
industry_id,role_id,functional_id,job_type,
desire_candiadate_profile,company_profile,
website,executive_name,address,email,
phone,post_date,is_active;
private String count,counter;//----count=total no of row found
//---counter=now displaying row nos.
private String errorflag;
public void seterrorflag(String errorflag)
{
this.errorflag=errorflag;
}
public String geterrorflag()
{
return this.errorflag;
}
public void setcount(String count)
{
this.count=count;
}
public String getcount()
{
return this.count;
}
public void setcounter(String counter)
{
this.counter=counter;
}
public String getcounter()
{
return this.counter;
}
public void setjob_id(String job_id)
{
this.job_id=job_id;
}
public String getjob_id()
{
return this.job_id;
}
public void setuserdetail_id(String userdetail_id){
this.userdetail_id=userdetail_id;
}
public String getuserdetail_id()
{
return this.userdetail_id;
}
public void setuser_name(String user_name){
this.user_name=user_name;
}
public String getuser_name()
{
return this.user_name;
}
public void setsubuser_id(String subuser_id){
this.subuser_id=subuser_id;
}
public String getsubuser_id()
{
return this.subuser_id;
}
public void setjob_title(String job_title){
this.job_title=job_title;
}
public String getjob_title()
{
return this.job_title;
}
public void setsearch_keyword(String search_keyword){
this.search_keyword=search_keyword;
}
public String getsearch_keyword()
{
return this.search_keyword;
}
public void setjob_skill(String job_skill){
this.job_skill=job_skill;
}
public String getjob_skill()
{
return this.job_skill;
}
public void setjob_exp_min(String job_exp_min){
this.job_exp_min=job_exp_min;
}
public String getjob_exp_min()
{
return this.job_exp_min;
}
public void setjob_exp_max(String job_exp_max){
this.job_exp_max=job_exp_max;
}
public String getjob_exp_max()
{
return this.job_exp_max;
}
public void setjob_description(String job_description){
this.job_description=job_description;
}
public String getjob_description()
{
return this.job_description;
}
public void setsalary(String salary){
this.salary=salary;
}
public String getsalary()
{
return this.salary;
}
public void setjob_location(String job_location){
this.job_location=job_location;
}
public String getjob_location()
{
return this.job_location;
}
public void seteducation(String education){
this.education=education;
}
public String geteducation()
{
return this.education;
}
public void setindustry_id(String industry_id){
this.industry_id=industry_id;
}
public String getindustry_id()
{
return this.industry_id;
}
public void setrole_id(String role_id){
this.role_id=role_id;
}
public String getrole_id()
{
return this.role_id;
}
public void setfunctional_id(String functional_id){
this.functional_id=functional_id;
}
public String getfunctional_id()
{
return this.functional_id;
}
public void setjob_type(String job_type){
this.job_type=job_type;
}
public String getjob_type()
{
return this.job_type;
}
public void setdesire_candiadate_profile(String desire_candiadate_profile){
this.desire_candiadate_profile=desire_candiadate_profile;
}
public String getdesire_candiadate_profile()
{
return this.desire_candiadate_profile;
}
public void setcompany_profile(String company_profile){
this.company_profile=company_profile;
}
public String getcompany_profile()
{
return this.company_profile;
}
public void setwebsite(String website){
this.website=website;
}
public String getwebsite()
{
return this.website;
}
public void setexecutive_name(String executive_name){
this.executive_name=executive_name;
}
public String getexecutive_name()
{
return this.executive_name;
}
public void setaddress(String address){
this.address=address;
}
public String getaddress()
{
return this.address;
}
public void setemail(String email){
this.email=email;
}
public String getemail()
{
return this.email;
}
public void setphone(String phone){
this.phone=phone;
}
public String getphone()
{
return this.phone;
}
public void setpost_date(String post_date){
this.post_date=post_date;
}
public String getpost_date()
{
return this.post_date;
}
public void setis_active(String is_active){
this.is_active=is_active;
}
public String getis_active()
{
return this.is_active;
}
}

Categories

Resources