Android Firebase -Cards not displaying in RecyclerView and NullPointerException - java

I am trying to build an app where users can post something with image and description which is included individually in CardView in RecyclerView. So I have have got three problems
1.When id(userId) is used as child and then I post the data it gets replaced with old data instead of adding new data (if the posts has multiple children with same ID then my cards should display but the ID is getting replaced every time)
Cards aren't showing when a post is added.(When there are posts in
Firebase database)
If by default there are no posts in Firebase database
NullPointerException to the method getDesc() is generated even
though I have put null checks.
Earlier for storing posts the child I used was id(userId), but the posts got replaced instead of adding a new one so I used a random String generator and tried to fetch information from it instead.
HomeFragment.java
public class HomeFragment extends Fragment {
private RecyclerView rv;
private TextView username,date,desc;
private CircleImageView postImage;
private ImageView postBigImage;
private CardView postCard;
private List<PostActivity> postItems;
private DatabaseReference dr;
private StorageReference sr;
private FirebaseUser user;
//FirebaseRecyclerAdapter<PostActivity, userViewHolder> fra;
private PostAdapter pa;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
sr = FirebaseStorage.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
String id = user.getUid();
AddPost ap = new AddPost();
dr =
FirebaseDatabase.getInstance().getReference().child("Posts")
.child(ap.getUni());
postItems = new ArrayList<>();
pa = new PostAdapter(postItems);
rv =view.findViewById(R.id.rvPostItems);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
rv.setAdapter(pa);
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
//postItems.add(ds.getValue(PostActivity.class));
PostActivity pa =dataSnapshot.getValue(PostActivity.class);
postItems.add(pa);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
PostAdapter.java
package com.pappu5.navigation;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public List<PostActivity> postItems;
public PostAdapter(List<PostActivity> postItems) {
this.postItems = postItems;
}
#NonNull
#Override
public PostAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_items,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final PostAdapter.ViewHolder holder, int position) {
String descTe = postItems.get(position).getDesc();
if(descTe!=null) {
holder.setDesc(descTe);
}else{
String def = "This is NULL";
holder.setDesc(def);
}
}
#Override
public int getItemCount() {
return postItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView desc;
private View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDesc(String descText){
desc = mView.findViewById(R.id.postDesc);
desc.setText(descText);
}
}
}
AddPost.java
package com.pappu5.navigation;
public class AddPost extends AppCompatActivity {
private Toolbar toolbar;
private ImageView postImage;
private Button postButton;
private EditText postDesc;
private static final int gallery_no = 1;
private ProgressDialog pd;
private FirebaseUser user;
private StorageReference sr;
private DatabaseReference dr;
private Uri postImageUri = null;
private Bitmap compressor;
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
String uni = getSaltString();
public String getUni(){
return this.uni;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_post);
toolbar = findViewById(R.id.postBar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Add New Post !");
postImage = findViewById(R.id.postImage);
postDesc = findViewById(R.id.inputDesc);
postButton = findViewById(R.id.post);
sr = FirebaseStorage.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
String id = user.getUid();
dr = FirebaseDatabase.getInstance().getReference().child("Posts").child(uni);
dr.keepSynced(true);
postImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery,"Select Image"),gallery_no);
}
});
postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String desc = postDesc.getText().toString();
if(!TextUtils.isEmpty(desc) && postImageUri!=null ){
pd = new ProgressDialog(AddPost.this);
pd.setTitle("Uploading..");
pd.setMessage("Please Wait ..");
pd.setCanceledOnTouchOutside(false);
pd.show();
final String id = user.getUid();
File thumb = new File(postImageUri.getPath());
try {
compressor = new Compressor(AddPost.this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(75)
.compressToBitmap(thumb);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
compressor.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final byte[] thumb_byte = baos.toByteArray();
final StorageReference path = sr.child("Post_Images").child(id + ".jpg");
final StorageReference thumb_nail = sr.child("Post_Images").child("Thumb_Nails").child(id+".jpg");
path.putFile(postImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
path.putFile(postImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
path.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String down_url = uri.toString();
UploadTask uploadTask = thumb_nail.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
thumb_nail.putFile(postImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
thumb_nail.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String thumb_down_url = uri.toString();
Map <String,Object> update_map = new HashMap<>();
update_map.put("image", down_url);
update_map.put("thumb_image", thumb_down_url);
update_map.put("desc",desc);
update_map.put("timestamp", date);
dr.updateChildren(update_map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(AddPost.this, "Uploaded !", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AddPost.this,MainActivity.class);
startActivity(intent);
finish();
pd.dismiss();
} else {
Toast.makeText(AddPost.this, "Error in uploading thumbnail!", Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
});
}
});
}
});
}
});
}
});
}
});
} else {
Toast.makeText(AddPost.this, "Error!", Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
});
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == gallery_no && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri).setAspectRatio(1, 1).setMinCropWindowSize(500, 500)
.start(AddPost.this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
postImageUri = result.getUri();
postImage.setImageURI(postImageUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
post_items.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/postCard"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.56"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/postImage"
android:layout_width="65dp"
android:layout_height="65dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:src="#drawable/default_avatar"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/postUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Username"
android:textStyle="bold"
app:layout_constraintStart_toEndOf="#+id/postImage"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/postDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Datee"
android:textStyle="italic"
app:layout_constraintStart_toEndOf="#+id/postImage"
app:layout_constraintTop_toBottomOf="#+id/postUsername" />
<ImageView
android:id="#+id/postBigImage"
android:layout_width="0dp"
android:layout_height="256dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/postImage"
tools:srcCompat="#tools:sample/avatars[3]" />
<TextView
android:id="#+id/postDesc"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="TextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/postBigImage" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>

To fix NullPointerException check null value of postItems.get(position) instead of postItems.get(position).getDesc() i.e.
#Override
public void onBindViewHolder(#NonNull final PostAdapter.ViewHolder holder, int position) {
if(postItems.get(position) != null) {
String descTe = postItems.get(position).getDesc();
holder.setDesc(descTe);
} else {
String def = "This is NULL";
holder.setDesc(def);
}
}
Also, you are initializing PostAdapter with blank List of postItems, i.e.
postItems = new ArrayList<>();
pa = new PostAdapter(postItems);
and Items are added later inSide onDataChange() method of the ValueEventListener. you must update your PostAdapter for the new updated List postItems and notify the adapter. like this.
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
//postItems.add(ds.getValue(PostActivity.class));
PostActivity pa =dataSnapshot.getValue(PostActivity.class);
postItems.add(pa);
}
pa.notifyDataSetChanged();
}
And for Cards not being displayed can you share the code of post_items.xml file.

(Posted an answer on behalf of the question author).
I solved every problem by removing whole PostAdapter class and then implementing FireebaseRecyclerAdapter in the HomeFragment itself ! My cards are displaying like charm now ! Thanks to everyone who replied to me here and helped me.

Related

How to download a image from url in recylerview?

I have made a meme app, which fetches image url from an API and i m parsing them and showing in recyler view using Glide , in my item layout i have two buttons one for sharing and one for download Image , i want when user clicks the download button the images get download to the user phone.
Help me how i can implement this.
MyAdapter class
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
ArrayList<Model> modelArrayList;
public Adapter(Context context, ArrayList<Model> modelArrayList) {
this.context = context;
this.modelArrayList = modelArrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String url = modelArrayList.get(position).getUrl();
holder.setImage(url);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sharing = new Intent (Intent.ACTION_SEND);
sharing.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharing.setType("text/plain");
String subject = "Hey Man just look at this coll meme click the link " +url;
sharing.putExtra(Intent.EXTRA_TEXT,subject);
context.startActivity(Intent.createChooser(sharing,"Shring using"));
}
});
holder.buttonDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
Button button,buttonDownload;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
button = itemView.findViewById(R.id.button);
buttonDownload = itemView.findViewById(R.id.btn_download);
}
void setImage(String link){
Glide.with(context).load(link).into(imageView);
}
}
}
My model class
public class Model {
String url;
public Model(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
My item_layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="8dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background"
tools:ignore="VectorDrawableCompat" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="104dp"
android:layout_marginLeft="104dp"
android:layout_marginBottom="28dp"
android:text="Share"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="71dp"
android:layout_marginRight="71dp"
android:layout_marginBottom="28dp"
android:text="Download"
android:textColor="#0B0B0B"
app:backgroundTint="#12E71A"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
My mainactivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
Adapter adapter;
ArrayList<Model> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recylerview_id);
arrayList = new ArrayList<>();
String url = "https://meme-api.herokuapp.com/gimme/30";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("memes");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String url = jsonObject.getString("url");
Model m = new Model(url);
arrayList.add(m);
}
adapter = new Adapter(MainActivity.this,arrayList);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
}
Glide allows to load a Bitmap.
you can save Bitmap to file, and then just pass file path to another screen.
Here you can find detailed tutorial, how to store image to file with Glide library:
https://medium.com/#akshayranagujjar/how-to-save-image-to-storage-using-glide-in-android-fa26c842f212
And don't forget about storage permissions.

Listview is not visible on Activity

I can't see my listview on Activity after adding a list item dynamically on floatingAction button click.
When I click on floatingActionButton, a new activity opens up which takes my input, after clicking on the save button ReminderActivity opens up but did not show input passed added in the list.
My motive is to add a new item in the listView every time after getting data from ReminderInputDataActivity which opens when I click on floating action button.
public class ReminderActivity extends AppCompatActivity {
private ListView lvReminder;
private FloatingActionButton floatingActionButton;
private ArrayList<Reminder> reminders;
public static final String REMINDER_INPUT = "reminder_input";
private ReminderCustomAdapter reminderListAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
reminders = new ArrayList<>();
lvReminder = (ListView) findViewById(R.id.lvReminder);
Intent getIntent = getIntent();
String[] reminderInput = getIntent.getStringArrayExtra(REMINDER_INPUT);
if (reminderInput != null) {
reminders.add(new Reminder(reminderInput[0], reminderInput[1], reminderInput[2]));
}
reminderListAdapter = new ReminderCustomAdapter(this, R.layout.listview_reminder, reminders);
lvReminder.setAdapter(reminderListAdapter);
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ReminderActivity.this, ReminderInputDataActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
if (reminderListAdapter != null) {
reminderListAdapter.notifyDataSetChanged();
}
}
}
public class Reminder {
private String title;
private String date;
private String time;
public Reminder() {
}
public Reminder(String title, String date, String time) {
this.title = title;
this.date = date;
this.time = time;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
public class ReminderInputDataActivity extends AppCompatActivity {
private EditText etReminderTitle;
private Button btDate, btTime;
public static final String REMINDER_INPUT = "reminder_input";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input_reminder);
etReminderTitle = (EditText) findViewById(R.id.etReminderTitle);
btDate = (Button) findViewById(R.id.btReminderDate);
btTime = (Button) findViewById(R.id.btReminderTime);
btDate.setText(new SimpleDateFormat("E, dd MMM yyyy", Locale.getDefault()).format(new Date()));
btTime.setText(new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date()));
Button btRemSave = (Button) findViewById(R.id.btRemSave);
Button btRemCancel = (Button) findViewById(R.id.btRemCancel);
final Intent intent = new Intent(ReminderInputDataActivity.this, ReminderActivity.class);
btRemSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] userInput = new String[3];
userInput[0] = etReminderTitle.getText() != null ? etReminderTitle.getText().toString() : "";
userInput[1] = btDate.getText().toString();
userInput[2] = btTime.getText().toString();
Bundle bundle = new Bundle();
bundle.putStringArray(REMINDER_INPUT, userInput);
intent.putExtras(bundle);
startActivity(intent);
}
});
btRemCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
}
}
public class ReminderCustomAdapter extends BaseAdapter {
private final Context mContext;
private int resource;
private ArrayList<Reminder> reminderList;
public ReminderCustomAdapter(Context mContext, int resource, ArrayList<Reminder> reminderList) {
this.mContext = mContext;
this.resource = resource;
this.reminderList = reminderList;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(resource, null);
TextView tvInputRemTitle = (TextView) view.findViewById(R.id.tvInputRemTitle);
TextView tvInputRemDate = (TextView) view.findViewById(R.id.tvInputRemDate);
TextView tvInputRemTime = (TextView) view.findViewById(R.id.tvInputRemTime);
Reminder reminder = reminderList.get(position);
tvInputRemTitle.setText(reminder.getTitle());
tvInputRemDate.setText(reminder.getDate());
tvInputRemTime.setText(reminder.getTime());
return view;
}
}
activity_reminder.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/lvReminder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_margin="16dp"
android:backgroundTint="#color/colorPrimaryDark"
android:contentDescription="#string/reminder"
android:src="#android:drawable/ic_input_add"
app:shapeAppearanceOverlay="#style/fab_3_rounded" />
</RelativeLayout>
listview_reminder.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/tvInputRemTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Title"
android:textSize="15sp" />
<TextView
android:id="#+id/tvInputRemDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvInputRemTitle"
android:hint="Date" />
<TextView
android:id="#+id/tvInputRemTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvInputRemTitle"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/tvInputRemDate"
android:hint="Time" />
</RelativeLayout>
I am new to android and started creating a basic project, for the above issue I watched some videos and go through articles but unable to get the issue here.
Please help. Thanks in Advance!
Problem is due to this code
final Intent intent = new Intent(ReminderInputDataActivity.this, ReminderActivity.class);
btRemSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] userInput = new String[3];
userInput[0] = etReminderTitle.getText() != null ? etReminderTitle.getText().toString() : "";
userInput[1] = btDate.getText().toString();
userInput[2] = btTime.getText().toString();
Bundle bundle = new Bundle();
bundle.putStringArray(REMINDER_INPUT, userInput);
intent.putExtras(bundle);
startActivity(intent);
}
});
Here you start ReminderActivity again which calls onCreate method of this activity, where you have added reminders = new ArrayList<>(); which recreate this arraylist with no data.
To Avoid this you can implement two solutions.
Implement interface.
StartActivityForResult.
Easiest solution would be StartActivityForResult.
For Example,
Intent intent = new Intent(ReminderActivity.this,ReminderInputDataActivity.class);
startActivityForResult(intent, 2);
and in the same activity implement the callback.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}
From ReminderInputDataActivity send data back to this class like this.
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity

Glide is not loading image from firebase

I am working on a firebase project but I am facing a problem like when I upload an image on firebase I am not getting it in my original apk. I upload an image on firebase and save its URL in the firebase database and then when I load it with the Recycler view and Glide library it stuck on the placeholder image but did not load the original image. Can anyone help me to solve this problem I provided my source code below:-
EventActivity:-
public class EventActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter imageAdapter;
private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("NotifyImages");
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
mUploads.add(upload);
}
imageAdapter = new ImageAdapter(EventActivity.this, mUploads);
mRecyclerView.setAdapter(imageAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Upload class:-
public class Upload {
private String mName;
private String mImageUri;
public Upload() {
}
public Upload(String name, String ImageUri) {
if (name.trim().equals("")) {
name = "No name";
}
mName = name
;
mImageUri = ImageUri;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageUri() {
return mImageUri;
}
public void setImageUri(String ImageUri) {
mImageUri = ImageUri;
}
}
Image Adapter:-
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
// Glide.with(mContext)
// .load(uploadCurrent.getImageUri())
// .centerCrop()
// .into(holder.imageView);
Glide.with(mContext)
.load(uploadCurrent.getImageUri())
.placeholder(R.mipmap.ic_launcher_round)
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_upload);
}
}
}
activity_event.xml:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
ImageItem.xml:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="8dp"
android:layout_marginBottom="80dp"
android:text="Name"
android:textColor="#color/ColorRed"
android:textSize="20sp" />
<ImageView
android:id="#+id/image_upload"
android:layout_width="match_parent"
android:layout_height="300dp"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
You can easily copy my code and test it. Please answer me if you find a solution.
Please make changes in your UploadFile() Function :
fireRef.putFile(ImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
}
} , 5000);
Toast.makeText(MainActivity.this, "Upload Successfull", Toast.LENGTH_SHORT).show();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Upload upload = new Upload(mainEditTextNotify.getText().toString().trim(),
downloadUrl.toString());
String uploadId = mDataRef.push().getKey();
mDataRef.child(uploadId).setValue(upload);
}
})
The above code will provide you proper uri of image which you can store inside Database.
It will provide you proper uri which will help to load images in Glide.
But i suggest to store filepath from Firebase Storage. Cause if uri token expires then you need generate uri token and change with old one.

How to change color and font on ListView after reading firebase DB

How to handle the problem of showing empty view for ListView because I don't know which data I have to put when I'm reading data from my firebase DB and display it in the ListView. and I'm using CustomListAdapter to change font color and the background color of ListView
Note: I'm reading data from firebase database and display it in ListView, any solution
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private static final int HERO_COUNT = 12;
private Context context;
private List<String> items;
public CustomListAdapter(Context context) {
this.context = context;
items = new ArrayList<>();
}
#Override
public int getCount() {
return HERO_COUNT;
}
#Override
public String getItem(int position) {
if (position >= 0 && position < items.size()) {
return items.get(position);
}
return "";
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.custom_list, null, false);
TextView text = (TextView) mView.findViewById(R.id.textView);
//textView.setTextColor(Color.BLUE);
text.setText(getItem(position));
if (items.isEmpty()) {
// Set holder color
} else {
text.setTextColor(Color.WHITE);
int color = Color.argb(200, 255, 64, 64);
text.setBackgroundColor(color);
}
}
return mView;
}
public void updateList(List<String> updatedItems) {
items.clear();
items.addAll(updatedItems);
notifyDataSetChanged();
}
}
ViewDatabase.java
public class ViewDatabase extends AppCompatActivity {
private static final String TAG = "ViewDatabase";
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_database_layout);
mListView = (ListView) findViewById(R.id.listview);
CustomListAdapter adapter = new CustomListAdapter(this);
mListView.setAdapter(adapter);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
// userID = user.getUid();
userID = "";
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMessage("Successfully signed in.");
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMessage("Successfully signed out.");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
DailyInfo uInfo = new DailyInfo();
uInfo.setHero1(ds.child(userID).getValue(DailyInfo.class).getHero1()); //set the name1
uInfo.setHero2(ds.child(userID).getValue(DailyInfo.class).getHero2()); //set the name2
uInfo.setHero3(ds.child(userID).getValue(DailyInfo.class).getHero3()); //set the name3
uInfo.setHero4(ds.child(userID).getValue(DailyInfo.class).getHero4()); //set the name4
uInfo.setHero5(ds.child(userID).getValue(DailyInfo.class).getHero5()); //set the name5
uInfo.setHero6(ds.child(userID).getValue(DailyInfo.class).getHero6()); //set the name6
uInfo.setHero7(ds.child(userID).getValue(DailyInfo.class).getHero7()); //set the name7
uInfo.setHero8(ds.child(userID).getValue(DailyInfo.class).getHero8()); //set the name8
uInfo.setHero9(ds.child(userID).getValue(DailyInfo.class).getHero9()); //set the name9
uInfo.setHero10(ds.child(userID).getValue(DailyInfo.class).getHero10()); //set the name10
uInfo.setHero11(ds.child(userID).getValue(DailyInfo.class).getHero11()); //set the name11
uInfo.setHero12(ds.child(userID).getValue(DailyInfo.class).getHero12()); //set the name12
//display all the information
Log.d(TAG, "showData: Hero1: " + uInfo.getHero1());
Log.d(TAG, "showData: Hero2: " + uInfo.getHero2());
Log.d(TAG, "showData: Hero3: " + uInfo.getHero3());
Log.d(TAG, "showData: Hero4: " + uInfo.getHero4());
Log.d(TAG, "showData: Hero5: " + uInfo.getHero5());
Log.d(TAG, "showData: Hero6: " + uInfo.getHero6());
Log.d(TAG, "showData: Hero7: " + uInfo.getHero7());
Log.d(TAG, "showData: Hero8: " + uInfo.getHero8());
Log.d(TAG, "showData: Hero9: " + uInfo.getHero9());
Log.d(TAG, "showData: Hero10: " + uInfo.getHero10());
Log.d(TAG, "showData: Hero11: " + uInfo.getHero11());
Log.d(TAG, "showData: Hero12: " + uInfo.getHero12());
ArrayList<String> array = new ArrayList<>();
array.add(uInfo.getHero1());
array.add(uInfo.getHero2());
array.add(uInfo.getHero3());
array.add(uInfo.getHero4());
array.add(uInfo.getHero5());
array.add(uInfo.getHero6());
array.add(uInfo.getHero7());
array.add(uInfo.getHero8());
array.add(uInfo.getHero9());
array.add(uInfo.getHero10());
array.add(uInfo.getHero11());
array.add(uInfo.getHero12());
/* ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);*/
if (mListView.getAdapter() instanceof CustomListAdapter) {
((CustomListAdapter) mListView.getAdapter()).updateList(array);
mListView.setBackgroundColor(ContextCompat.getColor(mListView.getContext(), R.color.category_colors));
}
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
/**
* customizable toast
*
* #param message
*/
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
view_database_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvUserInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Information"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp"/>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</LinearLayout>
custom_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
</LinearLayout>
DailyInfo.java
public class DailyInfo {
private String hero1;
private String hero2;
private String hero3;
private String hero4;
private String hero5;
private String hero6;
private String hero7;
private String hero8;
private String hero9;
private String hero10;
private String hero11;
private String hero12;
public DailyInfo(){
}
public String getHero1() {
return hero1;
}
public void setHero1(String hero1) {
this.hero1 = hero1;
}
public String getHero2() {
return hero2;
}
public void setHero2(String hero2) {
this.hero2 = hero2;
}
public String getHero3() {
return hero3;
}
public void setHero3(String hero3) {
this.hero3 = hero3;
}
public String getHero4() {
return hero4;
}
public void setHero4(String hero4) {
this.hero4 = hero4;
}
public String getHero5() {
return hero5;
}
public void setHero5(String hero5) {
this.hero5 = hero5;
}
public String getHero6() {
return hero6;
}
public void setHero6(String hero6) {
this.hero6 = hero6;
}
public String getHero7() {
return hero7;
}
public void setHero7(String hero7) {
this.hero7 = hero7;
}
public String getHero8() {
return hero8;
}
public void setHero8(String hero8) {
this.hero8 = hero8;
}
public String getHero9() {
return hero9;
}
public void setHero9(String hero9) {
this.hero9 = hero9;
}
public String getHero10() {
return hero10;
}
public void setHero10(String hero10) {
this.hero10 = hero10;
}
public String getHero11() {
return hero11;
}
public void setHero11(String hero11) {
this.hero11 = hero11;
}
public String getHero12() {
return hero12;
}
public void setHero12(String hero12) {
this.hero12 = hero12;
}
}
You're creating the adapter after receiving the response on ValueEventListener:
CustomListAdapter adapter = new CustomListAdapter(ViewDatabase.this , R.layout.custom_list , mList);
ListView mListView= findViewById(R.id.listview);
mListView.setAdapter(adapter);
Instead of that, set the adapter on ViewDatabase within onCreate for instance and set the color based on that initial state.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_database_layout);
mListView = findViewById(R.id.listview);
CustomListAdapter adapter = new CustomListAdapter(this);
mListView.setAdapter(adapter);
//[...]
}
And, instead of creating the adapter, update it:
private void showData(DataSnapshot dataSnapshot) {
//[...]
if (mListView.getAdapter() instanceof CustomListAdapter) {
((CustomListAdapter)mListView.getAdapter()).updateList(array);
}
}
You could also replace ArrayAdapter with BaseAdapter as the extended class:
public class CustomListAdapter extends BaseAdapter {
private static final int HERO_COUNT = 12;
private Context context;
private List<String> items;
public CustomListAdapter(Context context) {
this.context = context;
items = new ArrayList<>();
}
#Override
public int getCount() {
return HERO_COUNT;
}
#Override
public String getItem(int position) {
if (position >= 0 && position < items.size()) {
return items.get(position);
}
return "";
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.custom_list, null, false);
}
//Bind view content here
//TODO associate holder to tag
return mView;
}
public void updateList(List<String> updatedItems) {
items.clear();
items.addAll(updatedItems);
notifyDataSetChanged();
}
}
}
EDIT:
In order to have a default background color on the list to be changed when the values are received, you can set the default color on the main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvUserInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Information"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp"/>
<ListView
android:id="#+id/listview"
android:background="#color/empty_color"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</LinearLayout>
And then change it when the values are received:
private void showData(DataSnapshot dataSnapshot) {
//[...]
if (mListView.getAdapter() instanceof CustomListAdapter) {
((CustomListAdapter)mListView.getAdapter()).updateList(array);
listView.setBackgroundColor(ContextCompat.getColor(listView.getContext(), R.color.loaded_color));
}
}
If what you want is to change the row color then you'll need to change the row layout on getView when the string is empty.
EDIT 2
Specified where to make the view changes
You are modifying the view only when it hasn't been created before, which won't be the case the next time around, that's it, when the data is available. So, based on your code (should consider including a holder btw):
public View getView(int position, View v, ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.custom_list, null, false);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
text.setText(getItem(position));
if (items.isEmpty()) {
// Set holder color
} else {
text.setTextColor(Color.WHITE);
}
return mView;
}

Code to play list of mp4 url fetching from the server in android studio

I know these questions are previously asked by so many peoples but for my requirement, I'm not able to get the solution.
I have created the main class there I implemented the method to fetch a list of video name's and placing it in to in recycler view. So when the user clicks on any particular video name getting the URL.So the problem is how can I implement the logic to play that clicked item.
MainActivity :
public class MainActivity extends AppCompatActivity {
//ProgressDialog mDialog;
VideoView videoView;
Button btnPlayPause;
//ImageButton btnPlayPause;
String videoURL;
ProgressDialog pd;
private final String url_video = "url://xyz.com/abc/video";
private static final int RECOVERY_REQUEST = 1;
private RecyclerView recyclerView;
private VideoListAdapter videoListAdapter;
private ArrayList<VideoDetail> videoDetailsArrayList = new ArrayList<>();
private View.OnClickListener videoItemClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
videoURL = view.getTag().toString();
//setVideo();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlayPause= (Button) findViewById(R.id.btn_play_pause);
videoView = (VideoView) findViewById(R.id.videoView1);
setAdapter();
loadRequestList();
}
private void loadRequestList() {
if (isNetworkAvailable()) {
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Loading data...");
pd.show();
//ProgressUtils.getInstance(this).show("Loding Video List........");
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_video, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//ProgressUtils.getInstance(MainActivity.this).cancel();
pd.dismiss();
if (TextUtils.isEmpty(response)) {
return;
}
VideoDetailsModel videoDetailsModel = VideoResponseHandler.getVideoListDetails(response);
// System.out.println("printing Data of video"+videoDetailsModel.getDetails());
if (videoDetailsModel == null) {
return;
}
if (videoDetailsModel.getDetails() == null) {
return;
}
//System.out.println("printing list3\n");
videoListAdapter.setVideoList((ArrayList<VideoDetail>) videoDetailsModel.getDetails());
//System.out.println("printing list video\n");
} catch (Throwable e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
//ProgressUtils.getInstance(MainActivity.this).cancel();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}else{
builderDialog(MainActivity.this).show();
}
}
private AlertDialog.Builder builderDialog(MainActivity listVideoActivity) {
AlertDialog.Builder builder = new AlertDialog.Builder(listVideoActivity);
builder.setTitle("No Internet Connection");
builder.setMessage("You Need To Have Mobile Data or Wifi to access this. Press OK to Exit");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(MainActivity.this,MainActivity.class));
//finish();
}
});
return builder;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activityNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activityNetworkInfo != null && activityNetworkInfo.isConnected();
}
private void setAdapter() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerVideo);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
videoListAdapter = new VideoListAdapter(videoDetailsArrayList,videoItemClickListener);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(videoListAdapter);
}
}
Adapter Class look like this :
public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.MyViewHandler> {
private ArrayList<VideoDetail> videoDetailArrayList = new ArrayList<>();
private View.OnClickListener videoItemClickListener;
public VideoListAdapter(ArrayList<VideoDetail> videoDetailArrayList, View.OnClickListener videoItemClickListener) {
this.videoDetailArrayList = videoDetailArrayList;
this.videoItemClickListener = videoItemClickListener;
}
#Override
public MyViewHandler onCreateViewHolder (ViewGroup parent, int viewType){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_video_list, parent, false);
return new MyViewHandler(view);
}
#Override
public void onBindViewHolder (MyViewHandler holder,int position){
if (videoDetailArrayList == null) {
return;
}
VideoDetail videoDetail = videoDetailArrayList.get(position);
if (videoDetail == null) {
return;
}
if (holder instance_of MyViewHandler) {
if (TextUtils.isEmpty(videoDetail.getFileName())) {
return;
}
holder.tvVideo.setText(videoDetail.getFileName());
holder.tvVideo.setTag(videoDetail.getFilePath());
holder.videoImage.setTag(videoDetail.getFilePath());
if (videoItemClickListener != null) {
holder.tvVideo.setOnClickListener(videoItemClickListener);
holder.videoImage.setOnClickListener(videoItemClickListener);
}
}
}
#Override
public int getItemCount() {
return videoDetailArrayList.size();
}
public class MyViewHandler extends RecyclerView.ViewHolder {
private final TextView tvVideo;
private final ImageView videoImage;
public MyViewHandler(View itemView) {
super(itemView);
tvVideo = (TextView) itemView.findViewById(R.id.tvVideo);
videoImage = (ImageView) itemView.findViewById(R.id.videoImage);
}
}
public void setVideoList(ArrayList<VideoDetail> videoDetails) {
if (videoDetails != null) {
this.videoDetailArrayList = videoDetails;
}
notifyDataSetChanged();
}
}
activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="com.xyz.videoviewengineersdream.MainActivity">
<VideoView
android:id="#+id/videoView1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn_play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:onClick="videoPlay"
android:clickable="true"
android:layout_below="#+id/videoView1"
android:layout_centerHorizontal="true"
android:background="#color/colorPrimary"
android:padding="10dp"
android:layout_marginTop="10dp"
android:textColor="#FFF"
android:textStyle="bold"
android:textSize="16dp"/>
<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:layout_below="#+id/btn_play_pause"
android:id="#+id/viewView"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerVideo"
android:layout_below="#+id/viewView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
you have already created VideDetail class
private ArrayList<VideoDetail> videoDetailArrayList = new ArrayList<>()
just Add videourl fields to the VideoDetail class then you can directly get url on button click like below in onBindViewHolder
final VideDetail videodetail = videolist.get(position);
holder.yourbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = videdetail.getvideourl();
// play video with the url you got
}
});

Categories