Sort Array in Recyclerview (Java, Android) - java

package com.example.sander.app;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
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.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.Collections;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleFrame extends Fragment {
ArrayList<String> names = new ArrayList<>();
ArrayList<String> cPoints = new ArrayList<>();
ArrayList<String> code = new ArrayList<>();
ArrayList<String> latitude = new ArrayList<>();
ArrayList<String> longitude = new ArrayList<>();
GPSTracker gps;
ArrayList<Double> dLatitude = new ArrayList<>();
ArrayList<Double> dLongitude = new ArrayList<>();
ArrayList<Float> distance = new ArrayList<>();
ArrayList<Data> dataList = new ArrayList<>();
public RecycleFrame() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_view, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Integer id = item.getItemId();
if(id == R.id.action_A_Z){
//Sorts the garages from A to Z
Collections.sort(names);
//Refreshes the fragment
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
else if(id == R.id.action_Z_A){
//Sorts the garages from Z to A
Collections.reverse(names);
//Refreshes the fragment
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
else if (id == R.id.short_distance){
Collections.sort(distance);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_recycle, container, false);
final RecyclerView VRecyclerView = (RecyclerView) view.findViewById(R.id.rv_recycler_view);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/parkgarage_all.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("");
if(names.size() == 0) {
for (int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
dataList.add(new Data(jsonObject.getString("parkgarage_name"), jsonObject.getString("charging_capcatity"), jsonObject.getDouble("langitude"),
jsonObject.getDouble("longitude"), jsonObject.getString("parkgarage_code"), distance.get(i)));
//names.add(jsonObject.getString("parkgarage_name"));
//cPoints.add(jsonObject.getString("charging_capacity"));
//code.add(jsonObject.getString("parkgarage_code"));
//latitude.add(jsonObject.getString("langitude"));
//longitude.add(jsonObject.getString("longitude"));
dLatitude.add(jsonObject.getDouble("langitude"));
dLongitude.add(jsonObject.getDouble("longitude"));
}
}
} catch (JSONException ex){}
gps = new GPSTracker(getActivity());
//check if gps is on
if(!gps.canGetLocation()){
gps.showSettingsAlert();
}
Location myLocation = new Location("");
myLocation.setLatitude(gps.getLatitude());
myLocation.setLongitude(gps.getLongitude());
for(int z = 0; z < latitude.size(); z++){
Location parkingGarage = new Location("");
parkingGarage.setLatitude(dLatitude.get(z));
parkingGarage.setLongitude(dLongitude.get(z));
distance.add(myLocation.distanceTo(parkingGarage)/1000);
}
VRecyclerView.setHasFixedSize(true);
//RecycleAdapter adapter = new RecycleAdapter(names, cPoints, code, latitude, longitude, distance);
RecycleAdapter adapter = new RecycleAdapter(dataList);
VRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
VRecyclerView.setLayoutManager(llm);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
return view;
}
}
This is my RecycleFrame code, below is my RecyclerAdapter code
package com.example.sander.app;
import android.app.Fragment;
import android.media.Image;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
ArrayList<Data> ArrayListData;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView TextViewNames;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
TextViewNames = (TextView) v.findViewById(R.id.text_view_names);
}
}
public RecycleAdapter(ArrayList<Data> names){
ArrayListData = names;
//ArrayCharging= cPoints;
//ArrayCode = code;
//ArrayLatitude = latitude;
//ArrayLongitude = longitude;
//ArrayDistance = distance;
}
#Override
public RecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_card_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.TextViewNames.setText(String.valueOf(ArrayListData.get(position)));
//holder.TextViewNames.setText("Naam: " + ArrayNames.get(position));
//holder.TextViewCharging.setText("Oplaadpunten: " + ArrayCharging.get(position));
//holder.TextViewCode.setText("Code: " + ArrayCode.get(position));
//holder.TextViewLatitude.setText("Positie: (" + ArrayLatitude.get(position) + ", " + ArrayLongitude.get(position)+ ")");
//holder.TextViewDistance.setText(String.valueOf(ArrayDistance.get(position)));
//holder.mImageView.setImageResource(R.drawable.ic_local_parking_black_24dp);
}
#Override
public int getItemCount() { return ArrayListData.size(); }
}
What I want is the following: I want to be able to press a item in a 3 dot menu and sort it from A to Z, Z to A & sort in on distance to the certain location. Sorting works correct (except for the distance but I can fix that myself). The only problem is that when I sort from A to Z or Z to A or distance the code & name & cPoints are not matching anymore. Does anyone know how to fix this?

As per you code you have multiple arraylist for name, distance, cpoint and when you sort one list the mapping between sorted list and all others list lost.
To fix this you have to keep the mapping between all whenever you sort based on attribute.
Better create a custom class with fields like name, distance, cpoint.... and whenever you sort on one attribute sort the list of custom objects. By this way mapping between multiple list is not lost.
There is another inefficient approach to solve the problem. But I will not recommend.
Try to sort the 4 array simultaneously based on one key. Like if you want to sort based on name, try to implement the selection sort on name array and on swapping swap elements in all four array to maintain the mapping between all four. Performance of sorting is not good in this solution. To implement this refer How to sort multiple ArrayLists based off order of another?

Related

Implementing if statement directly to Arraylist [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I am using RecyclerView and CardView. I want the sysytem to choose which ImageView to display by circumstances from the JSON. How should I do it? I implemented the if statement but it seems like the statement is not working. Could someone give me an advice. This is my first time writing a parsing program. I don't know much about it.
package com.morimoku.location_activity;
import android.app.DownloadManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class favaoritesFragment extends Fragment {
public static TextView data;
private RecyclerView.Adapter mAdapter;
private RequestQueue mQueue;
private RecyclerView.LayoutManager mLayoutManager;
int i1;
int i2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_favorites,container,false);
mQueue = Volley.newRequestQueue(getActivity());
ArrayList<Status> statusArrayList = new ArrayList<>();
statusArrayList.add(new Status(R.drawable.ic_action_name,"Line 1", (i1 == 0)?
R.drawable.ic_check_box_black_24dp: R.drawable.ic_warning_black_24dp));
statusArrayList.add(new Status(R.drawable.ic_action_name,"Line 2", (i2 == 0)?
R.drawable.ic_check_box_black_24dp: R.drawable.ic_warning_black_24dp));
mAdapter = new RecyclerAdapter(statusArrayList);
RecyclerView mRecyclerView = view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));//listView.setAdapter(adapter);
mRecyclerView.setAdapter(mAdapter);
return view;
}
private void jsonParse() {
String url = ("URL");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("odpt.TrainInformation:Line 1");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject negishi = jsonArray.getJSONObject(i);
String negishis = negishi.getString("odpt:trainInformationText");
if (negishis.equals( "operating normally")) {
i1 = 0;
} else {
i1 = 1;
}
}
JSONArray jsonArray1 = response.getJSONArray("odpt.TrainInformation:Line 2");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject negishi2 = jsonArray.getJSONObject(i);
String negishis2 = negishi2.getString("odpt:trainInformationText");
if (negishis2 .equals( "operating normally")) {
i2 = 0;
} else {
i2 = 1;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
}}
statusArrayList.add(new Status(R.drawable.ic_action_name,"keihin",
(i1 == 0? R.drawable.common_google_signin_btn_icon_dark_focused:
R.drawable.common_google_signin_btn_icon_dark_focused));

Get an error : com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray

I try to get data from the database via API but the recyclerview doesn't display anything and the log displays an error.
This is my code
Fragment
package com.example.hp.retailmakanan;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.hp.retailmakanan.Model.MenuModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FragHome extends Fragment {
RecyclerView recV;
BottomNavigationView top_navigation;
HomeAdapter listAdapter;
List<MenuModel> listMenu= new ArrayList<>();
private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment sfragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_noodle:
recV.setAdapter(listAdapter);
break;
case R.id.nav_beverage:
recV.setAdapter(listAdapter);
break;
case R.id.nav_toping:
recV.setAdapter(listAdapter);
break;
case R.id.nav_cari:
recV.setAdapter(listAdapter);
break;
}
return false;
}
};
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.act_home, container, false);
recV = (RecyclerView) v.findViewById(R.id.rec_ramen);
getData();
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recV.setLayoutManager(layoutManager);
listAdapter = new HomeAdapter(listMenu, getActivity());
recV.setAdapter(listAdapter);
top_navigation = (BottomNavigationView) v.findViewById(R.id.top_nav);
top_navigation.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
return v;
}
this is the code that i used to get data
private void getData() {
String url ="https://waggish-requisition.000webhostapp.com/GetAllMenu.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listMenu.clear();
for (int i = 0; i < response.length(); i++) {
try {
Log.d("menu",response.toString());
JSONObject jsonObject = response.getJSONObject(i);
String id_menu = jsonObject.getString("id");
String nama_menu = jsonObject.getString("nama_menu");
String deskripsi = jsonObject.getString("deskripsi");
int harga = jsonObject.getInt("harga");
MenuModel menus = new MenuModel(id_menu,nama_menu,deskripsi,harga);
listMenu.add(menus);
System.out.println(menus);
//Toast.makeText(this,"Download data "+i,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Log.d("menu",e.toString());
}
listAdapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
}
Adapter
package com.example.hp.retailmakanan;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.hp.retailmakanan.Model.MenuModel;
import java.util.Arrays;
import java.util.List;
public class HomeAdapter extends RecyclerView.Adapter {
private List<MenuModel> menus;
private Context context;
public HomeAdapter(List<MenuModel> menus, Context context) {
this.context = context;
this.menus = menus;
//System.out.println(menus);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recv_desain, viewGroup, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int pos) {
}
#Override
public int getItemCount() {
return menus.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mText,txt2, txt3, txtQty;
ImageView img;
Button btnMin, btnPlus;
int x;
public ListViewHolder(View itemView){
super(itemView);
mText = itemView.findViewById(R.id.text_item);
txt2 = itemView.findViewById(R.id.text_item2);
txt3 = itemView.findViewById(R.id.textView3);
img = itemView.findViewById(R.id.image_item);
btnMin = itemView.findViewById(R.id.buttonMinMenu);
btnPlus = itemView.findViewById(R.id.buttonPlusMenu);
txtQty = itemView.findViewById(R.id.textQtyMenu);
itemView.setOnClickListener(this);
}
public void bindView (int pos){
x=0;
MenuModel model = menus.get(pos);
mText.setText(model.getNama_menu());
txt2.setText(model.getDeskripsi());
txt3.setText(model.getHarga());
//img.setImageResource(DataMenu.picture[pos]);
txtQty.setText(String.valueOf(x));
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
txtQty.setText(String.valueOf(x));
}
});
btnMin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x--;
if (x<=0){
x=0;
txtQty.setText(String.valueOf(x));
}else if (x>0){
txtQty.setText(String.valueOf(x));
}
}
});
}
#Override
public void onClick(View v) {
}
}
}
And this is my php code
<?php
require_once('connection.php');
//public $mServerName;
//public $mConnectionInfo;
//public $conn;
//Create query to retrieve all contacts
$query = "SELECT * FROM menu";
$stmt = mysqli_query($conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$menus= array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = mysqli_fetch_array($stmt)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$menu= array("id" => $row['id_menu'],
"deskripsi" => $row['Deskripsi'],
"nama_menu" => $row['nm_menu'],
"harga" => $row['harga_menu'],
"ImageUrl" =>$row['gambar']
);
//Add the contact to the contacts array
array_push($menus, $menu);
}
//Echo out the contacts array in JSON format
echo json_encode($menus);
}
?>
I changed JSONObject to JSONArray, but that caused many other errors. I am a beginner please help me. I really don't know what to do :(

App keeps on crashing when I click in element of recycleview

Why is this app is not working properly when I click on the each item of the recycle view Toast of the position of the item appears but when I click each item(cardview) to open a new activity app crash. I don't know what is wrong.
GalleryFragment.java
package com.example.kiran.cr7;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
/** * A simple {#link Fragment} subclass. */ public class GalleryFragment extends Fragment implements Adapter.OnCardClickListner {
public GalleryFragment() {
// Required empty public constructor
}
private RecyclerView mrecycleview;
private CardView mcardview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
mrecycleview = (RecyclerView)view.findViewById(R.id.recycle_view);
mcardview = (CardView)view.findViewById(R.id.card_view);
//improve performance
mrecycleview.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(view.getContext());
mrecycleview.setLayoutManager(manager);
ArrayList<Item> itemlist = dummies();
//set adapter // Adapter adapter = new Adapter(view.getContext(),itemlist); // mrecycleview.setAdapter(adapter); // adapter.setOnCardClickListner(this);
Adapter adapter = new Adapter(view.getContext(),itemlist);
mrecycleview.setAdapter(adapter);
adapter.setOnCardClickListner(this);
return view;
}
private ArrayList<Item> dummies() {
ArrayList<Item> list = new ArrayList<>();
for (int i = 0; i < 6; i++) {
if (i == 0) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://wallpapercave.com/wp/sIggTrG.jpg";
list.add(item);
} else if (i == 1) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://i2.wp.com/www.footballwood.com/wp-content/uploads/2015/01/Ronaldo-Best-Wallpapers.jpg";
list.add(item);
} else if (i == 2) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://www.magazinefuse.com/wp-content/uploads/2015/09/7-i476725-1024x640.jpg";
list.add(item);
} else if (i == 3) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "https://i.ytimg.com/vi/SwHv6xGGBBQ/maxresdefault.jpg";
list.add(item);
}else if (i == 4) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "https://i.ytimg.com/vi/WrCfkR4Qcns/maxresdefault.jpg";
list.add(item);
}
else if (i == 5) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://images.latinpost.com/data/images/full/101477/cristiano-ronaldo-real-madrid.jpg";
list.add(item);
}
}
return list;
}
#Override
public void OnCardClicked(View view, int position) {
Log.d("OnClick", "Card Position" + position);
Toast.makeText(getContext(),"click"+position,Toast.LENGTH_SHORT).show();
Intent in= new Intent(view.getContext(),Detail.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(in);
} }
Adapter.java
package com.example.kiran.cr7;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private RecyclerView mRecyclerView;
private Context context;
private ArrayList<Item> itemlist;
OnCardClickListner onCardClickListner;
public Adapter(Context context, ArrayList<Item> itemlist){
this.context = context;
this.itemlist = itemlist;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycle_view);
ViewHolder viewholder = new ViewHolder(view);
return viewholder;
}
//bind views with data
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Item item = itemlist.get(position);
//get element form your dataset at this position
//replace the contents of the view with that element
Picasso.with(context)
.load(item.img)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(holder.cardimage);
holder.cardtext.setText(item.text);
holder.card_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onCardClickListner.OnCardClicked(v,position);
Intent in = new Intent(v.getContext(), Detail.class);
in.putExtra("item",item);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//context.startActivity(in);
}
});
}
#Override
public int getItemCount() {
if(itemlist != null){
return itemlist.size();
}
return 0;
}
//provide the reference to the views for each data item
//ViewHolder class
//since it is static it uses only single memory so protect memory leak : a design pattern for android
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView card_view;
public TextView cardtext;
public ImageView cardimage;
//connects which view belongs to which layout
public ViewHolder(View itemView) {
super(itemView);
card_view = (CardView)itemView.findViewById(R.id.card_view);
cardtext = (TextView)itemView.findViewById(R.id.cardtext);
cardimage = (ImageView)itemView.findViewById(R.id.cardimage);
}
#Override
public void onClick(View view) {
}
}
public interface OnCardClickListner {
void OnCardClicked(View view, int position);
}
public void setOnCardClickListner(OnCardClickListner onCardClickListner) {
this.onCardClickListner = onCardClickListner;
}
}
Detail
package com.example.kiran.cr7;
import android.app.DownloadManager; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Detail extends AppCompatActivity implements Adapter.OnCardClickListner {
private ImageView detailimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
detailimage = (ImageView)findViewById(R.id.detailimage);
}
#Override
public void OnCardClicked(View view, int position) {
Log.d("OnClick", "Card Position" + position);
if(getIntent().getSerializableExtra("item") != null){
Item i = (Item)getIntent().getSerializableExtra("item");
Picasso.with(this)
.load(i.img)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(detailimage);
}
} }
You don't need to use OnCardClicked in detail.java activity. Use serializable to send data from one activity from another. Use OnCardClicked.onBindViewHolder to send data from one activity to another.
package com.example.kiran.cr7;
import android.app.DownloadManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
public class Test extends Activity {
private ImageView detailimage;
private Button download;
DownloadManager downloadManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
download = (Button) findViewById(R.id.Download);
detailimage = (ImageView) findViewById(R.id.detailimage);
final Animation animAlpha = AnimationUtils.loadAnimation(this,R.anim.anim_alpha);
if (getIntent().getSerializableExtra("item") != null) {
final Item i = (Item) getIntent().getSerializableExtra("item");
Picasso.with(this)
.load(i.img)
.resize(500,600)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(detailimage);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//Toast.makeText(Test.this, "Network Connection available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Test.this, "No Network Connection", Toast.LENGTH_LONG).show();
}
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.startAnimation(animAlpha);
downloadManager =(DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(i.img);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
}
});
}
}
}

Populate recycle adapter from controller class

I'm trying to populate a recycle adapter from a controller class, to split the logic in the app. But I can't seem to get it working.. Do to the request is running on another thread, the view is not updated before it is shown. What am I doing wrong ?
FragmentClass:
package lassebjoerklund.homecontrol.views.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.controllers.FridgeController;
import lassebjoerklund.homecontrol.decorations.DividerItemDecoration;
import lassebjoerklund.homecontrol.model.Product;
import lassebjoerklund.homecontrol.utils.FragmentUtil;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverView extends Fragment {
private final FridgeController fridgeController = new FridgeController();
private RecyclerView recyclerView;
private LinkedList<String> types;
private FridgeFragmentOverViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_layout, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productOverviewRecycleView);
recyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new FridgeFragmentOverViewAdapter(fridgeController.getProductsTypes());
recyclerView.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
fridgeController.refresh(getContext(), adapter);
}
}
Controller Class:
package lassebjoerklund.homecontrol.controllers;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
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;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.interfaces.OnSucsess;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeController implements OnSucsess {
private RequestQueue rQueue;
private ArrayList<Product> products;
private List<String> productsTypes;
public ArrayList<Product> getProducts() {
return products;
}
public List<String> getProductsTypes() {
return productsTypes;
}
public void refresh(Context context, final FridgeFragmentOverViewAdapter adapter) {
String fetchProducts = "http://87.52.28.25:900/index.php";
rQueue = Volley.newRequestQueue(context);
final JsonArrayRequest getProductsRequest = new JsonArrayRequest(fetchProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
products = new ArrayList<>();
productsTypes = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) response.get(i);
String barcode = jsonObject.getString("code");
String name = jsonObject.getString("name");
String ex_date = jsonObject.getString("ex_date");
String add_date = jsonObject.getString("add_date");
String type = jsonObject.getString("type");
Product product = new Product(barcode, name, ex_date, add_date, type);
products.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (products.size() != 0) {
for (int i = 0; i < products.size(); i++) {
if (!productsTypes.contains(products.get(i).getType())) {
productsTypes.add(products.get(i).getType());
}
}
}
getProductsOnsucsess(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQueue.add(getProductsRequest);
}
#Override
public void getProductsOnsucsess(FridgeFragmentOverViewAdapter adapter) {
adapter.refreshAdapter(productsTypes);
}
}
Adapter:
package lassebjoerklund.homecontrol.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverViewAdapter extends RecyclerView.Adapter {
private List<String> types;
public FridgeFragmentOverViewAdapter(List<String> types) {
this.types = types;
}
#Override
public int getItemCount() {
return 0;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_overview_card_layout, null);
return new ProductsGroupedHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
public class ProductsGroupedHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTypeOfProduct, tvCount, tvExpired;
public ProductsGroupedHolder(View itemView) {
super(itemView);
tvTypeOfProduct = (TextView) itemView.findViewById(R.id.tvTypeOfProduct);
tvCount = (TextView) itemView.findViewById(R.id.tvCount);
tvExpired = (TextView) itemView.findViewById(R.id.tvExpired);
}
#Override
public void onClick(View v) {
}
}
public void refreshAdapter(List<String> types) {
if(this.types != null) {
this.types.clear();
this.types = types;
notifyDataSetChanged();
}else {
this.types = types;
notifyDataSetChanged();
}
}
}
Try calling:
adapter.notifyDataSetChanged();
after updating it.
Edit 1:
Return actual size of adapter items in getItemCount() as #prathamkesarkar said.
Simple looks like you have set the getItemType() method return 0.
That method determines how much item your RecyclerView have.
#Override
public int getItemCount() {
return type.size();
}

Unable to get the card index

I am trying to get the index of the card which is active on the screen with this code.
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.glass.app.Card;
import com.google.android.glass.touchpad.Gesture;
import com.google.android.glass.touchpad.GestureDetector;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import com.google.api.services.mirror.model.TimelineItem;
public class MainActivity extends Activity {
private GestureDetector mGestureDetector;
String identifysource;
int cardindex;
private static ArrayList<Card> sourceCard = new ArrayList<Card>();
private ArrayList<String> sourceText = new ArrayList<String>(Arrays.asList("PCWorld", "TechCrunch"));
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for(int i=0;i<sourceText.size();i++)
{
System.out.println("whats up");
Card card = new Card(this);
identifysource=sourceText.get(i);
card.setText(identifysource);
sourceCard.add(card);
}
System.out.println(this);
mGestureDetector = createGestureDetector(this);
CardScrollView csvCardsView = new CardScrollView(this);
csaAdapter cvAdapter = new csaAdapter();
csvCardsView.setAdapter(cvAdapter);
csvCardsView.activate();
setContentView(csvCardsView);
cardindex=csvCardsView.getSelectedItemPosition();
}
private static class csaAdapter extends CardScrollAdapter
{
#Override
public int findIdPosition(Object id)
{
return -1;
}
#Override
public int findItemPosition(Object item)
{
return sourceCard.indexOf(item);
}
#Override
public int getCount()
{
return sourceCard.size();
}
#Override
public Object getItem(int position)
{
return sourceCard.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return sourceCard.get(position).toView();
}
}
}
This results in the same cardindex output every time i.e 0
I tried getting the position with cvAdapter.findItemPosition() but that also returns -1 everytime.
Implement the onClickListener from the CardScrollView. Within you'll be able to determine which item was selected.

Categories

Resources