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;
}
}
Related
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;
I'm updating the database to other classes and I want the custom listview to be updated when I get to the main activity. My customListview is still standing
I have searched for this problem, but I could not solve it myself. Where should I add the code to solve this problem? Please help me 3 days did not solve my problem.
public class MainActivity extends AppCompatActivity {
veritabani vtabani; //database
List<Yukleclas> yuklele =new ArrayList<Yukleclas>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vtabani=new veritabani(this);
OzelAdaptor adaptor=new OzelAdaptor(this,yuklele);
ListView listView=(ListView) findViewById(R.id.listview);
String[] sutunlar =
{"id","bilgi","simdikiyil","simdikiay","simdikigun","alarmsaat",
"alarmdakika","gsonrayil","gsonraay","gsonragun","hsonrayil","hsonraay",
"hsonragun","asonrayil","asonraay","asonragun","seviye","durum"};
SQLiteDatabase dboku =vtabani.getReadableDatabase();
Cursorcursor=dboku.query("tablo_adi",sutunlar,null,null,null,null,null);
while (cursor.moveToNext()) {
if (cursor.getInt(17)==1) {
yuklele.add(new Yukleclas(cursor.getString(1), cursor.getInt(2),
cursor.getInt(3), cursor.getInt(4),
cursor.getInt(7),cursor.getInt(8),cursor.getInt(9),cursor.getInt(10),
cursor.getInt(11),cursor.getInt(12),cursor.getInt(13),cursor.getInt(14),
cursor.getInt(15),cursor.getInt(16)));
}
}
cursor.close();
dboku.close();
listView.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
}
public void ekleyegit(View view) {
Intent intent =new Intent(this,ekleactivity.class);
startActivity(intent);
finish();
}}
and this is myAdapter:
public class OzelAdaptor extends BaseAdapter {
LayoutInflater layoutInflater;
List<Yukleclas> list;
public OzelAdaptor(Activity activity,List<Yukleclas> mList){
layoutInflater= (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
list=mList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View satirView;
satirView=layoutInflater.inflate(R.layout.satir,null);
TextView tv_tarih = (TextView) satirView.findViewById(R.id.text_tarih);
TextView tv_bilgi= (TextView) satirView.findViewById(R.id.text_bilgi);
ImageView imageView= (ImageView) satirView.findViewById(R.id.imageView);
Yukleclas yukleclas =list.get(position);
tv_bilgi.setText(yukleclas.getBilgi());
if(yukleclas.getSeviye()==1){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGun() +"/" +yukleclas.getAy() + "/" +yukleclas.getYil() );
}else if(yukleclas.getSeviye()==2){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGsgun() +"/" +yukleclas.getGsay() + "/" +yukleclas.getGsyil() );
}else if (yukleclas.getSeviye()==3){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getHsgun() +"/" +yukleclas.getHsay() + "/" +yukleclas.getHsyil() );
}else if (yukleclas.getSeviye()==4){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getAsgun() +"/" +yukleclas.getAsay() + "/" +yukleclas.getAsyil() );
}
if(yukleclas.getSeviye()==1){
imageView.setImageResource(bir); // eğer 1. seviyede ise bir isimli ikonu göster
}else if(yukleclas.getSeviye()==2){
imageView.setImageResource(iki);
}else if(yukleclas.getSeviye()==3){
imageView.setImageResource(uc);
}else if(yukleclas.getSeviye()==4){
imageView.setImageResource(ic_launcher);
}
return satirView;
}
}
and this is my class to get-set:
public class Yukleclas {
private String bilgi;
private int yil;
private int ay;
private int gun;
private int seviye;
private int gsyil;
private int gsay;
private int gsgun;
private int hsyil;
private int hsay;
private int hsgun;
private int asyil;
private int asay;
private int asgun;
public Yukleclas(String mBilgi,int mYil,int mAy,int mGun,int mGsyil,int
mGsay,int mGsgun,int mHsyil,int mHsay,int mHsgun,int mAsyil,int mAsay,int
mAsgun,int mSeviye){
yil=mYil;
bilgi=mBilgi;
ay=mAy;
gun=mGun;
gsyil=mGsyil;
gsay=mGsay;
gsgun=mGsgun;
hsyil=mHsyil;
hsay=mHsay;
hsgun=mHsgun;
asyil=mAsyil;
asay=mAsay;
asgun=mAsgun;
seviye=mSeviye;
}
public int getYil() {
return yil;
}
public void setYil(int yil) {
this.yil = yil;
}
public int getSeviye() {
return seviye;
}
public void setSeviye(int yil) {
this.seviye = seviye;
}
public String getBilgi() {
return bilgi;
}
public void setBilgi(String bilgi) {
this.bilgi = bilgi;
}
public int getAy() {
return ay;
}
public void setAy(int ay) {
this.ay = ay;
}
public int getGun() {
return gun;
}
public void setGun(int gun) {
this.gun = gun;
}
public int getGsyil() {return gsyil;
}
public void setGsyil(int gsyil) {this.gsyil = gsyil;
}
public int getGsay() {return gsay;
}
public void setGsay(int gsay) {this.gsay = gsay;
}
public int getGsgun() {return gsgun;
}
public void setGsgun(int gsgun) {this.gsgun = gsgun;
}
public int getHsyil() {return hsyil;
}
public void setHsyil(int hsyil) {this.hsyil = hsyil;
}
public int getHsay() {return hsay;
}
public void setHsay(int hsay) {this.hsay = hsay;
}
public int getHsgun() {return hsgun;
}
public void setHsgun(int hsgun) {this.hsgun = hsgun;
}
public int getAsyil() {return asyil;
}
public void setAsyil(int asyil) {this.asyil = asyil;
}
public int getAsay() {return asay;
}
public void setAsay(int asay) {this.asay = asay;
}
public int getAsgun() {return asgun;
}
public void setAsgun(int asgun) {this.asgun = asgun;
}
}
I know it is very complex but How to replace my customlistview ?
Easy way is to call adapter.notifyDataSetChanged() in your onResume function.
But I would suggest you check if your list has been updated then only you call adapter.notifyDataSetChanged(). You can do this in multiple ways, but for a cleaner approach use EventBus which allows you to fire events and listen to them, So you can fire an event every time you update your dataBaseand on listening to this event, simply call adapter.notifyDataSetChanged
Hi Im trying to show a list from retrofit onResponse and I am using recyclerview inside a fragment. The list shoud show chefs but I got an error from RecyclerView
Conexion Class
public class Conexion {
public static String BASE_URL = "http://10.30.0.133:8091/Service1.asmx/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
EndPoint Interface
public interface EndPointsInterface {
#GET("chef/{idUser}")
Call<ChefResponse> GetChefsCercanos(#Path("idUser") Integer id_usuario);
}
Entity Usuario
public class Usuario {
#SerializedName("id_usuario")
private Integer id_usuario;
#SerializedName("NombreUsuario")
private String NombreUsuario;
#SerializedName("ApellidoUsuario")
private String ApellidoUsuario;
#SerializedName("TelefonoUsuario")
private String TelefonoUsuario;
#SerializedName("Email")
private String Email;
#SerializedName("Contraseña")
private String Contraseña;
#SerializedName("pos_x")
private Double pos_x;
#SerializedName("pos_y")
private Double pos_y;
public Usuario(){}
public Usuario(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y){
this.id_usuario=id_usuario;
this.NombreUsuario=NombreUsuario;
this.ApellidoUsuario=ApellidoUsuario;
this.TelefonoUsuario=TelefonoUsuario;
this.Contraseña=Contraseña;
this.pos_x=pos_x;
this.pos_y=pos_y;
}
public Integer getId_usuario() {
return id_usuario;
}
public void setId_usuario(Integer id_usuario) {
this.id_usuario = id_usuario;
}
public String getNombreUsuario() {
return NombreUsuario;
}
public void setNombreUsuario(String nombreUsuario) {
NombreUsuario = nombreUsuario;
}
public String getApellidoUsuario() {
return ApellidoUsuario;
}
public void setApellidoUsuario(String apellidoUsuario) {
ApellidoUsuario = apellidoUsuario;
}
public String getTelefonoUsuario() {
return TelefonoUsuario;
}
public void setTelefonoUsuario(String telefonoUsuario) {
TelefonoUsuario = telefonoUsuario;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getContraseña() {
return Contraseña;
}
public void setContraseña(String contraseña) {
Contraseña = contraseña;
}
public Double getPos_x() {
return pos_x;
}
public void setPos_x(Double pos_x) {
this.pos_x = pos_x;
}
public Double getPos_y() {
return pos_y;
}
public void setPos_y(Double pos_y) {
this.pos_y = pos_y;
}
}
Entity Chef
public class Chef extends Usuario{
#SerializedName("id_chef")
private Integer id_chef;
#SerializedName("TipoServicio")
private String TipoServicio;
#SerializedName("Rating")
private Double Rating;
#SerializedName("EstadoChef")
private Boolean EstadoChef;
public Chef(){}
public Chef(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y,Integer id_chef,String TipoServicio,Double Rating,Boolean EstadoChef){
super(id_usuario,NombreUsuario,ApellidoUsuario,TelefonoUsuario,Email,Contraseña,pos_x,pos_y);
this.id_chef=id_chef;
this.TipoServicio=TipoServicio;
this.Rating=Rating;
this.EstadoChef=EstadoChef;
}
public Integer getId_chef() {
return id_chef;
}
public void setId_chef(Integer id_chef) {
this.id_chef = id_chef;
}
public String getTipoServicio() {
return TipoServicio;
}
public void setTipoServicio(String tipoServicio) {
TipoServicio = tipoServicio;
}
public Double getRating() {
return Rating;
}
public void setRating(Double rating) {
Rating = rating;
}
public Boolean getEstadoChef() {
return EstadoChef;
}
public void setEstadoChef(Boolean estadoChef) {
EstadoChef = estadoChef;
}
}
Chef Response
public class ChefResponse {
#SerializedName("results")
private Chef[] results;
public Chef[] getresults(){
return results;
}
}
RecyclerView Adapter
public class ListaChefsCercanos extends RecyclerView.Adapter<ListaChefsCercanos.ListaChefsCercanosViewHolder> {
private List<Chef> chefs;
private List<Usuario> usuarios;
private int rowLayout;
private Context context;
#Override
public ListaChefsCercanosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ListaChefsCercanosViewHolder(view);
}
#Override
public void onBindViewHolder(ListaChefsCercanosViewHolder holder, int position) {
holder.nombreschefscerca.setText(chefs.get(position).getNombreUsuario());
holder.ratingchef.setText(chefs.get(position).getRating().toString());
}
#Override
public int getItemCount() {
return chefs.size();
}
public static class ListaChefsCercanosViewHolder extends RecyclerView.ViewHolder{
LinearLayout chefslayout;
TextView nombreschefscerca;
TextView ratingchef;
public ListaChefsCercanosViewHolder(View v){
super(v);
chefslayout=(LinearLayout) v.findViewById(R.id.cheflayoutcerca);
nombreschefscerca=(TextView) v.findViewById(R.id.tv_NombreChefCercano);
ratingchef=(TextView) v.findViewById(R.id.tv_RatingChefCercano);
}
}
public ListaChefsCercanos(ArrayList <Chef> chefs){
this.chefs=chefs;
//this.rowLayout = rowLayout;
//this.context = context;
}
}
and the fragment
public class RecomendadosFragment extends Fragment {
private RatingBar ratingBar;
//ListAdapter adapter;
ArrayList<Chef> listachef;
ListView lvLista;
String tag_json_array="jarray req";
RecyclerView recyclerviewChefsCarnos;
ListaChefsCercanos mListaChefsCercanos;
private ArrayList<Chef> data;
private ListaChefsCercanos adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.recomendados,null);
//ratingBar = (RatingBar) x.findViewById(R.id.rb_RatingChefCercano);
recyclerviewChefsCarnos=(RecyclerView) x.findViewById(R.id.rv_chefsCernaos);
recyclerviewChefsCarnos.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
EndPointsInterface apiService = Conexion.getClient().create(EndPointsInterface.class);
Call<ChefResponse> call = apiService.GetChefsCercanos(5);
call.enqueue(new Callback<ChefResponse>() {
#Override
public void onResponse(Call<ChefResponse> call, Response<ChefResponse> response) {
int statusCode = response.code();
if (response.isSuccessful()) {
ChefResponse jsonResponse = response.body();
if(jsonResponse != null) {
data = new ArrayList<>(Arrays.asList(jsonResponse.getresults()));
adapter= new ListaChefsCercanos(data);
recyclerviewChefsCarnos.setAdapter(adapter);
}
} else {
// Do whatever you want if API is unsuccessful.
}
// List<Chef> chefs= response.body().getResults();
// recyclerviewChefsCarnos.setAdapter(new ListaChefsCercanos( chefs,R.layout.itemchefscercanos,getActivity().getApplicationContext()));
}
#Override
public void onFailure(Call<ChefResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
return x;
}
this is the error I found while Im debuging
E/RecyclerView: No adapter attached; skipping layout
Update: Use a empty adapter for the RecyclerView in the OncreateView()
recyclerView.setAdapter(new YourAdapter(getCurrentActivity()));
1- MainActivity:
public class MainActivity extends AppCompatActivity {
private List<String> mListItems = Arrays.asList("Hamaki","Amr Diab");
private ArtistsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.Artist_list_view);
mAdapter = new ArtistsAdapter(this, mListItems);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,SoundActivity.class);
intent.putExtra("Artist", mListItems.get(position));
startActivity(intent);
}
});
}
}
2-Sound Activity:
public class SoundActivity extends AppCompatActivity {
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new SoundFragment()).commit();
}
}
3-Sound Fragment:
public class SoundFragment extends Fragment {
static SCTrackAdapter mAdapter;
static DatabaseReference db;
static FirebaseHelper helper;
private TextView mSelectedTrackTitle;
static ArrayList<Music> mTracks = new ArrayList<>();
static MediaPlayer mMediaPlayer;
private ImageView mPlayerControl;
static String Artist;
static ListView listView;
int currentTrack;
private static String fileName;
public SoundFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
new Fetchtracks().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sound, container, false);
Intent intent = getActivity().getIntent();
if (intent != null) {
Artist = intent.getStringExtra("Artist");
}
listView = (ListView) rootView.findViewById(R.id.track_list_view);
mAdapter = new SCTrackAdapter(getActivity(), mTracks);
listView.setAdapter(mAdapter);
return rootView;
}
4- STrack Adapter:
public class SCTrackAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Music> mTracks;
public SCTrackAdapter(Context context, ArrayList<Music> tracks) {
mContext = context;
mTracks = tracks;
}
public void update_tracks(ArrayList<Music> list)
{
mTracks.clear();
mTracks.addAll(list);
}
#Override
public int getCount() {
return mTracks.size();
}
#Override
public Music getItem(int position) {
return mTracks.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.track_list_row, parent, false);
holder = new ViewHolder();
holder.titleTextView = (TextView) convertView.findViewById(R.id.track_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleTextView.setText(mTracks.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView titleTextView;
}
}
5- Fetchtracks:
public class Fetchtracks extends AsyncTask<Void, Void, ArrayList<Music>> {
#Override
protected ArrayList<Music> doInBackground(Void... voids) {
db = FirebaseDatabase.getInstance().getReference().child(Artist);
helper = new FirebaseHelper(db);
mTracks.addAll(helper.retrieve());
Log.e("doInBackground: ",helper.retrieve()+"");
return mTracks;
}
#Override
protected void onPostExecute(ArrayList<Music> list) {
super.onPostExecute(list);
Log.e("doInBackground: ",list.size()+"");
mAdapter.update_tracks(list);
mAdapter.notifyDataSetChanged();
}
}
6- FirebaseHelper:
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
ArrayList<Music> A = new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//WRITE
public Boolean save(Music m)
{
if(m==null)
{
saved=false;
}else
{
try
{
// db.child(Artist).push().setValue(m);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<Music> retrieve()
{
A.clear();
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "1");
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "2");
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// Log.e("onChildAdded: ", "3");
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
// Log.e("onChildAdded: ", "4");
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e("onChildAdded: ", "5");
}
});
return A;
}
private void fetchData(DataSnapshot dataSnapshot)
{
Music m=new Music();
m.setName(dataSnapshot.child("name").getValue().toString());
m.setUrl(dataSnapshot.child("url").getValue().toString());
A.add(m);
// SoundFragment.mTracks.add(m);
// Log.e("onFetch: ", SoundFragment.mTracks.size()+"");
}
}
7- Music:
public class Music {
String name;
String url;
public Music() {
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public String getURL() {
return url;
}
}
no need to call this in onPostExecute() as it is only set
listView.setAdapter(mAdapter);
I am using tabs which consist of fragment that has an arraylist of objects. I want to store my arraylist
list<Model_BarcodeDetail>
onStop() ie., I want to store my list that is present in my current tab when I navigate to another tab. I did the following code but it is giving me exception when I'm trying to save my list.
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
System.out.println("=====pause");
saveDatas();
}
public void saveDatas() {
Log.d("msg", "Save Instance");
SharedPreferences.Editor outState = getActivity().getSharedPreferences(
"order", Context.MODE_APPEND).edit();
text = editText_barcode.getText().toString();
itemQuantity = editText_quantity.getText().toString();
outState.putString("saved", "true");
outState.putString("text", text);
outState.putString("title", job_name);
outState.putString("area", selected_area);
outState.putString("location", selected_loc);
outState.putString("quantity", itemQuantity);
//String strObject = gson.toJson(list, Model_BarcodeDetail.class);
//outState.putString("MyList", strObject);
POJO mPojo = new POJO();
mPojo.setData(list);
String strObject = gson.toJson(mPojo, POJO.class);
outState.putString("MyList", strObject);
outState.commit();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Bundle extras = getArguments();
/***** PUT DATA IN EDITTEXT if ITS AVAILABLE IN BUNDLE *****/
System.out.println("===jobname:"+job_name);
SharedPreferences orderData = getActivity().getSharedPreferences(
"order", Context.MODE_APPEND);
if (orderData != null) {
String a = orderData.getString("saved", "");
if (a != null && a.equalsIgnoreCase("true")) {
text = orderData.getString("text", "");
System.out.println("====tetx:" + text);
String title = orderData.getString("title", "");
System.out.println("===title: "+title+"===jobname: "+job_name);
if (title.equalsIgnoreCase(job_name)) {
editText_barcode.setText(text);
selected_area = orderData.getString("area", "");
selected_loc = orderData.getString("location", "");
itemQuantity = orderData.getString("quantity", "");
editText_quantity.setText(itemQuantity);
String json = orderData.getString("MyList", "");
List<Model_BarcodeDetail> list = gson.fromJson(json,
listOfObjects);
}
}
}
}
I'm getting the following exception when I add another tab:
12-09 12:08:28.072: E/AndroidRuntime(28616): FATAL EXCEPTION: main
12-09 12:08:28.072: E/AndroidRuntime(28616): Process: com.example.pdt, PID:
28616
12-09 12:08:28.072: E/AndroidRuntime(28616): java.lang.NullPointerException
12-09 12:08:28.072: E/AndroidRuntime(28616): at
com.example.pdt.Fragment_Main.saveDatas(Fragment_Main.java:446)
12-09 12:08:28.072: E/AndroidRuntime(28616): at
com.example.pdt.Fragment_Main.onPause(Fragment_Main.java:426)
12-09 12:08:28.072: E/AndroidRuntime(28616): at
android.support.v4.app.Fragment.performPause(Fragment.java:1950)
12-09 12:08:28.072: E/AndroidRuntime(28616): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1005)
12-09 12:08:28.072: E/AndroidRuntime(28616): at
android.support.v4.app.FragmentManagerImpl.removeFragment(FragmentManager.java:1235)
EDIT:
Model_BarcodeDetail class:
package com.example.model;
public class Model_BarcodeDetail {
public String datetime, success, name, reference, description, price,
color, size, stock, branch, supplier, location, basesell, vat,
avg_cost, last_cost, next_cost, group_code, type, remarks1,
remarks2, listed_days, title, meta_keywords, meta_description,
job_id, total, fixedTotal, fixedPrice, aliascode, draftName,
itemBarcode, totalDiscount;
boolean priceEdited;
public boolean isPriceEdited() {
return priceEdited;
}
public void setPriceEdited(boolean priceEdited) {
this.priceEdited = priceEdited;
}
private String string_sale_return;
public String barcode, quantity = "0", area, batch;
private boolean scanned, isEdited;
public String getTotalDiscount() {
return totalDiscount;
}
public void setTotalDiscount(String totalDiscount) {
this.totalDiscount = totalDiscount;
}
public String getItemBarcode() {
return itemBarcode;
}
public void setItemBarcode(String itemBarcode) {
this.itemBarcode = itemBarcode;
}
public String getDraftName() {
return draftName;
}
public void setDraftName(String draftName) {
this.draftName = draftName;
}
public String getAliascode() {
return aliascode;
}
public void setAliascode(String aliascode) {
this.aliascode = aliascode;
}
public String getString_sale_return() {
return string_sale_return;
}
public void setString_sale_return(String string_sale_return) {
this.string_sale_return = string_sale_return;
}
public boolean isScanned() {
return scanned;
}
public void setScanned(boolean scanned) {
this.scanned = scanned;
}
public String getJob_id() {
return job_id;
}
public void setJob_id(String job_id) {
this.job_id = job_id;
}
public String getBatch() {
return batch;
}
public void setBatch(String batch) {
this.batch = batch;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getStock() {
return stock;
}
public void setStock(String stock) {
this.stock = stock;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBasesell() {
return basesell;
}
public void setBasesell(String basesell) {
this.basesell = basesell;
}
public String getVat() {
return vat;
}
public void setVat(String vat) {
this.vat = vat;
}
public String getAvg_cost() {
return avg_cost;
}
public void setAvg_cost(String avg_cost) {
this.avg_cost = avg_cost;
}
public String getLast_cost() {
return last_cost;
}
public void setLast_cost(String last_cost) {
this.last_cost = last_cost;
}
public String getNext_cost() {
return next_cost;
}
public void setNext_cost(String next_cost) {
this.next_cost = next_cost;
}
public String getGroup_code() {
return group_code;
}
public void setGroup_code(String group_code) {
this.group_code = group_code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRemarks1() {
return remarks1;
}
public void setRemarks1(String remarks1) {
this.remarks1 = remarks1;
}
public String getRemarks2() {
return remarks2;
}
public void setRemarks2(String remarks2) {
this.remarks2 = remarks2;
}
public String getListed_days() {
return listed_days;
}
public void setListed_days(String listed_days) {
this.listed_days = listed_days;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMeta_keywords() {
return meta_keywords;
}
public void setMeta_keywords(String meta_keywords) {
this.meta_keywords = meta_keywords;
}
public String getMeta_description() {
return meta_description;
}
public void setMeta_description(String meta_description) {
this.meta_description = meta_description;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public boolean isEdited() {
return isEdited;
}
public void setEdited(boolean isEdited) {
this.isEdited = isEdited;
}
public String getFixedTotal() {
return fixedTotal;
}
public void setFixedTotal(String fixedTotal) {
this.fixedTotal = fixedTotal;
}
public String getFixedPrice() {
return fixedPrice;
}
public void setFixedPrice(String fixedPrice) {
this.fixedPrice = fixedPrice;
}
}
POJO class:
package com.example.model;
import java.util.List;
public class Pojo {
List<Model_BarcodeDetail> data;
public List<Model_BarcodeDetail> getData() {
return data;
}
public void setData(List<Model_BarcodeDetail> data) {
this.data = data;
}
}
You need to store your list in the model class like this
public class POJO {
List<Model_BarcodeDetail> data;
public List<Model_BarcodeDetail> getData() {
return data;
}
public void setData(List<Model_BarcodeDetail> data) {
this.data = data;
}
}
now when you have data in your POJO class
Convert it to json string and store to prefrence like this
String strObject = gson.toJson(list, POJO.class);
outState.putString("MyList", strObject);
Now when you want to get back those data just do like this
String json = orderData.getString("MyList", "");
POJO mPojo = gson.fromJson(json,POJO.class);
now access you List using this object like this
mPojo.getModel_BarcodeList();
Let me know if you still have an issue
You can use TinyDB -- Android-Shared-Preferences-Turbo