Volley array request проблемы при использовании в fragment
Доброго времени суток.
Хочу получить результат обращения к api сайта. Вот фрагмент в котором я это хочу сделать. заполнения cardView попросту не происходит. permissions для доступа в интернет включены. возможно я не правильно написал метод makeRequestCapCoin, прошу помочь с решением Вот пример
{
"data": [
{
"id": "bitcoin",
"rank": "1",
"symbol": "BTC",
"name": "Bitcoin",
"supply": "17193925.0000000000000000",
"maxSupply": "21000000.0000000000000000",
"marketCapUsd": "119150835874.4699281625807300",
"volumeUsd24Hr": "2927959461.1750323310959460",
"priceUsd": "6929.8217756835584756",
"changePercent24Hr": "-0.8101417214350335",
"vwap24Hr": "7175.0663247679233209"
},
{
"id": "ethereum",
"rank": "2",
"symbol": "ETH",
"name": "Ethereum",
"supply": "101160540.0000000000000000",
"maxSupply": null,
"marketCapUsd": "40967739219.6612727047843840",
"volumeUsd24Hr": "1026669440.6451482672850841",
"priceUsd": "404.9774667045200896",
"changePercent24Hr": "-0.0999626159535347",
"vwap24Hr": "415.3288028454417241"
}
]
}
public class FragmentTwo extends Fragment {
private Context mContext;
private ArrayList<String> cRank = new ArrayList<>();
private ArrayList<String> cName = new ArrayList<>();
private ArrayList<String> cSymbol = new ArrayList<>();
private ArrayList<String> cPrice = new ArrayList<>();
public FragmentTwo() {
// Required empty public constructor
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_two, container, false);
makeRequestCapCoin();
RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
recyclerView.setLayoutManager(linearLayoutManager);
CustomAdapter customAdapter = new CustomAdapter(mContext, cRank, cName, cSymbol, cPrice);
recyclerView.setAdapter(customAdapter);
return root;
}
private void makeRequestCapCoin() {
RequestQueue queue = Volley.newRequestQueue(mContext);
String jsonUrl = "https://api.coincap.io/v2/assets?limit=5";
StringRequest stringRequest = new StringRequest(
Request.Method.GET, jsonUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i > jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
cRank.add(object.getString("rank"));
cName.add(object.getString("name"));
cSymbol.add(object.getString("symbol"));
cPrice.add(object.getString("priceUsd"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
}
}
Адаптер
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList<String> cRank;
ArrayList<String> cName;
ArrayList<String> cSymbol;
ArrayList<String> cPrice;
private Context context;
public CustomAdapter(Context context, ArrayList<String> cRank, ArrayList<String> cName, ArrayList<String> cSymbol, ArrayList<String> cPrice) {
this.context=context;
this.cRank = cRank;
this.cName = cName;
this.cSymbol = cSymbol;
this.cPrice = cPrice;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// infalte the item Layout
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_top, parent, false);
MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
// set the data in items
holder.cRank.setText(cRank.get(position));
holder.cName.setText(cName.get(position));
holder.cSymbol.setText(cSymbol.get(position));
holder.cPrice.setText(cPrice.get(position));
}
@Override
public int getItemCount() {
return cRank.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView cRank, cName, cSymbol, cPrice;// init the item view's
public MyViewHolder(View itemView) {
super(itemView);
// get the reference of item view's
cRank = (TextView) itemView.findViewById(R.id.cryptoRank);
cName = (TextView) itemView.findViewById(R.id.cryptoName);
cSymbol = (TextView) itemView.findViewById(R.id.cryptoSymbol);
cPrice = (TextView) itemView.findViewById(R.id.cryptoPrice);
}
}
}
fragment_two.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#D81B60"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
item_top.xml
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#039BE5">
<ImageView
android:id="@+id/icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="10dp"
android:src="@drawable/ic_whatshot" />
<RelativeLayout
android:id="@+id/containerInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_toEndOf="@+id/icon">
<TextView
android:id="@+id/cryptoRank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/cryptoName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_toEndOf="@+id/cryptoRank"
android:text="Bitcoin"
android:textColor="#8BC34A"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/cryptoSymbol"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_toEndOf="@+id/cryptoName"
android:text="BTC"
android:textColor="#FFEB3B"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:paddingBottom="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/containerInfo"
android:layout_marginTop="10dp"
android:layout_toEndOf="@+id/icon">
<TextView
android:id="@+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Цена в USD: "
android:textColor="#fff" />
<TextView
android:id="@+id/cryptoPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/price"
android:maxLength="6"
android:text="4645.63874"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
dependency
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.android.material:material:1.0.0'
implementation "androidx.cardview:cardview:1.0.0"
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation 'com.android.volley:volley:1.1.1'
}
Ответы (1 шт):
Автор решения: Дмитрий Левицкий
→ Ссылка
Кажется, вы просто забыли уведомить адаптер об обновлении данных. Попробуйте добавить adapter.notifyDataSetChanged() в onResponse после цикла. – ЮрийСПб
Все изменения в коде отмечены комментариями
public class FragmentTwo extends Fragment {
private Context mContext;
private ArrayList<String> cRank = new ArrayList<>();
private ArrayList<String> cName = new ArrayList<>();
private ArrayList<String> cSymbol = new ArrayList<>();
private ArrayList<String> cPrice = new ArrayList<>();
public FragmentTwo() {
// Required empty public constructor
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_two, container, false);
RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
recyclerView.setLayoutManager(linearLayoutManager);
final CustomAdapter customAdapter = new CustomAdapter(Objects.requireNonNull(getActivity()).getApplicationContext(), cRank, cName, cSymbol, cPrice);
recyclerView.setAdapter(customAdapter);
// JsonArrayRequest modified !!! The previous method "makeRequestCapCoin()" has been deleted.
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
String jsonUrl = "https://api.myjson.com/bins/15rrou";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
jsonUrl,
null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
System.out.println(jsonObject);
cRank.add(jsonObject.getString("market_cap_rank"));
cName.add(jsonObject.getString("name"));
cSymbol.add(jsonObject.getString("symbol"));
cPrice.add(jsonObject.getString("current_price"));
}
// Added notify for Adapter
customAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonArrayRequest);
return root;
}
}