Draw Route in RecyclerView with GoogleMaps - java

I´m trying to draw a route in severel google maps using a reclycerview, but i don't know why doesn´t draw in the first map, but in the other draw correctly.
I´m using Library Volley to get the data.
ReclycerView:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.directions.route.AbstractRouting;
import com.directions.route.Route;
import com.directions.route.RouteException;
import com.directions.route.Routing;
import com.directions.route.RoutingListener;
import com.example.crossonme.Dependencias.Alertas.Alerta;
import com.example.crossonme.Dependencias.DB.EventosItem;
import com.example.crossonme.Login_Register;
import com.example.crossonme.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements OnMapReadyCallback, RoutingListener{
Context context;
public static ArrayList<EventosItem> eventosItemArrayList = new ArrayList<>();
private OnClick mOnClick;
GoogleMap mMap;
MapView mMapView;
int id, Position;
private List<Polyline> polylines = null;
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvNome, tvDescricao, dtData;
OnClick onClick;
MyViewHolder(View view, OnClick onClick) {
super(view);
tvNome = view.findViewById(R.id.evitem_nome);
tvDescricao = view.findViewById(R.id.evitem_descricao);
dtData = view.findViewById(R.id.evitem_data);
mMapView = view.findViewById(R.id.evitem_map);
this.onClick = onClick;
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onClick.onItemClick(getAdapterPosition());
}
}
public MyAdapter(ArrayList<EventosItem> eventosItemArrayList, OnClick onClick) {
this.eventosItemArrayList = eventosItemArrayList;
this.mOnClick = onClick;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.evento_item, null, true);
context = parent.getContext();
return new MyViewHolder(view, mOnClick);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Position = position;
mMapView.onCreate(null );
mMapView.onResume();
Findroutes(eventosItemArrayList.get(Position).getComecoEv(), eventosItemArrayList.get(Position).getFimEv());
Log.e("TAG", ""+ Position );
mMapView.getMapAsync(this);
id = eventosItemArrayList.get(position).getIdEv();
holder.tvNome.setText(eventosItemArrayList.get(position).getNomeEv());
holder.tvDescricao.setText(eventosItemArrayList.get(position).getDescricaoEv());
holder.dtData.setText(eventosItemArrayList.get(position).getDataEv());
}
#Override
public int getItemCount() {
return eventosItemArrayList.size();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap= googleMap;
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(context, R.raw.map_theme));
LatLng Portugal = new LatLng(39.399872, -8.224454);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Portugal, 6));
}
public interface OnClick{
void onItemClick(int position);
}
public void Findroutes(LatLng Start, LatLng End)
{
Routing routing = new Routing.Builder()
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(true)
.waypoints(Start, End)
.key("AIzaSyDzsi_tYj6jhR2CiPx9g-d7EEc8BRb6N7g")
.build();
routing.execute();
}
//Routing call back functions.
#Override
public void onRoutingFailure(RouteException e) {
}
#Override
public void onRoutingStart() {
}
#Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
PolylineOptions polyOptions = new PolylineOptions();
LatLng polylineStartLatLng=null;
LatLng polylineEndLatLng=null;
polylines = new ArrayList<>();
for (int i = 0; i <route.size(); i++) {
if(i==shortestRouteIndex)
{
polyOptions.color(Color.parseColor("#FF8E06"));
polyOptions.width(10);
polyOptions.addAll(route.get(shortestRouteIndex).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylineStartLatLng=polyline.getPoints().get(0);
int k=polyline.getPoints().size();
polylineEndLatLng=polyline.getPoints().get(k-1);
polylines.add(polyline);
}
}
MarkerOptions endMarker = new MarkerOptions();
endMarker.position(polylineEndLatLng);
endMarker.title("Destino");
endMarker.icon(bitmapDescriptorFromVector(context, R.drawable.dt_fim));
mMap.addMarker(endMarker);
MarkerOptions beginMarker = new MarkerOptions();
beginMarker.position(polylineStartLatLng);
beginMarker.title("Inicio");
beginMarker.icon(bitmapDescriptorFromVector(context, R.drawable.dt_inicio));
mMap.addMarker(beginMarker);
}
#Override
public void onRoutingCancelled() {
}
private BitmapDescriptor bitmapDescriptorFromVector(Context context, #DrawableRes int vectorDrawableResourceId) {
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
}
MainActivity
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.crossonme.Dependencias.Alertas.Alerta;
import com.example.crossonme.Dependencias.DB.EventosItem;
import com.example.crossonme.Dependencias.DB.SharedPrefManager;
import com.example.crossonme.Dependencias.DB.URLs;
import com.example.crossonme.Dependencias.DB.User;
import com.example.crossonme.Dependencias.DB.VolleySingleton;
import com.example.crossonme.Dependencias.MyAdapter;
import com.example.crossonme.R;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.JsonObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Eventos extends android.app.Activity implements View.OnClickListener, MyAdapter.OnClick
{
public static ArrayList<EventosItem> eventosItemArrayList = new ArrayList<>();
EventosItem eventosItem;
LatLng Inicio, Fim;
MyAdapter adapter;
#Override
public void onCreate(android.os.Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.eventos);
eventosItemArrayList.clear();
adapter = new MyAdapter(eventosItemArrayList, this);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.ev_ScrollAtual);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setNestedScrollingEnabled(true);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTOS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
String[] latlongIni = object.getString("comeco").split(",");
String[] latlongFim = object.getString("fim").split(",");
Inicio = new LatLng(Double.parseDouble(latlongIni[0]), Double.parseDouble(latlongIni[1]));
Fim = new LatLng(Double.parseDouble(latlongFim[0]), Double.parseDouble(latlongFim[1]));
eventosItem = new EventosItem(object.getString("nome"), object.getString("tipo"),object.getString("descricao"),object.getString("nome_empresa"),object.getInt("id"),object.getString("data"),Inicio,Fim);
eventosItemArrayList.add(eventosItem);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
new Alerta.MensagemAlerta(Eventos.this, "Erro", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View v) {
}
#Override
public void onItemClick(int position) {
new Alerta.MensagemAlerta(Eventos.this, "Erro", String.valueOf(position));
}
}
This is for a project, i have tryed several thing's but not helped.
I hope someone can help me.
David

Related

Failed to parse Json data from the Api

I am trying to get the data (List of Images and Names) from an Api using Volley into a recycler View but due to some reason I am only getting the list of names but unable to fetch the images corresponding to that name, and getting File Not Found Exception
This is the Main Activity
package com.example.bks;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
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.JsonArrayRequest;
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;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG ="tag";
RecyclerView recyclerView;
ProgressBar progressBar;
private List<CropModel> mList;
private cropAdapter cropAdapter;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recycleView);
progressBar=findViewById(R.id.progressBar);
cropAdapter= new cropAdapter(this, mList );
recyclerView.setLayoutManager(new LinearLayoutManager(this));
requestQueue=volleySingleton.getmInstance(this).getRequestQueue();
mList= new ArrayList<>();
fetchData();
}
private void fetchData() {
progressBar.setVisibility(View.VISIBLE);
String url= "http://bharatkrushiseva.in/api_user/getCropType";
JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray= response.getJSONArray("crop");
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject= jsonArray.getJSONObject(i);
String name= jsonObject.getString("crop_name");
String image= jsonObject.getString("crop_image");
CropModel post = new CropModel(name,image);
mList.add(post);
}
cropAdapter adapter = new cropAdapter(MainActivity.this,mList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params= new HashMap<>();
params.put("language","en");
return params;
}
};
requestQueue.add(jsonObjectRequest);
}
}
This is the Adapter Class
package com.example.bks;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class cropAdapter extends RecyclerView.Adapter<cropAdapter.Viewholder> {
private Context context;
private List<CropModel> cropModels;
public cropAdapter(Context context, List<CropModel> cropModels) {
this.context = context;
this.cropModels = cropModels;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.crop_view,parent,false);
return new cropAdapter.Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
CropModel cropModel= cropModels.get(position);
holder.cropName.setText(cropModel.getCrop_name());
Glide.with(context).load(cropModel.getCrop_image()).into(holder.cropImage);
}
#Override
public int getItemCount() {
return cropModels.size() ;
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView cropName;
ImageView cropImage;
public Viewholder(#NonNull View itemView) {
super(itemView);
cropImage=itemView.findViewById(R.id.Cropimage);
cropName=itemView.findViewById(R.id.cropName);
}
}
}
This is my Model Class
package com.example.bks;
public class CropModel {
private String crop_name;
private String crop_image;
public CropModel(String crop_name, String crop_image) {
this.crop_name = crop_name;
this.crop_image = crop_image;
}
public String getCrop_name() {
return crop_name;
}
public void setCrop_name(String crop_name) {
this.crop_name = crop_name;
}
public String getCrop_image() {
return crop_image;
}
public void setCrop_image(String crop_image) {
this.crop_image = crop_image;
}
}
This is the Volley Singleton Class
package com.example.bks;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class volleySingleton {
private RequestQueue requestQueue;
private static volleySingleton mInstance;
private volleySingleton(Context context) {
requestQueue= Volley.newRequestQueue(context.getApplicationContext());
}
public static synchronized volleySingleton getmInstance(Context context){
if(mInstance==null){
mInstance=new volleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){
return requestQueue;
}
}

How to filter what will appear in the recyclerview

I want to filter what gonna appear in the recyclerview
is it possible ?
There is a CalendarView and i want that when someone clicks in a day from the calendarview, it shows itemviews just from that date, for example when someone click in day 15 of the month may, it shows just the tasks that is for that day
I do not know if is it possible.
If someone can help me, it would be great.
Sorry for my english, it's google translate
package com.iza.letfly;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class AdapterDoes extends RecyclerView.Adapter<AdapterDoes.MyViewHolder> {
Context context;
ArrayList<Mydoes> mydoes;
FirebaseFirestore firestore;
FirebaseUser user;
public AdapterDoes(Context c, ArrayList<Mydoes> p){
context = c;
mydoes = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup ViewGroup, int i) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item_does, ViewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.titleDoes.setText(mydoes.get(i).getTitleDoes());
myViewHolder.DescribeDoes.setText(mydoes.get(i).getDescribeDoes());
myViewHolder.dateDoes.setText(mydoes.get(i).getDateDoes());
myViewHolder.alarm.setText(mydoes.get(i).getAlarm());
myViewHolder.checkBox2.setText(mydoes.get(i).getCheck());
myViewHolder.checkBox2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myViewHolder.checkBox2.isChecked()){
myViewHolder.checkBox2.setChecked(false);
}else{
myViewHolder.checkBox2.setChecked(true);
}
}
});
if(myViewHolder.checkBox2.getText().equals("CHECKED")){
myViewHolder.checkBox2.setChecked(true);
myViewHolder.titleDoes.setAlpha(0.4f);
myViewHolder.DescribeDoes.setAlpha(0.5f);
myViewHolder.DescribeDoes.setPaintFlags(myViewHolder.DescribeDoes.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
myViewHolder.titleDoes.setPaintFlags(myViewHolder.titleDoes.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
if(myViewHolder.checkBox2.getText().equals("UNCHECKED")){
myViewHolder.checkBox2.setChecked(false);
}
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
final String getTitleDoes = mydoes.get(i).getTitleDoes();
final String getDescribeDoes = mydoes.get(i).getDescribeDoes();
final String getDateDoes = mydoes.get(i).getDateDoes();
final String getAlarm = mydoes.get(i).getAlarm();
final String getKeyDoes = mydoes.get(i).getKeyDoes();
final String getCheck = mydoes.get(i).getCheck();
#Override
public void onClick(View v) {
Intent i = new Intent(context,Edit_Check.class);
i.putExtra("titleDoes",getTitleDoes);
i.putExtra("DescribeDoes",getDescribeDoes);
i.putExtra("dateDoes",getDateDoes);
i.putExtra("alarm",getAlarm);
i.putExtra("keyDoes",getKeyDoes);
i.putExtra("check", getCheck);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mydoes.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView titleDoes,DescribeDoes,dateDoes, alarm, keyDoes;
CheckBox checkBox2;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
titleDoes = (TextView) itemView.findViewById(R.id.titleDoes);
DescribeDoes = (TextView) itemView.findViewById(R.id.DescribeDoes);
dateDoes = (TextView) itemView.findViewById(R.id.dateDoes);
alarm = (TextView) itemView.findViewById(R.id.alarm);
checkBox2 = (CheckBox) itemView.findViewById(R.id.checkBox2);
}
}
}

How to implement custom listview adapter in tabbed activity?

I am trying to implement the custom list view in tabbed activity for youtube video playing app. I could not able to call custom listview adapter in fragment java class. I have tried to pass getActivity() to custom adapter but the app crashes. If any one know the solution please help me.
The java class are as follows:
HomeFragment.java
package layout;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import in.testapp.app1.R;
public class HomeFragment extends Fragment {
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList();
private final List<String> mFragmentTitleList = new ArrayList();
public Adapter(FragmentManager manager) {
super(manager);
}
public Fragment getItem(int position) {
return (Fragment) this.mFragmentList.get(position);
}
public int getCount() {
return this.mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
this.mFragmentList.add(fragment);
this.mFragmentTitleList.add(title);
}
public CharSequence getPageTitle(int position) {
return (CharSequence) this.mFragmentTitleList.get(position);
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
((TabLayout) view.findViewById(R.id.tablayout)).setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new YouTubeFragment(), "Tab 1");
adapter.addFragment(new SecondFragment(), "Tab 2");
viewPager.setAdapter(adapter);
}
}
YouTubeFragment.java
package layout;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
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 in.testapp.app1.AppUtils;
import in.testapp.app1.ChannelActivity;
import in.testapp.app1.CustomListAdapter;
import in.testapp.app1.R;
import in.testapp.app1.VideoDetails;
public class YouTubeFragment extends Fragment {
String TAG="MainActivity2";
ListView lvVideo;
ArrayList<VideoDetails> videoDetailsArrayList;
CustomListAdapter customListAdapter;
//{youtube_api_key} is replaced by actual key
String URL="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UC5Eg6bkwsdCd-ZlcB3nt1dg&maxResults=25&key={youtube_api_key}";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_you_tube, container, false);
lvVideo=(ListView)view.findViewById(R.id.videoList);
videoDetailsArrayList=new ArrayList<>();
//App crashes here in the beolw line
customListAdapter=new CustomListAdapter(getActivity(),videoDetailsArrayList);
//App crashes here in the above line
showVideo();
return view;
}
private void showVideo() {
RequestQueue requestQueue= Volley.newRequestQueue(getContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("items");
for(int i=1;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
JSONObject jsonsnippet= jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectdefault = jsonsnippet.getJSONObject("thumbnails").getJSONObject("medium");
VideoDetails videoDetails=new VideoDetails();
String videoid=jsonVideoId.getString("videoId");
Log.e(TAG," New Video Id" +videoid);
videoDetails.setURL(jsonObjectdefault.getString("url"));
videoDetails.setVideoName(jsonsnippet.getString("title"));
videoDetails.setVideoDesc(jsonsnippet.getString("description"));
videoDetails.setVideoId(videoid);
videoDetailsArrayList.add(videoDetails);
}
lvVideo.setAdapter(customListAdapter);
customListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
CustomListAdapter.java
package in.testapp.app1;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter {
Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private LayoutInflater inflater;
ArrayList<VideoDetails> singletons;
public CustomListAdapter(Activity activity, ArrayList<VideoDetails> singletons) {
this.activity = activity;
this.singletons = singletons;
}
public int getCount() {
return this.singletons.size();
}
public Object getItem(int i) {
return this.singletons.get(i);
}
public long getItemId(int i) {
return (long) i;
}
public View getView(int i, View convertView, ViewGroup viewGroup) {
if (this.inflater == null) {
this.inflater = (LayoutInflater) this.activity.getLayoutInflater();
// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = this.inflater.inflate(R.layout.videolist, null);
}
if (this.imageLoader == null) {
this.imageLoader = AppController.getInstance().getImageLoader();
}
NetworkImageView networkImageView = (NetworkImageView) convertView.findViewById(R.id.video_image);
final TextView imgtitle = (TextView) convertView.findViewById(R.id.video_title);
final TextView imgdesc = (TextView) convertView.findViewById(R.id.video_descriptio);
final TextView tvURL=(TextView)convertView.findViewById(R.id.tv_url);
final TextView tvVideoID=(TextView)convertView.findViewById(R.id.tv_videoId);
((LinearLayout) convertView.findViewById(R.id.asser)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(view.getContext(), VideoActivity.class);
intent.putExtra("videoId",tvVideoID.getText().toString());
view.getContext().startActivity(intent);
}
});
VideoDetails singleton = (VideoDetails) this.singletons.get(i);
networkImageView.setImageUrl(singleton.getURL(), this.imageLoader);
tvVideoID.setText(singleton.getVideoId());
imgtitle.setText(singleton.getVideoName());
imgdesc.setText(singleton.getVideoDesc());
return convertView;
}
}
VideoDeatils.java
package in.testapp.app1;
public class VideoDetails {
String VideoName;
String VideoDesc;
String URL;
String VideoId;
public void setVideoName(String VideoName){
this.VideoName=VideoName;
}
public String getVideoName(){
return VideoName;
}
public void setVideoDesc(String VideoDesc){
this.VideoDesc=VideoDesc;
}
public String getVideoDesc(){
return VideoDesc;
}
public void setURL(String URL){
this.URL=URL;
}
public String getURL(){
return URL;
}
public void setVideoId(String VideoId){
this.VideoId=VideoId;
}
public String getVideoId(){
return VideoId;
}
}

Blank Screen Shows after search from database (Android)

When i tap search donor then it shows blank screen in listview i don't know why This is the response that i get back from server
This is my custom adapter code:
package com.example.kamran.ebloodbank;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Kamran on 4/12/2017.
*/
public class DonorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataSet> donorItems;
public DonorAdapter(Activity activity,List<DataSet> donorItems) {
this.activity = activity;
this.donorItems = donorItems;
}
#Override
public int getCount() {
return donorItems.size();
}
#Override
public Object getItem(int location) {
return donorItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.donor_search_list_theme, null);
TextView nameTextView = (TextView) convertView.findViewById(R.id.donor_name);
TextView areaTextView = (TextView) convertView.findViewById(R.id.donor_area);
DataSet d = donorItems.get(position);
nameTextView.setText(d.getName());
areaTextView.setText(d.getArea());
return convertView;
}
}
This is my model code:
package com.example.kamran.ebloodbank;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
/**
* Created by Kamran on 4/12/2017.
*/
public class DataSet {
private String name;
private int area;
public void setArea(int area) {
this.area = area;
}
public void setName(String name) {
this.name = name;
}
public int getArea() {
return area;
}
public String getName() {
return name;
}
}
This is my first activity code:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.android.volley.AuthFailureError;
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.example.kamran.ebloodbank.data.BloodContract.BloodEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindDonor extends AppCompatActivity {
Spinner bloodgroup;
Spinner area;
String findDonorUrl = "https://wwwkamranalitk.000webhostapp.com/findDonor.php";
int mBlood = BloodEntry.BLOOD_GROUP_A_POS;
int mArea = BloodEntry.DONOR_AREA_MALIR;
Button searchButton;
RequestQueue requestQueue;
StringRequest request;
JSONObject jsonObject;
JSONArray result;
private List<DataSet> donorList = new ArrayList<DataSet>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_donor);
bloodgroup = (Spinner) findViewById(R.id.bloodspinnerfinddonor);
area = (Spinner) findViewById(R.id.areaSpinner);
searchButton = (Button) findViewById(R.id.searchDonor);
setupSpinnerBlood();
setupSpinnerArea();
requestQueue = Volley.newRequestQueue(getApplicationContext());
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, findDonorUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObject = new JSONObject(response);
result = jsonObject.getJSONArray("result");
JSONObject donorData = result.getJSONObject(0);
DataSet donorSet = new DataSet();
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("bloodgroup", String.valueOf(mBlood));
parameters.put("area", String.valueOf(mArea));
return parameters;
}
};
requestQueue.add(request);
}
});
}
private void setupSpinnerBlood() {
ArrayAdapter bloodGroupSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.blood_group, android.R.layout.simple_spinner_item);
bloodGroupSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
bloodgroup.setAdapter(bloodGroupSpinnerAdapter);
bloodgroup.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blood_apos))) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
} else if (selection.equals((getString(R.string.blood_bpos)))) {
mBlood = BloodEntry.BLOOD_GROUP_B_POS;
} else if (selection.equals(getString(R.string.blood_opos))) {
mBlood = BloodEntry.BLOOD_GROUP_O_POS;
} else if (selection.equals((getString(R.string.blood_oneg)))) {
mBlood = BloodEntry.BLOOD_GROUP_O_NEG;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
}
});
}
private void setupSpinnerArea() {
ArrayAdapter areaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.area, android.R.layout.simple_spinner_item);
areaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
area.setAdapter(areaSpinnerAdapter);
area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.donor_area_malir))) {
mArea = BloodEntry.DONOR_AREA_MALIR;
} else if (selection.equals(getString(R.string.donor_area_defence))) {
mArea = BloodEntry.DONOR_AREA_DEFENCE;
} else if (selection.equals(getString(R.string.donor_area_korangi))) {
mArea = BloodEntry.DONOR_AREA_KORANGI;
} else if (selection.equals(getString(R.string.donor_area_johar))) {
mArea = BloodEntry.DONOR_AREA_JOHAR;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mArea = BloodEntry.DONOR_AREA_MALIR;
}
});
}
}
and This is the code in which data will be shown:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DonorSearchList extends AppCompatActivity {
private String mArea;
private List<DataSet> donorList = new ArrayList<DataSet>();
private ListView listView;
private DonorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donor_search_list);
listView = (ListView) findViewById(R.id.donorListView);
adapter = new DonorAdapter(this, donorList);
listView.setAdapter(adapter);
}
}
You need to transfer data from the search to list activity.
Try something like this:
public class bridge {
public static List<DataSet> donorList = new ArrayList<DataSet>();
}
Then, in the class FindDonor:
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
//here put this line
bridge.donarList = donarList;
//rest code
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
Then, in the DonorSearchList class:
adapter = new DonorAdapter(this, bridge.donorList);

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

Categories

Resources