ListView not displaying items(using retrofit to retrieve list) - android

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;
}

Related

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

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.

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.

Converting nameless JSONArray to List using Retrofit

I'm trying to fill a List object by using retrofit. Currently, I'm getting a null pointer exception whenever I call the List object. How do I get retrofit to work properly?
My call to Retrofit:
#Override
public void success(List<Game> gameList, Response response) {
mGameSeason = gameList;
}
My Retrofit implementation:
public class ApiClient {
private static ApiInterface sApiService;
public static ApiInterface getApiClient() {
if (sApiService == null) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://www.someapi.com")
.build();
sApiService = restAdapter.create(ApiInterface.class);
}
return sApiService;
}
public interface ApiInterface {
#GET("path")
void getGames(Callback<List<Game>> callback);
}
}
My Game POJO:
public class Game {
#Expose
private String gameID;
#Expose
private String date;
#Expose
private String awayTeam;
#Expose
private String homeTeam;
#Expose
private String gameType;
/**
*
* #return
* The gameID
*/
public String getGameID() {
return gameID;
}
/**
*
* #param gameID
* The gameID
*/
public void setGameID(String gameID) {
this.gameID = gameID;
}
/**
*
* #return
* The date
*/
public String getDate() {
return date;
}
/**
*
* #param date
* The date
*/
public void setDate(String date) {
this.date = date;
}
/**
*
* #return
* The awayTeam
*/
public String getAwayTeam() {
return awayTeam;
}
/**
*
* #param awayTeam
* The awayTeam
*/
public void setAwayTeam(String awayTeam) {
this.awayTeam = awayTeam;
}
/**
*
* #return
* The homeTeam
*/
public String getHomeTeam() {
return homeTeam;
}
/**
*
* #param homeTeam
* The homeTeam
*/
public void setHomeTeam(String homeTeam) {
this.homeTeam = homeTeam;
}
/**
*
* #return
* The gameType
*/
public String getGameType() {
return gameType;
}
/**
*
* #param gameType
* The gameType
*/
public void setGameType(String gameType) {
this.gameType = gameType;
}
}
The JSON Response:
[
{
"gameID":"2011030416",
"date":"Mon Jun 11, 2012",
"awayTeam":"New Jersey Devils",
"homeTeam":"Los Angeles Kings",
"gameType":"Playoffs"
},
{
"gameID":"2011030415",
"date":"Sat Jun 09, 2012",
"awayTeam":"Los Angeles Kings",
"homeTeam":"New Jersey Devils",
"gameType":"Playoffs"
},
{
"gameID":"2011030414",
"date":"Wed Jun 06, 2012",
"awayTeam":"New Jersey Devils",
"homeTeam":"Los Angeles Kings",
"gameType":"Playoffs"
},
{
"gameID":"2011030413",
"date":"Mon Jun 04, 2012",
"awayTeam":"New Jersey Devils",
"homeTeam":"Los Angeles Kings",
"gameType":"Playoffs"
},
{
"gameID":"2011030314",
"date":"Mon May 21, 2012",
"awayTeam":"New York Rangers",
"homeTeam":"New Jersey Devils",
"gameType":"Playoffs"
},
{
"gameID":"2011030313",
"date":"Sat May 19, 2012",
"awayTeam":"New York Rangers",
"homeTeam":"New Jersey Devils",
"gameType":"Playoffs"
}
]
Do you declare correctly your list mGameSeason before?
You can try to do something like this
public void success(List<Game> gameList, Response response) {
mGameSeason.clear();
mGameSeason.addAll(gameList);
gameAdapter.notifyDataSetChanged();
}
You will also need to define an adapter for your list if you haven't already done it.
Let me know if this helps
Here's what you can do for the adapter
protected List<Game> mGameList;
protected LayoutInflater inflater;
protected Context mContext;
public GameAdapter(List<Game> games, Context context) {
this.mGameList = games;
this.mContext = context;
this.inflater = LayoutInflater.from(this.mContext);
}
#Override
public int getCount() {
return mGameList.size();
}
#Override
public Game getItem(int position) {
return mGameList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolderItem;
if(convertView==null){
// inflate the layout
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.list_item_game, parent, false);
// well set up the ViewHolder
viewHolderItem = new ViewHolderItem(convertView);
// store the holder with the view.
convertView.setTag(viewHolderItem);
}else{
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
viewHolderItem = (ViewHolderItem) convertView.getTag();
}
Game game = getItem(position);
// assign values if the object is not null
if(game != null) {
// set your layout here
viewHolderItem.nameGame.setText(game.getName());
}
return convertView;
}
static class ViewHolderItem {
#InjectView(R.id.name_radio)
TextView nameRadio;
public ViewHolderItem(View v) {
ButterKnife.inject(this, v);
}
}
RestAdapter and your API interface should be used as a SINGLETON, it looks like you are not checking the rest adapter to be a singleton, try something like this in your fragment or activity:
// Activity or fragment use
MyAwesomeApiInterface api;
MyAwesomeApiInterface getApi() {
if (api == null) {
api = getRestAdapter().create(MyAwesomeApiInterface.class);
}
return api;
}
Retrofit retrofit;
Retrofit getRestAdapter() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}

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,

BaseAdapter.notifyDatasetChanged() not updating the ListView

why does my listview not update when I call notifyDatasetChanged() ?
the only way I can make it display the data is, to call setAdatper() on the ListView again... i also tried to call it via runOnUIThread() which did not change anything
The Adapter
/**
* Adapter to provide the data for the online scores
*
* #author soh#zolex
*
*/
public class OnlineScoresAdapter extends BaseAdapter {
private Context context;
private List<ScoreItem> scores = new ArrayList<ScoreItem>();
/**
* Constructor
*
* #param Context context
*/
public OnlineScoresAdapter(Context context) {
this.context = context;
}
/**
* Add an item to the adapter
*
* #param item
*/
public void addItem(ScoreItem item) {
this.scores.add(item);
}
/**
* Get the number of scores
*
* #return int
*/
public int getCount() {
return this.scores.size();
}
/**
* Get a score item
*
* #param int pos
* #return Object
*/
public Object getItem(int pos) {
return this.scores.get(pos);
}
/**
* Get the id of a score
*
* #param in pos
* #retrn long
*/
public long getItemId(int pos) {
return 0;
}
/**
* Get the type of an item view
*
* #param int pos
* #return int
*/
public int getItemViewType(int arg0) {
return arg0;
}
/**
* Create the view for a single list item.
* Load it from an xml layout.
*
* #param int pos
* #param View view
* #param ViewGroup viewGroup
* #return View
*/
public View getView(int pos, View view, ViewGroup group) {
LinearLayout layout;
if (view == null) {
layout = (LinearLayout)View.inflate(this.context, R.layout.scoreitem, null);
} else {
layout = (LinearLayout)view;
}
TextView position = (TextView)layout.findViewById(R.id.pos);
TextView time = (TextView)layout.findViewById(R.id.time);
TextView player = (TextView)layout.findViewById(R.id.player);
TextView createdAt = (TextView)layout.findViewById(R.id.created_at);
ScoreItem item = (ScoreItem)getItem(pos);
player.setText(item.player);
position.setText(String.valueOf(new Integer(item.position)) + ".");
time.setText(String.format("%.4f", item.time));
createdAt.setText(item.created_at);
return layout;
}
/**
* Get the number of different views
*
* #return int
*/
public int getViewTypeCount() {
return 1;
}
/**
* Return wheather the items have stable IDs or not
*
* #return boolean
*/
public boolean hasStableIds() {
return false;
}
/**
* Return wheather the list is empty or not
*
* #return boolean
*/
public boolean isEmpty() {
return this.scores.size() == 0;
}
/**
* No need of a data observer
*
* #param DataSetObserver arg0
* #return void
*/
public void registerDataSetObserver(DataSetObserver arg0) {
}
/**
* No need of a data observer
*
* #param DataSetObserver arg0
* #return void
*/
public void unregisterDataSetObserver(DataSetObserver arg0) {
}
/**
* No item should be selectable
*
* #return boolean
*/
public boolean areAllItemsEnabled() {
return false;
}
/**
* No item should be selectable
*
* #param int pos
* #return boolean
*/
public boolean isEnabled(int arg0) {
return false;
}
}
The Activity
The XMLLoaderThread works fine, it's just notifyDatasetChanged seems to do nothing...
/**
* Obtain and display the online scores
*
* #author soh#zolex
*
*/
public class OnlineScoresDetails extends ListActivity {
WakeLock wakeLock;
OnlineScoresAdapter adapter;
boolean isLoading = false;
int chunkLimit = 50;
int chunkOffset = 0;
#Override
/**
* Load the scores and initialize the pager and adapter
*
* #param Bundle savedInstanceState
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "racesow");
adapter = new OnlineScoresAdapter(this);
setListAdapter(adapter);
this.loadData();
setContentView(R.layout.listview);
getListView().setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (totalItemCount > 0 && visibleItemCount > 0 && firstVisibleItem + visibleItemCount >= totalItemCount) {
if (!isLoading) {
loadData();
}
}
}
});
}
public void loadData() {
final ProgressDialog pd = new ProgressDialog(OnlineScoresDetails.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("Obtaining scores...");
pd.setCancelable(false);
pd.show();
isLoading = true;
String mapName = getIntent().getStringExtra("map");
XMLLoaderThread t = new XMLLoaderThread("http://racesow2d.warsow-race.net/map_positions.php?name=" + mapName + "&offset=" + this.chunkOffset + "&limit=" + this.chunkLimit, new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
// network error
case 0:
new AlertDialog.Builder(OnlineScoresDetails.this)
.setMessage("Could not obtain the maplist.\nCheck your network connection and try again.")
.setNeutralButton("OK", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
overridePendingTransition(0, 0);
}
})
.show();
break;
// maplist received
case 1:
pd.dismiss();
InputStream xmlStream;
try {
xmlStream = new ByteArrayInputStream(msg.getData().getString("xml").getBytes("UTF-8"));
XMLParser parser = new XMLParser();
parser.read(xmlStream);
NodeList positions = parser.doc.getElementsByTagName("position");
int numPositions = positions.getLength();
for (int i = 0; i < numPositions; i++) {
Element position = (Element)positions.item(i);
ScoreItem score = new ScoreItem();
score.position = Integer.parseInt(parser.getValue(position, "no"));
score.player = parser.getValue(position, "player");
score.time = Float.parseFloat(parser.getValue(position, "time"));
score.created_at = parser.getValue(position, "created_at");
adapter.addItem(score);
}
adapter.notifyDataSetChanged();
chunkOffset += chunkLimit;
isLoading = false;
} catch (UnsupportedEncodingException e) {
new AlertDialog.Builder(OnlineScoresDetails.this)
.setMessage("Internal error: " + e.getMessage())
.setNeutralButton("OK", null)
.show();
}
break;
}
pd.dismiss();
}
});
t.start();
}
/**
* Acquire the wakelock on resume
*/
public void onResume() {
super.onResume();
this.wakeLock.acquire();
}
/**
* Release the wakelock when leaving the activity
*/
public void onDestroy() {
super.onDestroy();
this.wakeLock.release();
}
/**
* Disable animations when leaving the activity
*/
public void onBackPressed() {
this.finish();
this.overridePendingTransition(0, 0);
}
}
A bit late but the answer is you should not implement
public void registerDataSetObserver(DataSetObserver arg0) {
}
public void unregisterDataSetObserver(DataSetObserver arg0) {
}
I just had a simple BaseAdapter working as intended, who stop working after adding those two methods. I asume that "someone" need to observe data changes and such :)
I am not really sure if your implementation of Custom BaseAdapter is correct.
Try changing
public long getItemId(int pos) {
return 0;
}
to
public long getItemId(int pos) {
return pos;
}
I also found this simple tutorial that might be helpful on how to implement BaseAdapter. After you got this down, you can try notifyDataSetChanged() again.
You should call adapter.notifyDataSetChanged() after every manipulation of your dataset. If you're adding items in a batch (e.g. a for-loop), this means you have to put .notifyDataSetChanged in your loop, like so:
for(int i = 0; i < numPositions; i++) {
....
adapter.addItem(score);
adapter.notifyDataSetChanged();
}
Make sure you call adapter.notifyDataSetChanged() from your UI-thread.
If you rather update your adapter once, store your ScoreItems in an ArrayList and after the loop call:
adapter.addAll(scoreList);
adapter.notifyDataSetChanged();
But then again, as far as I'm aware there's really no reason to do that.
Maybe it will be helpful to someone. For the method to work correctly, you should make sure that the following conditions are met:
1) getCount() should return correct items size, e.g.
#Override
public int getCount() {
return allMonthDays.size();
}
2) getItemId(int position) should return different id if item was changed, so it may be not enough to return just position here, e.g.
#Override
public long getItemId(int position) {
return allMonthDays.get(position).getTimestamp();
}
3) getView(int position, View convertView, ViewGroup parent) should return needed View, you should make sure that you update it if you want to reuse old convertView

Categories

Resources