RecyclerView:No adapter attached; skipping layou, retrofit [duplicate] - android

This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
Closed 6 years ago.
good evening everyone, Ive been searching for a solution to an error android studio's log is sending using RecyclerView to show a JSON "product" list with retrofit.
I have already read the questions related to this error but im not able to find the right answer to my needs.
Android: RecyclerView: No adapter attached; skipping layout
No adapter attached; skipping layout recyclerview error
recyclerview No adapter attached; skipping layout
No adapter attached; skipping layout onCreateView()
This is de error log showed by android studio
RecyclerView: No adapter attached; skipping layout
RecyclerView: No adapter attached; skipping layout
Surface: getSlotFromBufferLocked: unknown buffer: 0xa3d9a700
OpenGLRenderer: endAllStagingAnimators on 0xa2b6bb00 (RippleDrawable) with handle 0xa200a310
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
For this proyect are been used this Classes and Layout files
"Producto" Class
public class Producto {
#SerializedName("id")
#Expose
private int id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("status")
#Expose
private String status;
#SerializedName("price")
#Expose
private String price;
#SerializedName("regular_price")
#Expose
private String regularPrice;
#SerializedName("sale_price")
#Expose
private String salePrice;
#SerializedName("price_html")
#Expose
private String priceHtml;
#SerializedName("on_sale")
#Expose
private boolean onSale;
#SerializedName("total_sales")
#Expose
private int totalSales;
#SerializedName("purchase_note")
#Expose
private String purchaseNote;
#SerializedName("categories")
#Expose
private List<Category> categories;
#SerializedName("menu_order")
#Expose
private int menuOrder;
/**
*
* #return
* The id
*/
public int getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The status
*/
public String getStatus() {
return status;
}
/**
*
* #param status
* The status
*/
public void setStatus(String status) {
this.status = status;
}
/**
*
* #return
* The price
*/
public String getPrice() {
return price;
}
/**
*
* #param price
* The price
*/
public void setPrice(String price) {
this.price = price;
}
/**
*
* #return
* The regularPrice
*/
public String getRegularPrice() {
return regularPrice;
}
/**
*
* #param regularPrice
* The regular_price
*/
public void setRegularPrice(String regularPrice) {
this.regularPrice = regularPrice;
}
/**
*
* #return
* The salePrice
*/
public String getSalePrice() {
return salePrice;
}
/**
*
* #param salePrice
* The sale_price
*/
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
/**
*
* #return
* The priceHtml
*/
public String getPriceHtml() {
return priceHtml;
}
/**
*
* #param priceHtml
* The price_html
*/
public void setPriceHtml(String priceHtml) {
this.priceHtml = priceHtml;
}
/**
*
* #return
* The onSale
*/
public boolean isOnSale() {
return onSale;
}
/**
*
* #param onSale
* The on_sale
*/
public void setOnSale(boolean onSale) {
this.onSale = onSale;
}
/**
*
* #return
* The totalSales
*/
public int getTotalSales() {
return totalSales;
}
/**
*
* #param totalSales
* The total_sales
*/
public void setTotalSales(int totalSales) {
this.totalSales = totalSales;
}
/**
*
* #return
* The purchaseNote
*/
public String getPurchaseNote() {
return purchaseNote;
}
/**
*
* #param purchaseNote
* The purchase_note
*/
public void setPurchaseNote(String purchaseNote) {
this.purchaseNote = purchaseNote;
}
/**
*
* #return
* The categories
*/
public List<Category> getCategories() {
return categories;
}
/**
*
* #param categories
* The categories
*/
public void setCategories(List<Category> categories) {
this.categories = categories;
}
/**
*
* #return
* The menuOrder
*/
public int getMenuOrder() {
return menuOrder;
}
/**
*
* #param menuOrder
* The menu_order
*/
public void setMenuOrder(int menuOrder) {
this.menuOrder = menuOrder;
}
}
"Category" Class (which matches with the private List<Category> categories; property)
public class Category {
#SerializedName("id")
#Expose
private int id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
/**
*
* #return
* The id
*/
public int getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The slug
*/
public String getSlug() {
return slug;
}
/**
*
* #param slug
* The slug
*/
public void setSlug(String slug) {
this.slug = slug;
}
}
Both Containanied as Arrays in this class called "JSONproducts"
public class JSONproducts {
private Producto[] products;
private Category[] categories;
public Producto[] getProducts(){
return products;
}
public Category[] getCategories(){
return categories;
}
}
Then The Request Interface called "LecturaProductos"
public interface LecturaProductos {
#GET("Products")
Call<JSONproducts> ListarProductos();
}
The data Adapter for the Recycler View called "Adaptador"
public class Adaptador extends RecyclerView.Adapter<Adaptador.ViewHolder> {
private ArrayList<Producto> productos;
private ArrayList<Category> categoria;
public Adaptador(ArrayList<Producto> productos, ArrayList<Category> categoria){
this.productos = productos;
this.categoria = categoria;
}
#Override
public Adaptador.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_view, parent, false );
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(Adaptador.ViewHolder holder, int position) {
holder.nom_pro_tv.setText(productos.get(position).getName());
holder.id_pro_tv.setText(productos.get(position).getId());
holder.cat_pro.setText(categoria.get(position).getName());
}
#Override
public int getItemCount() {
return productos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView nom_pro_tv, id_pro_tv, cat_pro;
public ViewHolder(View itemView) {
super(itemView);
nom_pro_tv = (TextView)itemView.findViewById(R.id.nom_pro_tv);
id_pro_tv = (TextView)itemView.findViewById(R.id.id_pro_tv);
cat_pro = (TextView)itemView.findViewById(R.id.cat_pro_tv);
}
}
}
And the Activity Class "ListaProductos"
public class ListaProductos extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<Producto> product;
private ArrayList<Category> category;
private Adaptador adaptador;
public static final String BASE_URL= "https://mydomain.com.mx/wp-json/wc/v1/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_productos);
showView();
}
private void showView(){
recyclerView = (RecyclerView)findViewById(R.id.prod_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
cargarJSON();
}
private void cargarJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
final LecturaProductos producto = retrofit.create(LecturaProductos.class);
Call<JSONproducts> productoCall = producto.ListarProductos();
productoCall.enqueue(new Callback<JSONproducts>() {
#Override
public void onResponse(Call<JSONproducts> call, Response<JSONproducts> response) {
JSONproducts jsonproducts = response.body();
product = new ArrayList<>(Arrays.asList(jsonproducts.getProducts()));
category = new ArrayList<>(Arrays.asList(jsonproducts.getCategories()));
adaptador = new Adaptador(product, category);
recyclerView.setAdapter(adaptador);
}
#Override
public void onFailure(Call<JSONproducts> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
And the Layout XML files that are been used
RecyclerView Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_lista_productos"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mx.com.corpcap.elrollorepartidor.ListaProductos">
<android.support.v7.widget.RecyclerView
android:id="#+id/prod_recycler_view"
android:layout_height="match_parent"
android:layout_width="match_parent"/></LinearLayout>
CardView Layout for the product list
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/nom_pro_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/id_pro_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/cat_pro_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
Everything complies great and launches the app without an issue but when the information is tried to be accessed it sends the log messages quoted in the beginning of this question.
Thanks a Lot

A RecyclerView is not much use on it's own without an adapter providing the data it must display. So when a RecyclerView is initialized and placed in the layout but .setAdapter has not yet been called, the problem you're experiencing occurs. How about you take an empty list and use that to initialize the adapter and set it to your RecyclerView before you even send the network request. When you make the network request and get a response, simply clear the old values in the list, add new values and notify your adapter that the data in the list has changed. This should avoid the skipping layout problem, Alex.
Something like this:
private ArrayList<YourObjectClass> listOfYourObjects = new ArrayList<>();
.
.
.
SomeAdapter yourAdapter = new SomeAdapter(listOfYourObjects , context);
yourRecyclerView.setAdapter(yourAdapter);
.
.
.
onResponse:
list.clear();
//Let the adapter know the list is empty now
yourAdapter.notifyDataSetChanged();
//Fill in your list with values from server using a for/while loop etc.
//Again notify your adapter that the list has changed:
yourAdapter.notifyDataSetChanged();
Hope that helps.

Related

how to parse this jsonarray using GSON library

This is my jsonarray.
[
{
"id": 3,
"title": "Best Seller",
"promotedProducts": [
{
"product": {
"id": 4208,
"name": "Gents T-Shirt With Navy Blue Collar cuff",
"reviewList": [],
"productDetail": {
"id": 4207,
"length": 33,
"breadth": 27
},
"attributeList": [
{
"id": 1,
"productId": 4208
}
]
}
},
{
"product": {
"id": 4208,
"name": "Gents T-Shirt With Navy Blue Collar cuff",
"reviewList": [],
"productDetail": {
"id": 4207,
"length": 33,
"breadth": 27
},
"attributeList": [
{
"id": 1,
"productId": 4208
}
]
}
}
]
}
]
I had created Homecollection class for it.also added following code for parsing.I had also created subclasses for product,promotedProducts,productDetail,attributeList,images.its give me as reponse of two items but other details are coming empty
Gson gson = new Gson();
HomeProducts homeProducts = HomeProducts.getInstance();
List<HomeCollections> collectionList = new ArrayList<HomeCollections>();
collectionList = Arrays.asList(gson.fromJson(response.toString(), HomeCollections[].class));
Create a Model class like this.
public class ProductDetail
{
public int id { get; set; }
public int length { get; set; }
public int breadth { get; set; }
}
public class AttributeList
{
public int id { get; set; }
public int productId { get; set; }
}
public class Product
{
public int id { get; set; }
public string name { get; set; }
public List<object> reviewList { get; set; }
public ProductDetail productDetail { get; set; }
public List<AttributeList> attributeList { get; set; }
}
public class PromotedProduct
{
public Product product { get; set; }
}
public class HomeCollections
{
public int id { get; set; }
public string title { get; set; }
public List<PromotedProduct> promotedProducts { get; set; }
}
Now use the GSON like this. Here url is the source link.You will get the response as a model. Now
response.promotedProducts will give you all list of items.
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
HomeCollections response = gson.fromJson(reader, HomeCollections.class);
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("org.jsonschema2pojo")
public class AttributeList {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("productId")
#Expose
private Integer productId;
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The productId
*/
public Integer getProductId() {
return productId;
}
/**
*
* #param productId
* The productId
*/
public void setProductId(Integer productId) {
this.productId = productId;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("org.jsonschema2pojo")
public class Example {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("promotedProducts")
#Expose
private List<PromotedProduct> promotedProducts = new ArrayList<PromotedProduct>();
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The promotedProducts
*/
public List<PromotedProduct> getPromotedProducts() {
return promotedProducts;
}
/**
*
* #param promotedProducts
* The promotedProducts
*/
public void setPromotedProducts(List<PromotedProduct> promotedProducts) {
this.promotedProducts = promotedProducts;
}
}
-----------------------------------com.example.Product.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("org.jsonschema2pojo")
public class Product {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("reviewList")
#Expose
private List<Object> reviewList = new ArrayList<Object>();
private ProductDetail productDetail;
private List<AttributeList> attributeList = new ArrayList<AttributeList>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Object> getReviewList() {
return reviewList;
}
public void setReviewList(List<Object> reviewList) {
this.reviewList = reviewList;
}
public ProductDetail getProductDetail() {
return productDetail;
}
public void setProductDetail(ProductDetail productDetail) {
this.productDetail = productDetail;
}
public List<AttributeList> getAttributeList() {
return attributeList;
}
public void setAttributeList(List<AttributeList> attributeList) {
this.attributeList = attributeList;
}
}
-----------------------------------com.example.ProductDetail.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ProductDetail {
private Integer id;
private Integer length;
private Integer breadth;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public Integer getBreadth() {
return breadth;
}
public void setBreadth(Integer breadth) {
this.breadth = breadth;
}
}
-----------------------------------com.example.PromotedProduct.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PromotedProduct {
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
use this classes to get this data
You can use the following website to parse:
jsonschema2pojo
A version would be:
public class PromotedProduct {
#SerializedName("product")
#Expose
private Product product;
/**
*
* #return
* The product
*/
public Product getProduct() {
return product;
}
/**
*
* #param product
* The product
*/
public void setProduct(Product product) {
this.product = product;
}
}
ProductDetail:
public class ProductDetail {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("length")
#Expose
private Integer length;
#SerializedName("breadth")
#Expose
private Integer breadth;
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The length
*/
public Integer getLength() {
return length;
}
/**
*
* #param length
* The length
*/
public void setLength(Integer length) {
this.length = length;
}
/**
*
* #return
* The breadth
*/
public Integer getBreadth() {
return breadth;
}
/**
*
* #param breadth
* The breadth
*/
public void setBreadth(Integer breadth) {
this.breadth = breadth;
}
}
Attributes:
public class AttributeList {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("productId")
#Expose
private Integer productId;
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The productId
*/
public Integer getProductId() {
return productId;
}
/**
*
* #param productId
* The productId
*/
public void setProductId(Integer productId) {
this.productId = productId;
}
}
The main class:
public class Example {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("promotedProducts")
#Expose
private List<PromotedProduct> promotedProducts = new ArrayList<PromotedProduct>();
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The promotedProducts
*/
public List<PromotedProduct> getPromotedProducts() {
return promotedProducts;
}
/**
*
* #param promotedProducts
* The promotedProducts
*/
public void setPromotedProducts(List<PromotedProduct> promotedProducts) {
this.promotedProducts = promotedProducts;
}
}
And the last Product:
public class Product {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("reviewList")
#Expose
private List<Object> reviewList = new ArrayList<Object>();
#SerializedName("productDetail")
#Expose
private ProductDetail productDetail;
#SerializedName("attributeList")
#Expose
private List<AttributeList> attributeList = new ArrayList<AttributeList>();
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The reviewList
*/
public List<Object> getReviewList() {
return reviewList;
}
/**
*
* #param reviewList
* The reviewList
*/
public void setReviewList(List<Object> reviewList) {
this.reviewList = reviewList;
}
/**
*
* #return
* The productDetail
*/
public ProductDetail getProductDetail() {
return productDetail;
}
/**
*
* #param productDetail
* The productDetail
*/
public void setProductDetail(ProductDetail productDetail) {
this.productDetail = productDetail;
}
/**
*
* #return
* The attributeList
*/
public List<AttributeList> getAttributeList() {
return attributeList;
}
/**
*
* #param attributeList
* The attributeList
*/
public void setAttributeList(List<AttributeList> attributeList) {
this.attributeList = attributeList;
}
}
Of course you need to polish it a bit. I just copy-pasted the generated files. You can change your main class there from "Example" to whatever you may like plus remove some stuff you do not like.

ListView not displaying items(using retrofit to retrieve list)

Hello guys I'm still learning android things and this is my first time that I 'm building a list using retrofit to populate it from server. I receive no error, app doesn't crash, and my log show that I receive data from server.
My Adapter for listview:
public class TransactionsAdapter extends BaseAdapter {
ArrayList<Transactions> transactions;
public TransactionsAdapter(ArrayList<Transactions> transactions) {
this.transactions=transactions;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=null;
ViewHolder viewHolder = null;
if(convertView == null)
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.izvjestaji_item,parent,false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}
else{
view = convertView;
viewHolder= (ViewHolder) view.getTag();
}
Transactions transactions = (Transactions) getItem(position);
if(transactions != null) {
viewHolder.datum.setText(transactions.getPurchaseDate());
viewHolder.partner.setText(transactions.getMerchantName());
viewHolder.iznos.setText(transactions.getTransactionMoneyAmount().toString());
viewHolder.brojbodova.setText(transactions.getSalesAmount().toString());
}
return view;
}
private class ViewHolder{
TextView datum;
TextView partner;
TextView iznos;
TextView brojbodova;
public ViewHolder(View view) {
this.datum = (TextView) view.findViewById(R.id.izvjestaji_datum);
this.partner = (TextView) view.findViewById(R.id.izvjestaji_partner);
this.iznos = (TextView) view.findViewById(R.id.izvjestaji_iznos);
this.brojbodova=(TextView)view.findViewById(R.id.izvjestaji_brojbodova);
}
}
}
Model that server return generated via jsonschema2pojo.org
import javax.annotation.Generated;
#Generated("org.jsonschema2pojo")
public class Transactions {
private Integer Id;
private String PurchaseDate;
private Integer Month;
private Integer Year;
private Double SalesAmount;
private Object SpecialSalesActionId;
private Integer PosTerminalId;
private Integer CardId;
private String MerchantName;
private Integer TransactionPointsAmount;
private Double TransactionMoneyAmount;
private Boolean IsDeleted;
private Boolean IsVoucher;
private Integer LoyaltyLevel;
private Integer CategoryId;
private Object CardNo;
private Integer MerchantId;
/**
*
* #return
* The Id
*/
public Integer getId() {
return Id;
}
/**
*
* #param Id
* The Id
*/
public void setId(Integer Id) {
this.Id = Id;
}
/**
*
* #return
* The PurchaseDate
*/
public String getPurchaseDate() {
return PurchaseDate;
}
/**
*
* #param PurchaseDate
* The PurchaseDate
*/
public void setPurchaseDate(String PurchaseDate) {
this.PurchaseDate = PurchaseDate;
}
/**
*
* #return
* The Month
*/
public Integer getMonth() {
return Month;
}
/**
*
* #param Month
* The Month
*/
public void setMonth(Integer Month) {
this.Month = Month;
}
/**
*
* #return
* The Year
*/
public Integer getYear() {
return Year;
}
/**
*
* #param Year
* The Year
*/
public void setYear(Integer Year) {
this.Year = Year;
}
/**
*
* #return
* The SalesAmount
*/
public Double getSalesAmount() {
return SalesAmount;
}
/**
*
* #param SalesAmount
* The SalesAmount
*/
public void setSalesAmount(Double SalesAmount) {
this.SalesAmount = SalesAmount;
}
/**
*
* #return
* The SpecialSalesActionId
*/
public Object getSpecialSalesActionId() {
return SpecialSalesActionId;
}
/**
*
* #param SpecialSalesActionId
* The SpecialSalesActionId
*/
public void setSpecialSalesActionId(Object SpecialSalesActionId) {
this.SpecialSalesActionId = SpecialSalesActionId;
}
/**
*
* #return
* The PosTerminalId
*/
public Integer getPosTerminalId() {
return PosTerminalId;
}
/**
*
* #param PosTerminalId
* The PosTerminalId
*/
public void setPosTerminalId(Integer PosTerminalId) {
this.PosTerminalId = PosTerminalId;
}
/**
*
* #return
* The CardId
*/
public Integer getCardId() {
return CardId;
}
/**
*
* #param CardId
* The CardId
*/
public void setCardId(Integer CardId) {
this.CardId = CardId;
}
/**
*
* #return
* The MerchantName
*/
public String getMerchantName() {
return MerchantName;
}
/**
*
* #param MerchantName
* The MerchantName
*/
public void setMerchantName(String MerchantName) {
this.MerchantName = MerchantName;
}
/**
*
* #return
* The TransactionPointsAmount
*/
public Integer getTransactionPointsAmount() {
return TransactionPointsAmount;
}
/**
*
* #param TransactionPointsAmount
* The TransactionPointsAmount
*/
public void setTransactionPointsAmount(Integer TransactionPointsAmount) {
this.TransactionPointsAmount = TransactionPointsAmount;
}
/**
*
* #return
* The TransactionMoneyAmount
*/
public Double getTransactionMoneyAmount() {
return TransactionMoneyAmount;
}
/**
*
* #param TransactionMoneyAmount
* The TransactionMoneyAmount
*/
public void setTransactionMoneyAmount(Double TransactionMoneyAmount) {
this.TransactionMoneyAmount = TransactionMoneyAmount;
}
/**
*
* #return
* The IsDeleted
*/
public Boolean getIsDeleted() {
return IsDeleted;
}
/**
*
* #param IsDeleted
* The IsDeleted
*/
public void setIsDeleted(Boolean IsDeleted) {
this.IsDeleted = IsDeleted;
}
/**
*
* #return
* The IsVoucher
*/
public Boolean getIsVoucher() {
return IsVoucher;
}
/**
*
* #param IsVoucher
* The IsVoucher
*/
public void setIsVoucher(Boolean IsVoucher) {
this.IsVoucher = IsVoucher;
}
/**
*
* #return
* The LoyaltyLevel
*/
public Integer getLoyaltyLevel() {
return LoyaltyLevel;
}
/**
*
* #param LoyaltyLevel
* The LoyaltyLevel
*/
public void setLoyaltyLevel(Integer LoyaltyLevel) {
this.LoyaltyLevel = LoyaltyLevel;
}
/**
*
* #return
* The CategoryId
*/
public Integer getCategoryId() {
return CategoryId;
}
/**
*
* #param CategoryId
* The CategoryId
*/
public void setCategoryId(Integer CategoryId) {
this.CategoryId = CategoryId;
}
/**
*
* #return
* The CardNo
*/
public Object getCardNo() {
return CardNo;
}
/**
*
* #param CardNo
* The CardNo
*/
public void setCardNo(Object CardNo) {
this.CardNo = CardNo;
}
/**
*
* #return
* The MerchantId
*/
public Integer getMerchantId() {
return MerchantId;
}
/**
*
* #param MerchantId
* The MerchantId
*/
public void setMerchantId(Integer MerchantId) {
this.MerchantId = MerchantId;
}
}
Fragment in which I want to include list:
public class Izvjestaji extends Fragment {
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Defines the xml file for the fragment
return inflater.inflate(R.layout.izvjestaji, parent, false);
}
// This event is triggered soon after onCreateView().
// Any view setup should occur here. E.g., view lookups and attaching view listeners.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
list=(ListView)view.findViewById(R.id.izvjestaji_list);
showList();
// Setup any handles to view objects here
// EditText etFoo = (EditText) view.findViewById(R.id.etFoo);
}
public void showList(){
NetworkSDK.getInstance().getTransactions(new Callback<List<Transactions>>() {
#Override
public void onResponse(Call<List<Transactions>> call, Response<List<Transactions>> response) {
if(response.isSuccess()){
Log.d("Data", String.valueOf(response.isSuccess()));
TransactionsAdapter transactionsAdapter=new TransactionsAdapter((ArrayList<Transactions>)response.body());
list.setAdapter(transactionsAdapter);
}
}
#Override
public void onFailure(Call<List<Transactions>> call, Throwable t) {
Log.d("Error","Def error");
}
});
}
}
2 xml files (one is from fragment and other is single item in list )
Fragment layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/izvjestaji_list" />
</LinearLayout>
Item_Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Datum"
android:id="#+id/izvjestaji_datum"
android:gravity="center"
android:background="#a9a8a8"
android:layout_weight="1"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/izvjestaji_partner"
android:text="Partner"
android:gravity="center"
android:background="#a9a8a8"
android:layout_weight="1"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/izvjestaji_iznos"
android:text="Iznos"
android:background="#a9a8a8"
android:gravity="center"
android:layout_weight="1"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/izvjestaji_brojbodova"
android:text="Broj Bodova"
android:gravity="center"
android:background="#a9a8a8"
android:layout_weight="1"
android:textSize="20dp" />
</LinearLayout>
In my preview I only get empty fragment
In TransactionAdapter class you have not implemented the overriding methods
use these
#Override
public int getCount() {
return transactions.size();
}
#Override
public Object getItem(int position) {
return transactions.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
Change to this
#Override
public int getCount() {
return transactions.size();
}
#Override
public Object getItem(int position) {
return transactions.get(position);
}
#Override
public long getItemId(int position) {
return position;
}

Can't populate layout with JSON data

I'm trying to populate a layout of mine by looping through some requested JSON (I use Retrofit).
When I try to populate the layout manually (like below), it displays fine:
Post post1 = new Post("1", "1", "This is a message.");
But if I try to populate it with the requested JSON data, the layout doesn't get populated nor does it display on my screen. Only the layout with "This is a message." is displayed.
Here is the code within my onCreateView() for my fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) view.findViewById(R.id.listview_posts);
final ArrayList<Post> arrayOfUsers = new ArrayList<Post>();
// This works fine. It populates the layout as it should.
Post post1 = new Post("1", "1", "This is a message.");
arrayOfUsers.add(post1);
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.build();
final ApiEndpointInterface apiService = restAdapter.create(ApiEndpointInterface.class);
apiService.getJsonStuff(1, new Callback<PostData>() {
#Override
public void success(PostData postData, Response response) {
// This doesn't work either
Post post2 = new Post("1", "1", "This is a message2.");
arrayOfUsers.add(post2);
for (Post p : postData.data) {
// This does not work. The layout isn't populated nor does it display.
Post posty = new Post(p.getId(), p.getUserId(), p.getContent());
arrayOfUsers.add(posty);
// The JSON is being read correctly, since this prints out the right values.
Log.d("MESSAGE", p.getMessage());
}
}
#Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace();
}
});
PostAdapter adapter = new PostAdapter(getActivity(), arrayOfUsers);
listView.setAdapter(adapter);
return view;
}
The callback:
void getJsonStuff(#Path("user_id") int userId, Callback<PostData> response);
Post model:
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Post {
#Expose
private String id;
#SerializedName("user_id")
#Expose
private String userId;
#Expose
private String content;
public Post(String id, String userId, String content) {
this.id = id;
this.userId = userId;
this.content = content;
}
/**
*
* #return
* The id
*/
public String getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* #return
* The userId
*/
public String getUserId() {
return userId;
}
/**
*
* #param userId
* The user_id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
*
* #return
* The content
*/
public String getContent() {
return content;
}
/**
*
* #param content
* The content
*/
public void setContent(String content) {
this.content= content;
}
}
PostData model:
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
public class PostData {
#Expose
public Boolean success;
#Expose
public List<Post> data = new ArrayList<Post>();
/**
*
* #return
* The success
*/
public Boolean getSuccess() {
return success;
}
/**
*
* #param success
* The success
*/
public void setSuccess(Boolean success) {
this.success = success;
}
/**
*
* #return
* The data
*/
public List<Post> getData() {
return data;
}
/**
*
* #param data
* The data
*/
public void setData(List<Post> data) {
this.data = data;
}
}
In the scenario that works for you -> you are doing the things sequentially: create the Post object - add it to the list - create the adapter based on the non-empty list - set the adapter on the list.
In the scenario that doesn't work, you are doing them asynchronously: create empty list - trigger request for data (but no data yet) - create adapter - set the adapter on the list - at some undetermined moment in the future data arrives. The problem is that in this case the adapter doesn't know that anything changed, so you need to notify it (at the end of your success callback):
adapter.notifyDataSetChanged()
Your getJsonStuff method should be declared something like...
getJsonStuff(int id, Callback<List<Post>> callback)

How to show data in spinner android?

I am using spinner which get populated dynamically from data base
here is my code
<Spinner
android:id="#+id/spnOrdrPrdBrand"
style="#style/ButtonStyleSpinner"
android:layout_marginTop="5dp"
android:hint="#string/select"
android:paddingLeft="5dp" />
List<Brand> brandList = new ArrayList<Brand>();
if(!custId.equals("0")){
brandList = cCon.getBrandList(custId);
}
// Sorting
//Collections.sort(brandList);
//Brand Lst
ArrayAdapter<Brand> brandAdp = new ArrayAdapter<Brand>(this,android.R.layout.simple_spinner_item,brandList.toArray(new Brand[brandList.size()]));
brandAdp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnOrdrPrdBrand.setAdapter(brandAdp);
data is thr in brandList object
but while populating showing me object name instead actual brand name.
I am using
public class Brand implements Comparable<Brand>{
// private variables
protected int brandId;
protected String brandNm;
// Empty constructor
public Brand() {
}
// constructor
public Brand(int brandId, String brandNm) {
this.brandId = brandId;
this.brandNm = brandNm;
}
/**
* #return the brandId
*/
public int getBrandId() {
return brandId;
}
/**
* #param brandId the brandId to set
*/
public void setBrandId(int brandId) {
this.brandId = brandId;
}
/**
* #return the brandNm
*/
public String getBrandNm() {
return brandNm;
}
/**
* #param brandNm the brandNm to set
*/
public void setBrandNm(String brandNm) {
this.brandNm = brandNm;
}
#Override
public int compareTo(Brand another) {
if (this.brandNm.equals(another.brandNm)) {
return ((Integer.valueOf(this.brandId)).compareTo(Integer.valueOf(another.brandId)));
} else {
return this.brandNm.compareTo(another.brandNm);
}
}
}
so how to resolve for the same
What are you showing is the toString implementation of Object. If you do not want to have a custom adapter, you can override toString() in your Brand class and let it returns the String you want to show,

parcelable is not working android

I'm trying to send an ArrayList of custom objects to the next activity but its not working for me. I've been all day trying to implement Parcelable with no luck at all. I've done my research here on SO but i'm still getting an error: Cannot convert Parceable[] to ArraList<Song> This is my code for parceling my object:
// Parcelling part
public Song(Parcel in){
this._id = in.readInt();
this.name = in.readString();
this.path = in.readString();
this.artistId = in.readInt();
this.albumId = in.readInt();
}
#Override
public int describeContents(){
return 0;
}
public static final Parcelable.Creator<Song> CREATOR = new Parcelable.Creator<Song>() {
public Song createFromParcel(Parcel in) {
return new Song(in);
}
public Song[] newArray(int size) {
return new Song[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(_id);
dest.writeString(name);
dest.writeString(path);
dest.writeInt(artistId);
dest.writeInt(albumId);
}
In my first activity i just:
ArrayList<Song> songs = db.selectAllSongs();
playerActivity.putParcelableArrayListExtra("songs", songs);
And in my second activity i just:
ArrayList<Song> songs = getIntent().getParcelableArrayExtra("songs");
I don't know why im getting an error when i'm implementing Parceable. I need a little guiding. Thanks in advance.
I hope this will help for you. In this way i am using parcellable values
public class Channel implements Serializable, Parcelable {
/** */
private static final long serialVersionUID = 4861597073026532544L;
private String cid;
private String uniqueID;
private String name;
private String logo;
/**
* #return the cid
*/
public String getCid() {
return cid;
}
/**
* #param cid
* the cid to set
*/
public void setCid(String cid) {
this.cid = cid;
}
/**
* #return the uniqueID
*/
public String getUniqueID() {
return uniqueID;
}
/**
* #param uniqueID
* the uniqueID to set
*/
public void setUniqueID(String uniqueID) {
this.uniqueID = uniqueID;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the logo
*/
public String getLogo() {
return logo;
}
/**
* #param logo
* the logo to set
*/
public void setLogo(String logo) {
this.logo = logo;
}
public Channel(Parcel in) {
super();
readFromParcel(in);
}
public static final Parcelable.Creator<Channel> CREATOR = new Parcelable.Creator<Channel>() {
public Channel createFromParcel(Parcel in) {
return new Channel(in);
}
public Channel[] newArray(int size) {
return new Channel[size];
}
};
public void readFromParcel(Parcel in) {
String[] result = new String[23];
in.readStringArray(result);
this.cid = result[0];
this.uniqueID = result[1];
this.name = result[2];
this.logo = result[3];
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] { this.cid, this.uniqueID,
this.name, this.logo});
}}
And in Activity class
bundle.putParcelableArrayList("channel",
(ArrayList<Channel>) channels);
And in the second Activity screen get the bundle parcelable array like this
Bundle getBundle = this.getIntent().getExtras();
List<Channel> channelsList = getBundle.getParcelableArrayList("channel");
The method Intent.getParcelableArrayExtra() (link) returns an array of parcelable objects. You're assigning that to an ArrayList object, and the compiler is complaining because ArrayLists aren't arrays.
Try using getParcelableArrayListExtra() instead.

Categories

Resources