When i try to put my Expandable layout to the bottom of my cardview using
android:layout_gravity="bottom" it goes to the bottom but expands upwards
After clicking the relative layout "button"
I am getting data from arraylist passing it to the recyclerview and cardview
i don't know if it's because of the Adapter animation settings or just fomr the xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_gravity="top"
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginEnd="8dp"
android:layout_marginBottom="551dp"
android:animateLayoutChanges="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/holderimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView5"
android:layout_width="68dp"
android:layout_height="62dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
app:srcCompat="#drawable/s1960678" />
<TextView
android:id="#+id/nameArray"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:fontFamily="serif"
android:includeFontPadding="false"
android:text="TextView"
android:textSize="14sp"
android:textStyle="bold" />
<RelativeLayout
android:id="#+id/button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp"
android:background="#drawable/ic_arrow_drop_down_black_24dp"
android:foregroundGravity="right"
android:gravity="right|center_horizontal"
android:orientation="vertical">
<View
android:id="#+id/view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<com.github.aakira.expandablelayout.ExpandableLinearLayout
android:id="#+id/expandableLayout"
android:layout_width="match_parent"
android:layout_height="72dp"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:foregroundGravity="bottom"
android:gravity="top"
android:orientation="vertical"
app:ael_duration="400"
app:ael_expanded="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/button3"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:text="Button"
tools:text="Download .PDF" />
<Button
android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
tools:text="View PDF" />
</LinearLayout>
</com.github.aakira.expandablelayout.ExpandableLinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
and here's the activity it gets data from , it's xml has only recyclerview
package com.example.imc.PDF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.imc.MainAdapter;
import com.example.imc.MySingleton;
import com.example.imc.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Resultsdwldview extends AppCompatActivity {
public RequestQueue requestQueue;
TextView MedicalText,PhoneText,AddressText,EmailText,result,resultArray;
EditText id;
Button getidbtn;
List<ArrayList<String>> Tests = new ArrayList<>();
ArrayList<String> urlArray = new ArrayList<String>();
ArrayList<String> nameArray = new ArrayList<String>();
ArrayList<String> IdfromjsonArray = new ArrayList<String>();
ArrayList<String> Patient_ID_Array = new ArrayList<String>();
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
WebView webView;
String PDFurl;
String idvalue;
String url = "https://docs.google.com/viewer?url=http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resultsdwldview);
MedicalText = findViewById(R.id.MedicalText);
PhoneText = findViewById(R.id.PhoneText);
AddressText = findViewById(R.id.AddressText);
EmailText = findViewById(R.id.EmailText);
// webView = findViewById(R.id.webview); //WEBVIEW
// webView.requestFocus();
// webView.getSettings().setJavaScriptEnabled(true);
// webView.loadUrl(url);
mRecyclerView = findViewById(R.id.recyvlerView);
// id = findViewById(R.id.getid);
// getidbtn =(Button) findViewById(R.id.send);
mLayoutManager = new LinearLayoutManager(this);
jsonParse();
/*
getidbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//idvalue = id.getEditableText().toString();
jsonParse();
}
});*/
}
public void jsonParse() {
String URL="http://ashaaban-001-site1.btempurl.com/api/patients/"+4;
//String URL="http://ashaaban-001-site1.btempurl.com/api/patients/"+idvalue;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Tests");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject arraydata = jsonArray.getJSONObject(i);
// Tests.add(jsonObject.getString(String.valueOf(i)));
String urlName = arraydata.getString("urlName");
String Name =arraydata.getString("Name");
String Idfromjson =arraydata.getString("Id");
String P_ID_Array =arraydata.getString("patients_Id");
urlArray.add(urlName);
nameArray.add(Name);
IdfromjsonArray.add(Idfromjson);
Patient_ID_Array.add(P_ID_Array);
Tests.add(urlArray);
Tests.add(nameArray);
Tests.add(IdfromjsonArray);
Tests.add(Patient_ID_Array);
// resultArray.append("urlName = " +urlName+" \n\n Name"+Name);
}
//resultArray.append(Tests+" , \n ");
// mRecyclerView.setHasFixedSize(true);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Integer P_MedicalNumber = response.getInt("MedicalNumber");
Integer P_id = response.getInt("Id");
String P_Username = response.getString("UserName");
Integer P_PhoneNumber = response.getInt("phoneNumber");
String P_Address = response.getString("Address");
String P_Email = response.getString("Email");
//result.append("Medical Number : "+P_MedicalNumber+" \n id :"+P_id+"UserName"+P_Username);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter = new MainAdapter(Tests,nameArray);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyItemRangeInserted(0, Tests.size());
// webView.loadUrl(PDFurl);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
});
// requestQueue.add(request);
MySingleton.getInstance(Resultsdwldview.this).addToReqeustQueue(jsonObjectRequest);
}
}
Adapter
package com.example.imc;
import android.animation.ObjectAnimator;
import android.content.ClipData;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.aakira.expandablelayout.ExpandableLayout;
import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter;
import com.github.aakira.expandablelayout.ExpandableLinearLayout;
import com.github.aakira.expandablelayout.Utils;
import java.util.ArrayList;
import java.util.List;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
List<ArrayList<String>> Tests;
ArrayList<String> urlArray;
ArrayList<String> nameArray;
ArrayList<String> IdfromjsonArray ;
ArrayList<String> Patient_ID_Array;
SparseBooleanArray expandState =new SparseBooleanArray();
public MainAdapter(List<ArrayList<String>> tests, ArrayList<String> urlArray, ArrayList<String> nameArray,
ArrayList<String> idfromjsonArray, ArrayList<String> patient_ID_Array) {
Tests = tests;
this.urlArray = urlArray;
this.nameArray = nameArray;
IdfromjsonArray = idfromjsonArray;
Patient_ID_Array = patient_ID_Array;
}
public MainAdapter(List<ArrayList<String>> tests, ArrayList<String> nameArray) {
Tests = tests;
this.nameArray = nameArray;
}
#NonNull
#Override
//Initialize the viewholder
public MainAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row,viewGroup,false);
return new ViewHolder(view);
}
/***************////////////////onBind Holds values to pass it to the viewholder///////////////////*******************
/***************////////////////
// This method is called for each ViewHolder to
// bind it to the adapter
// . This is where we will// pass our data to our ViewHolder///////////////////*******************
#Override
public void onBindViewHolder(#NonNull final MainAdapter.ViewHolder holder, final int i) {
// holder.URLName.setText( urlArray.get(i));
holder.mFullname.setText( nameArray.get(i));
holder.expandableLayout.setInRecyclerView(true);
holder.expandableLayout.setExpanded(expandState.get(i));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
changeRotate(holder.button,180f,0f).start();
expandState.put(i,true);
}
#Override
public void onPreClose() {
changeRotate(holder.button,0f,180f).start();
expandState.put(i,false);
}
});
holder.button.setRotation(expandState.get(i)?0f:180f);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Expandable child item
holder.expandableLayout.toggle();
}
});
}
private ObjectAnimator changeRotate(RelativeLayout button, float to, float from) {
ObjectAnimator animator = ObjectAnimator.ofFloat(button,"rotation",from,to);
animator.setDuration(200);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
#Override
public int getItemCount() {
return nameArray.size();
}
/***************////////////////VIEWHOLDER///////////////////*******************
public class ViewHolder extends RecyclerView.ViewHolder {
// public TextView URLName;
public TextView mFullname;
public RelativeLayout button;
public ExpandableLinearLayout expandableLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mFullname=itemView.findViewById(R.id.nameArray);
//URLName=itemView.findViewById(R.id.URLName);
button=itemView.findViewById(R.id.button);
expandableLayout=itemView.findViewById(R.id.expandableLayout);
}
}
}
Related
I am starting with Android java development and I am facing a issue on the ViewPager2 implementation.
On my app I have a ViewPager2 and I am inflate on it a layout which has a RecycleView.
The problem is, when I turn the ViewPager2 from page 0 to page 1, the adapter execulte onBindViewHolder twice, jumping from adapter position 0 to 1 and imediatelly from position 1 to 2. (ViewPager2 position stay on 1)
As I am populating the RecycleView with a Volley DB consult, this theard start only after the ViewPAger2 Adapter finish its works (after adapter execulte onBindViewHolder twice). So, only the ViewPager2 position 2 is populated (twice), ViewPager2 page 1 stay empty.
Thus, I kindly ask your help to avoid adapter execute onBindViewHolder twice once ViewPAger2 change. Or makes Volley executes its thread when the adapter position change from 0 to 1 and again when it change from 1 to 2.
Please help me since I have 5 days working around this problem without success.
See belwo my codes:
MY VIEWPAGER2 ADAPTER (Adapter_Department)
package br.com.portosaue.portosaueapp;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Adapter_Department extends RecyclerView.Adapter<Adapter_Department.UserViewHolder> {
Context mContext;
private RecyclerView rcv_products;
private RecyclerView.Adapter mAdapter;
private LinearLayoutManager mLayoutManager;
ViewPager2 vpg_productList;
List<Department> departmentList;
String Host_IP;
String ProductComment;
public MyAdapter(Context mContext, List<Department> departmentList) {
this.mContext = mContext;
this.departmentList = departmentList;
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Host_IP = "192.168.0.100";
View view = LayoutInflater.from(mContext).inflate(R.layout.products_list, parent, false);
return new UserViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
productsList(departmentList.get(position).getName());
}
#Override
public int getItemCount() {
return departmentList.size();
}
public class UserViewHolder extends RecyclerView.ViewHolder {
public UserViewHolder(#NonNull final View itemView) {
super(itemView);
rcv_products = itemView.findViewById(R.id.rcv_Products);
vpg_productList = ((Activity) mContext).findViewById(R.id.vpg_Products);
}
}
private void productsList(String department){
//SELECTING URL
String json_products;
switch (department) {
case "Salao":
json_products = "http://" + Host_IP + "/getSalon.php";
break;
case "Cozinha":
json_products = "http://" + Host_IP + "/getKitchen.php";
break;
case "Copa":
json_products = "http://" + Host_IP + "/getDrink.php";
break;
case "Churrasqueira":
json_products = "http://" + Host_IP + "/getBarbecue.php";
break;
case "Caixa":
json_products = "http://" + Host_IP + "/getCash.php";
break;
default:
json_products = "http://" + Host_IP + "/getProducts";
}
//VOLLEY / FETCH / JSONOBJECT
StringRequest stringRequest = new StringRequest(Request.Method.GET, json_products,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
ArrayList<Func_LoadProduct> loadproduct = new ArrayList<Func_LoadProduct>();
Func_LoadProduct p;
String ImagePath;
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
ImagePath = "http://" + Host_IP + "/PS APP Images/" + product.getString("Imagem");
p = new Func_LoadProduct(product.getInt("ID"),
product.getString("Nome"),
product.getDouble("Preco"),
ImagePath,
"");
loadproduct.add(p);
}
rcv_products=((Activity)mContext).findViewById(R.id.rcv_Products);
rcv_products.setHasFixedSize(true);
mLayoutManager=new LinearLayoutManager(mContext);
mAdapter=new Adapter_Products(loadproduct);
rcv_products.setLayoutManager(mLayoutManager);
rcv_products.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(mContext).add(stringRequest);
}
}
VIEWPAGER2 CLASS (Products)
package br.com.portosaue.portosaueapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager2.widget.ViewPager2;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Products extends AppCompatActivity {
ViewPager2 vpg_products;
List<Department> departmentList;
Adapter_Department adapterDepartment;
String TableNumb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
vpg_products = findViewById(R.id.vpg_Products);
departmentList = new ArrayList<>();
departmentList.add(new Department("Salon"));
departmentList.add(new Department("Kitchen"));
departmentList.add(new Department("Bar"));
adapterDepartment = new Adapter_Department(this, departmentList);
vpg_products.setAdapter(adapterDepartment);
}
}
VIEWPAGER2 LAYOUT (activity_departments.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Products"
android:orientation="vertical">
<include
android:id="#+id/tbr_toobar"
layout = "#layout/toolbar"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/vpg_Products"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="#+id/tbr_toobar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tbr_toobar"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
RECYCLEVIEW ADAPTER (Adapter_Products)
package br.com.portosaue.portosaueapp;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Adapter_Products extends RecyclerView.Adapter<Adapter_Products.MyViewHolder>{
private ArrayList<Func_LoadProduct> mProductList;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView img_ProductImage;
public TextView txv_ProductName;
public TextView txv_ProductPrice;
public TextView txv_ProductID;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
img_ProductImage = itemView.findViewById(R.id.imv_ProductImage);
txv_ProductName = itemView.findViewById(R.id.txv_ProductName);
txv_ProductPrice = itemView.findViewById(R.id.txv_ProductPrice);
txv_ProductID = itemView.findViewById(R.id.txv_ProcutID);
}
}
public Adapter_Products( ArrayList<Func_LoadProduct> productList){
this.mProductList=productList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_line, parent, false);
MyViewHolder evh = new MyViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Func_LoadProduct currentItem = mProductList.get(position);
Picasso.get().load(mProductList.get(position).getProductImageName()).into(holder.img_ProductImage);
holder.txv_ProductName.setText(currentItem.getProductName());
holder.txv_ProductPrice.setText("R$ " + Double.toString(currentItem.getProductPrice()));
holder.txv_ProductID.setText("ID: " + Integer.toString(currentItem.getProductID()));
}
#Override
public int getItemCount() {
return mProductList.size();
}
}
RECYCLEVIEW LAYOUT (product_list.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rcv_Products"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp" />
</RelativeLayout>
ITEMS CLASS (Func_LoadProduct)
package br.com.portosaue.portosaueapp;
public class Func_LoadProduct {
private int ProductID;
private String ProductName;
private double ProductPrice;
private String ProductImageName;
private String ProductComment;
public Func_LoadProduct(int productID, String productName, double productPrice, String productImageName, String productComment){
this.ProductID = productID;
this.ProductName = productName;
this.ProductPrice = productPrice;
this.ProductImageName = productImageName;
this.ProductComment = productComment;
}
//SET
public void setProductID(int productID) {
this.ProductID = productID;
}
public void setProductName(String productName) {
this.ProductName = productName;
}
public void setProductPrice(double productPrice) {
this.ProductPrice = productPrice;
}
public void setProductImageName(String productImageName) { this.ProductImageName = productImageName; }
public void setProductComment(String productComment) { this.ProductComment = productComment; }
//GET
public int getProductID() {
return this.ProductID;
}
public String getProductName() {
return this.ProductName;
}
public double getProductPrice() {
return this.ProductPrice;
}
public String getProductImageName() { return this.ProductImageName; }
public String getProductComment() { return this.ProductComment; }
}
ITEMS LAYOUT (product_line.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="4dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imv_ProductImage"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="2dp"
android:scaleType="fitXY"
tools:srcCompat="#tools:sample/avatars"/>
<TextView
android:id="#+id/txv_ProductName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="64dp"
android:layout_marginTop="2dp"
android:textColor="#android:color/black"
android:textSize="20sp"
android:layout_weight="10"
android:text="Produto"
android:textAppearance="#style/TextAppearance.AppCompat.Large"/>
<TextView
android:id="#+id/txv_ProductPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/txv_ProductName"
android:layout_alignParentTop="true"
android:layout_marginStart="2dp"
android:layout_marginTop="31dp"
android:layout_weight="3"
android:text="Valor"
android:textSize="15sp" />
<TextView
android:id="#+id/txv_ProcutID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txv_ProductPrice"
android:layout_alignParentStart="true"
android:layout_marginStart="347dp"
android:layout_marginBottom="0dp"
android:layout_weight="1"
android:text="ID"
android:textSize="15sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
List_items are not showing in the RecyclerView.
Have tried changing the layout height and other answers.
The list_items should contain
-item_name
-item_quantity
-date
So basically after entering the respective dataset in an AlertDialog and after clicking the save button, the ListActivity will show up. But a Blank Screen is showing up not containing the list_items within the CardView.
Here's the ListActivity
package com.example.akash.distributedapp.DatabaseApp.Activities;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.akash.distributedapp.DatabaseApp.Data.DatabaseHandler;
import com.example.akash.distributedapp.DatabaseApp.Model.Grocery;
import com.example.akash.distributedapp.DatabaseApp.UI.RecyclerViewAdapter;
import com.example.akash.distributedapp.R;
import java.util.ArrayList;
import java.util.List;
public class ListActivity extends AppCompatActivity {
private DatabaseHandler db;
private RecyclerView recyclerView;
private List<Grocery> groceryList;
private List<Grocery> listItems;
private RecyclerViewAdapter recyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
db = new DatabaseHandler(this);
recyclerView = findViewById(R.id.recyclerViewID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
groceryList = new ArrayList<>();
listItems = new ArrayList<>();
//get items from database
groceryList = db.getAllGroceries();
for(Grocery c : groceryList){
Grocery grocery = new Grocery();
grocery.setName(c.getName());
grocery.setQuantity("Qty:" + c.getQuantity());
grocery.setId(c.getId());
grocery.setDateItemAdded("Added on: " + c.getDateItemAdded());
listItems.add(grocery);
}
recyclerViewAdapter = new RecyclerViewAdapter(this, listItems);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
}
Here's the adapter class
package com.example.akash.distributedapp.DatabaseApp.UI;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.akash.distributedapp.DatabaseApp.Model.Grocery;
import com.example.akash.distributedapp.R;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private Context context;
private List<Grocery> groceryItems;
public RecyclerViewAdapter(Context context, List<Grocery> groceryItems) {
this.context = context;
this.groceryItems = groceryItems;
}
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
Grocery grocery = groceryItems.get(position);
holder.groceryItemName.setText(grocery.getName());
holder.quantity.setText(grocery.getQuantity());
holder.quantity.setText(grocery.getDateItemAdded());
}
#Override
public int getItemCount() {
return groceryItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView groceryItemName;
public TextView quantity;
public TextView dateAdded;
public Button editBtn;
public Button deleteBtn;
public int id;
public ViewHolder(View itemView, Context ctx) {
super(itemView);
context = ctx;
groceryItemName = itemView.findViewById(R.id.tv_item);
quantity = itemView.findViewById(R.id.tv_qty);
dateAdded = itemView.findViewById(R.id.tv_date);
editBtn = itemView.findViewById(R.id.btn_edit);
deleteBtn = itemView.findViewById(R.id.btn_delete);
editBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opens new activity
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_edit:
break;
case R.id.btn_delete:
break;
}
}
}
}
Here is my XML file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="125dp"
android:padding="5dp">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:padding="15dp"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_item"
android:text="Grocery name"
android:textSize="18sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_qty"
android:layout_below="#+id/tv_item"
android:text="Quantity"
android:paddingTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_date"
android:paddingTop="5dp"
android:text="Date"
android:layout_below="#+id/tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableRow
android:layout_alignParentRight="true"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/btn_edit"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="15dp"
android:background="#android:drawable/ic_menu_edit"/>
<Button
android:id="#+id/btn_delete"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#android:drawable/ic_delete"/>
</TableRow>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I have an app which has Recyclerview and I want to put some facebook Native ads in between list items, like every 5 list items 1 native ad will be shown. everything is working perfectly but main problem is when I scroll down adChoice icon is being doubled and on scrolling up also adChoice icons are getting doubled. It seems that ads are overlapping to the previous one.
SCREENSHOT
Any suggestion will help me a lot. Here is the all source code and the official facebook audience network native ad code sample.
dependency
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.facebook.android:audience-network-sdk:4.+'
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
content_layout.xml
<?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="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/textViewHead"
android:text="Heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"/>
<TextView
android:id="#+id/textViewDesc"
android:text="Description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
ads_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:orientation="vertical">
<LinearLayout
android:id="#+id/adChoicesContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:orientation="vertical"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="center_vertical"
android:layout_marginBottom="5dp"
android:layout_marginRight="10dp"
android:orientation="horizontal">
<com.facebook.ads.AdIconView
android:id="#+id/adIconView"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
tools:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvAdTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#android:color/white"
tools:text="Ad Title"/>
<TextView
android:id="#+id/tvAdBody"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="end"
android:gravity="center_vertical"
android:lines="3"
android:textColor="#android:color/darker_gray"
tools:text="This is an ad description."/>
</LinearLayout>
</LinearLayout>
<com.facebook.ads.MediaView
android:id="#+id/mediaView"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
>
<TextView
android:id="#+id/sponsored_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:textColor="#android:color/darker_gray"
android:textSize="10sp"/>
<Button
android:id="#+id/btnCTA"
style="?android:attr/borderlessButtonStyle"
android:layout_width="130dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:background="#android:color/darker_gray"
android:gravity="center"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:text="Install Now"
android:textColor="#android:color/white"
android:textSize="14sp"/>
</RelativeLayout>
</LinearLayout>
ContentModel.java
package com.example.my_demo_app.fb_in-feed_ad;
public class ContentModel {
String head, des;
public ContentModel(String head, String des) {
this.head = head;
this.des = des;
}
public String getHead() {
return head;
}
public String getDes() {
return des;
}
}
MyAdapter.java
package com.example.my_demo_app.fb_in-feed_ad;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.ads.Ad;
import com.facebook.ads.AdChoicesView;
import com.facebook.ads.AdIconView;
import com.facebook.ads.MediaView;
import com.facebook.ads.NativeAd;
import java.util.ArrayList;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int MENU_ITEM_VIEW_TYPE = 0;
public static final int AD_ITEM_VIEW_TYPE = 1;
private final List<Object> mRecyclerViewItems;
private final Context context;
public MyAdapter(List<Object> recyclerViewItems, Context context) {
this.mRecyclerViewItems = recyclerViewItems;
this.context = context;
}
//--------------------getItemViewType
#Override
public int getItemViewType(int position) {
Object recyclerViewItem = mRecyclerViewItems.get(position);
if (recyclerViewItem instanceof ContentModel) {
return MENU_ITEM_VIEW_TYPE;
} else if (recyclerViewItem instanceof Ad) {
return AD_ITEM_VIEW_TYPE;
} else {
return -1;
}
}
//--------------------getItemCount
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
//--------------------onCreateViewHolder
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
if (viewType==MENU_ITEM_VIEW_TYPE){
View menuItemView = inflater.inflate(R.layout.content_layout, parent, false);
return new MenuItemHolder(menuItemView);
}else if (viewType==AD_ITEM_VIEW_TYPE){
View adItemView = inflater.inflate(R.layout.ads_layout, parent, false);
return new AdHolder(adItemView);
}
return null;
}
//--------------------onBindViewHolder
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int itemType = getItemViewType(position);
if (itemType==MENU_ITEM_VIEW_TYPE){
MenuItemHolder menuItemHolder = (MenuItemHolder) holder;
ContentModel contentModel = (ContentModel) mRecyclerViewItems.get(position);
menuItemHolder.txtH.setText(contentModel.getHead());
menuItemHolder.txtD.setText(contentModel.getDes());
}else if (itemType==AD_ITEM_VIEW_TYPE){
AdHolder nativeAdViewHolder = (AdHolder) holder;
NativeAd nativeAd = (NativeAd) mRecyclerViewItems.get(position);
AdIconView adIconView = nativeAdViewHolder.adIconView;
TextView tvAdTitle = nativeAdViewHolder.tvAdTitle;
TextView tvAdBody = nativeAdViewHolder.tvAdBody;
Button btnCTA = nativeAdViewHolder.btnCTA;
LinearLayout adChoicesContainer = nativeAdViewHolder.adChoicesContainer;
MediaView mediaView = nativeAdViewHolder.mediaView;
TextView sponsorLabel = nativeAdViewHolder.sponsorLabel;
tvAdTitle.setText(nativeAd.getAdvertiserName());
tvAdBody.setText(nativeAd.getAdBodyText());
btnCTA.setText(nativeAd.getAdCallToAction());
sponsorLabel.setText(nativeAd.getSponsoredTranslation());
AdChoicesView adChoicesView = new AdChoicesView(context, nativeAd, true);
adChoicesContainer.addView(adChoicesView);
List<View> clickableViews = new ArrayList<>();
clickableViews.add(btnCTA);
clickableViews.add(mediaView);
nativeAd.registerViewForInteraction(nativeAdViewHolder.container, mediaView, adIconView, clickableViews);
}
}
//--------------------MenuItemHolder
public class MenuItemHolder extends RecyclerView.ViewHolder{
public TextView txtH, txtD;
public MenuItemHolder(View itemView) {
super(itemView);
txtH = (TextView) itemView.findViewById(R.id.textViewHead);
txtD = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
//--------------------AdHolder
public class AdHolder extends RecyclerView.ViewHolder{
AdIconView adIconView;
TextView tvAdTitle;
TextView tvAdBody;
Button btnCTA;
View container;
TextView sponsorLabel;
LinearLayout adChoicesContainer;
MediaView mediaView;
AdHolder(View itemView) {
super(itemView);
this.container = itemView;
adIconView = (AdIconView) itemView.findViewById(R.id.adIconView);
tvAdTitle = (TextView) itemView.findViewById(R.id.tvAdTitle);
tvAdBody = (TextView) itemView.findViewById(R.id.tvAdBody);
btnCTA = (Button) itemView.findViewById(R.id.btnCTA);
adChoicesContainer = (LinearLayout) itemView.findViewById(R.id.adChoicesContainer);
mediaView = (MediaView) itemView.findViewById(R.id.mediaView);
sponsorLabel = (TextView) itemView.findViewById(R.id.sponsored_label);
}
}
}
MainActivity.java
package com.example.my_demo_app.fb_in-feed_ad;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.NativeAd;
import com.facebook.ads.NativeAdListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "https://res.cloudinary.com/ravi40/raw/upload/v1532239134/my_json/heroes_list.json";
private RecyclerView recyclerView;
private List<Object> mRecyclerViewItems;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerViewItems = new ArrayList<>();
//--------------------Native Ad
NativeAd nativeAd = new NativeAd(getApplicationContext(), "IMG_16_9_LINK#YOUR_FACEBOOK_NATIVE_AD_PLACEMENT_ID_WILL_GOES_HERE"); // IMG_16_9_LINK# denote only testing purpose
nativeAd.setAdListener(new NativeAdListener() {
#Override
public void onMediaDownloaded(Ad ad) {
}
#Override
public void onError(Ad ad, AdError adError) {
}
#Override
public void onAdLoaded(Ad ad) {
for (int i=4; i<mRecyclerViewItems.size()+4; i+=5)
mRecyclerViewItems.add(i, ad);
adapter.notifyDataSetChanged();
}
#Override
public void onAdClicked(Ad ad) {
}
#Override
public void onLoggingImpression(Ad ad) {
}
});
nativeAd.loadAd();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("heroes");
for (int i = 0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
ContentModel item = new ContentModel(
o.getString("name"),
o.getString("about")
);
mRecyclerViewItems.add(item);
}
adapter = new MyAdapter(mRecyclerViewItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Ad are getting overlapped when adding in the container. The solution is to clear the container before adding the ads again.
For example:
AdChoicesView adChoicesView = new AdChoicesView(context, nativeAd, true);
// Clear the container.
adChoicesContainer.removeAllViews()
adChoicesContainer.addView(adChoicesView);
i want to use a checkbox on items in recyclerview i load data from the server 4 by 4 (after seeing the last item he add another 4 new item)but the problem when add new items the checked item change to another item idon't know why i want to save every item checked on SharedPreferences to use them on commande activity
some pictures :
enter image description here
after going dow i found another item checked and the firs one uchecked :
enter image description here
card.xml
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="wrap_content"
android:layout_height="119dp"
android:layout_gravity="center"
android:elevation="3dp"
card_view:cardCornerRadius="1dp"
card_view:cardElevation="4dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt_idArticle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="ID Article : "
android:textColor="#android:color/black"
android:textStyle="normal|bold" />
<TextView
android:id="#+id/txt_reference1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/txt_des"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="5dp"
android:text="Reference : "
android:textColor="#android:color/background_dark"
android:textStyle="normal|bold" />
<TextView
android:id="#+id/txt_des1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txt_prix"
android:layout_alignBottom="#+id/txt_prix"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Prix : "
android:textColor="#android:color/background_dark"
android:textStyle="normal|bold" />
<TextView
android:id="#+id/txt_des"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/txt_prix1"
android:layout_toRightOf="#+id/txt_prix1"
android:text="TextView" />
<TextView
android:id="#+id/txt_prix"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/txt_prix1"
android:layout_toEndOf="#+id/txt_des1"
android:layout_toRightOf="#+id/txt_des1"
android:text="TextView" />
<TextView
android:id="#+id/txt_idArticle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/txt_idArticle1"
android:layout_toRightOf="#+id/txt_idArticle1"
android:text="TextView" />
<TextView
android:id="#+id/txt_reference"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txt_reference1"
android:layout_alignBottom="#+id/txt_reference1"
android:layout_toEndOf="#+id/txt_reference1"
android:layout_toRightOf="#+id/txt_reference1"
android:text="TextView" />
<TextView
android:id="#+id/txt_prix1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/txt_reference1"
android:layout_marginBottom="5dp"
android:text="Designation : "
android:textColor="#android:color/black"
android:textStyle="normal|bold" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="panier"
android:textSize="10sp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
recherche_art.java
package com.example.bacha.pfe.activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.example.bacha.pfe.R;
import com.example.bacha.pfe.adapter.ArticleAdapter;
import com.example.bacha.pfe.classes.Article;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class recherche_art extends AppCompatActivity {
private RecyclerView recyclerView ;
private GridLayoutManager gridLayoutManager;
private ArticleAdapter adapter ;
private List<Article> data_list ;
private String recherche_article;
private ImageButton btnrechArt ;
private EditText arech;
int d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recherche_art);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
btnrechArt = (ImageButton) findViewById(R.id.btnrechArt);
recherche_art.this.onRestart();
btnrechArt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d=0;
Log.d("PFE", String.valueOf(d));
arech= (EditText) findViewById(R.id.eTextRechArt);
data_list = new ArrayList<>();
recherche_article=arech.getText().toString();
load_article_from_server(d);
gridLayoutManager = new GridLayoutManager(recherche_art.this,1);
recyclerView.setLayoutManager(gridLayoutManager);
adapter = new ArticleAdapter(recherche_art.this,data_list);
recyclerView.setAdapter(adapter);
}
});
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(gridLayoutManager.findLastCompletelyVisibleItemPosition() == data_list.size()-1){
d=data_list.size();
load_article_from_server(d);
Log.d("PFE", String.valueOf(d));
}
}
});
}
private void load_article_from_server(final int id) {
AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer,Void, Void>() {
#Override
protected Void doInBackground(Integer... Params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://10.0.2.2/slim/article/"+recherche_article+"/"+id).build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for(int i=0;i<array.length();i++){
JSONObject object = array.getJSONObject(i);
Article data = new Article(/*dd,*/object.getString("id_Article"),object.getString("Reference"),object.getString("Designation"),object.getString("PVTTC"));
data_list.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
System.out.print("End of content");
}
return null ;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
}
activity_recherche_art.xml
<TextView
android:text="Recherche Article :"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="24sp"
android:textStyle="normal|bold"
android:textAlignment="center"
android:textColor="?attr/colorPrimary"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/recherche"
android:id="#+id/btnrechArt"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/eTextRechArt"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/eTextRechArt"
android:layout_below="#+id/textView"
android:layout_toLeftOf="#+id/btnrechArt"
android:layout_toStartOf="#+id/btnrechArt" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
article_view:cardUseCompatPadding="true"
article_view:cardElevation="5dp"
article_view:cardCornerRadius="5dp"
android:scrollbars="vertical"
android:layout_marginTop="18dp"
android:layout_below="#+id/btnrechArt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
Article.java
package com.example.bacha.pfe.classes;
import java.io.Serializable;
/**
* Created by BACHA on 07/03/2017.
*/
public class Article implements Serializable {
private int id;
private String id_Article,Reference,Designation,PVTTC;
public Article(/*int id,*/ String id_Article, String reference, String designation, String PVTTC) {
// this.id = id;
this.id_Article = id_Article;
Reference = reference;
Designation = designation;
this.PVTTC = PVTTC;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getId_Article() {
return id_Article;
}
public void setId_Article(String id_Article) {
this.id_Article = id_Article;
}
public String getReference() {
return Reference;
}
public void setReference(String reference) {
Reference = reference;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public String getPVTTC() {
return PVTTC;
}
public void setPVTTC(String PVTTC) {
this.PVTTC = PVTTC;
}
}
ArticleAdapter.java
package com.example.bacha.pfe.adapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import com.example.bacha.pfe.R;
import com.example.bacha.pfe.activity.ArticleDetail;
import com.example.bacha.pfe.classes.Article;
import java.util.List;
import static com.example.bacha.pfe.R.layout.card;
/**
* Created by BACHA on 08/03/2017.
*/
public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ViewHolder> {
private static Context context ;
private List<Article> my_data ;
public ArticleAdapter(Context context, List<Article> my_data) {
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(card,parent,false);
return new ArticleAdapter.ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.id_Article.setText(my_data.get(position).getId_Article());
holder.Reference.setText(my_data.get(position).getReference());
holder.Designation.setText(my_data.get(position).getDesignation());
holder.PVTTC.setText(my_data.get(position).getPVTTC());
holder.root.setTag(my_data.get(position));
}
#Override
public int getItemCount() {
return my_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView id_Article,Reference,Designation,PVTTC;
View root;
public ViewHolder(View itemView) {
super(itemView);
root = itemView;
root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Article art = (Article)v.getTag();
Intent intent = new Intent(context, ArticleDetail.class);
intent.putExtra("REFERENCE", art.getReference());
context.startActivity(intent);
}
});
id_Article=(TextView) itemView.findViewById(R.id.txt_idArticle);
Reference=(TextView) itemView.findViewById(R.id.txt_reference);
Designation=(TextView) itemView.findViewById(R.id.txt_des);
PVTTC=(TextView) itemView.findViewById(R.id.txt_prix);
}
#Override
public void onClick(View v) {
}
}
}
every one,
I am a beginning learner on android system ,
I create a small app that could get specific data , like foreign exchange rate from bank website ,
this app uses Jsoup , ListView , BaseAdapter etc...
finally , the only problem is the listView has no any display ,
could any one tell me , how to fix it.
Thanks.
Category.java
public class Category
{
String bank_name;
String page_url;
Category(String bank_name,String url)
{
this.bank_name=bank_name;
this.page_url=url;
}
#Override
public String toString()
{
return bank_name;
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity
{
ArrayList<Category> items;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<Category>();
items.add(new Category("台灣銀行","http://rate.bot.com.tw/Pages/Static/UIP003.zh-TW.htm"));
ArrayAdapter<Category> adapter = new ArrayAdapter<Category>(this , android.R.layout.simple_list_item_1 ,items);
ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(adapter);
lv.setOnItemClickListener(itemClick);
}
OnItemClickListener itemClick = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> av , View v , int position , long id)
{
Category category = items.get(position);
Intent intent = new Intent();
intent.setClass(MainActivity.this , RateActivity.class );
intent.putExtra("bank_name", category.bank_name);
intent.putExtra("page_url" , category.page_url);
startActivity(intent);
}
};
RateBean.java
public class RateBean
{
private String currency;
private String cashBuy;
private String cashSold;
private String spotBuy;
private String spotSold;
public RateBean()
{
currency = "";
cashBuy = "";
cashSold = "";
spotBuy = "";
spotSold = "";
}
public RateBean(String [] strArr)
{
this.currency=strArr[0];
this.cashBuy=strArr[1];
this.cashSold=strArr[2];
this.spotBuy=strArr[3];
this.spotSold=strArr[4];
}
public RateBean(String currency , String cashBuy , String cashSold , String spotBuy ,String spotSold)
{
setCurrency(currency);
setCashBuy(cashBuy);
setCashSold(cashSold);
setSpotBuy(spotBuy);
setSpotSold(spotSold);
}
//Currency setter and getter
public void setCurrency(String currency)
{
this.currency = currency ;
}
public String getCurrency()
{
return currency;
}
//Cash buy setter and getter
public void setCashBuy(String cashBuy)
{
this.cashBuy = cashBuy;
}
public String getCashBuy()
{
return cashBuy;
}
//Cash sold setter and getter
public void setCashSold(String cashSold)
{
this.cashSold = cashSold;
}
public String getCashSold()
{
return cashSold;
}
//Spot buy setter and getter
public void setSpotBuy(String spotBuy)
{
this.spotBuy = spotBuy;
}
public String getSpotBuy()
{
return spotBuy;
}
//Spot sold setter and getter
public void setSpotSold(String spotSold)
{
this.spotSold = spotSold;
}
public String getSpotSold()
{
return spotSold;
}
}
RateActivity.java
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
public class RateActivity extends ListActivity
{
Context context ;
ArrayList<RateBean> rateBean_item;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate_show);
TextView updateTime = (TextView)findViewById(R.id.updateTime_textView);
Intent intent = getIntent();
String category = intent.getStringExtra("bank_name");
String page_url = intent.getStringExtra("page_url");
setTitle(category);
context=this;
ConnectThread thread = new ConnectThread(context , rateBean_item , page_url , updateTime);
thread.start();
}
public class ConnectThread extends Thread
{
Context context;
ArrayList<RateBean> rateBean_item;
String page_url ;
TextView updateTime;
RateAdapter adapter;
RateBean rateBean;
int i =0;
public ConnectThread(Context context , ArrayList<RateBean> rateBean_item , String page_url , TextView updateTime )
{
this.context=context;
this.rateBean_item=rateBean_item;
this.page_url=page_url;
this.updateTime=updateTime;
}
#Override
public void run()
{
try
{
String currency="";
String cashBuy="";
String cashSold="";
String spotBuy="";
String spotSold="";
Document doc = Jsoup.connect(page_url).get();
rateBean_item = new ArrayList<>();
String temp=doc.select("td[style=width:326px;text-align:left;vertical-align:top;color:#0000FF;font-size:11pt;font-weight:bold;]").text();
String time=temp.substring(12);
updateTime.setText("匯率更新時間:\n" + time);
for( Element title:doc.select("td.titleLeft"))
{
currency=title.text();
if( i < doc.select("td.decimal").size())
{
cashBuy=doc.select("td.decimal").eq(i++).text();
cashSold=doc.select("td.decimal").eq(i++).text();
spotBuy=doc.select("td.decimal").eq(i++).text();
spotSold=doc.select("td.decimal").eq(i++).text();
rateBean = new RateBean( a , b , c ,d , e );
rateBean_item.add(rateBean);
}
}
adapter = new RateAdapter(context , rateBean_item);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
catch( Exception exception )
{
exception.printStackTrace();
}
}
}
}
RateAdapter.java
import java.util.ArrayList;
import android.util.Log;
import android.widget.BaseAdapter;
import android.view.*;
import android.widget.*;
import android.content.*;
public class RateAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private ArrayList<RateBean> list ;
public RateAdapter()
{
}
public RateAdapter(Context context , ArrayList<RateBean> list )
{
this.inflater = LayoutInflater.from(context);
this.list = list;
}
#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;
}
public static class ViewHolder
{
TextView currency_name;
TextView cash_buy;
TextView cash_sold;
TextView spot_buy;
TextView spot_sold;
}
#Override
public View getView( int position , View convertView , ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = inflater.inflate(R.layout.rate_item , null);
holder = new ViewHolder();
holder.currency_name = (TextView)convertView.findViewById(R.id.xml_currency);
holder.cash_buy = (TextView)convertView.findViewById(R.id.xml_cashBuy);
holder.cash_sold = (TextView)convertView.findViewById(R.id.xml_cashSold);
holder.spot_buy = (TextView)convertView.findViewById(R.id.xml_spotBuy);
holder.spot_sold = (TextView)convertView.findViewById(R.id.xml_spotSold);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
RateBean rateItem = list.get(position);
holder.currency_name.setText(rateItem.getCurrency());
holder.cash_buy.setText(rateItem.getCashBuy());
holder.cash_sold.setText(rateItem.getCashSold());
holder.spot_buy.setText(rateItem.getSpotBuy());
holder.spot_sold.setText(rateItem.getSpotSold());
return convertView;
}
}
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/title_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="銀行查詢選擇"/>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_rate_show.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/updateTime_textView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="updateTime"/>
<Button
android:id="#+id/fresh_button"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="onClick"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/button_fresh"/>
</LinearLayout>>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/currency"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_sold"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_sold"/>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
rate_item.xml
<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:id="#+id/xml_currency"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:textAppearance="?android:attr/textAppearanceLarge"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
</LinearLayout>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Your listview needs a height, it cannot be wrap_content. Give it a height like 500dp or match_parent.