How to control URL of anything from Firebase database - java

I am making my college news feed app using Firebase, in which there is a list of items having an image, title and description. I want that if a user clicks on the list item, it automatically downloads the PDF file related to that news. So in the future, if I want to add some more news, How can I add the PDF to that new item? , or if I want to replace the old PDF link to new PDF link then how I can do that ?. Basically, I want a control on the firebase database So that I can change anytime the PDF link in my database.
Main Activity:
package com.namy86.dtu_saforum;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
public class Main2Activity extends AppCompatActivity {
private RecyclerView mBloglist;
FirebaseDatabase database;
DatabaseReference mReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mBloglist=(RecyclerView) findViewById(R.id.blog);
mBloglist.setHasFixedSize(true);
mBloglist.setLayoutManager(new LinearLayoutManager(this));
database=FirebaseDatabase.getInstance();
mReference=database.getReference();
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<ModelClass,BlogViewHolder> firebaseRecyclerAdapter=new
FirebaseRecyclerAdapter<ModelClass,BlogViewHolder>(ModelClass.class,R.layout.design_row,BlogViewHolder.class,mReference){
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, ModelClass model,int position){
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(),model.getImage(),model.getFile());
}
};
mBloglist.setAdapter(firebaseRecyclerAdapter);
}
public class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
Context ctx;
TextView post,description;
DownloadManager dm;
ImageView postImage;
public BlogViewHolder(View itemView){
super(itemView);
mView=itemView;
// itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//// Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://dtu.ac.in/Web/notice/2017/dec/file1219.pdf"));
////
//// Intent browserChooserIntent=Intent.createChooser(browserIntent,"Choose Browser Of Your Choice");
//// view.getContext().startActivity(browserChooserIntent);
//
//// TextView post2=(TextView)mView.findViewById(R.id.titletext);
//// TextView description2=(TextView)mView.findViewById(R.id.titletext2);
//// ImageView postImage2=(ImageView)mView.findViewById(R.id.images);
////
//// post2.setText(String.valueOf(post));
//// description2.setText(String.valueOf(description));
//// Picasso.with(ctx).load(String.valueOf(postImage)).into(postImage2);
//
// dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
// Uri uri = Uri.parse("https://firebasestorage.googleapis.com/v0/b/fir-dtu.appspot.com/o/Kaushik%20and%20Kaushik.pdf?alt=media&token=45d80725-dd37-4825-8c7d-23b0dbd50d17");
// DownloadManager.Request request = new DownloadManager.Request(uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// Long reference = dm.enqueue(request);
//
//
//
//
//
//
//
//
// }
// });
}
public void setTitle(String title){
TextView post=(TextView)mView.findViewById(R.id.titletext);
post.setText(title);
}
public void setDesc(String desc){
TextView description=(TextView)mView.findViewById(R.id.titletext2);
description.setText(desc);
}
public void setImage(Context ctx, String image, final String file){
ImageView postImage=(ImageView)mView.findViewById(R.id.images);
Picasso.with(ctx).load(image).into(postImage);
postImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(file);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = dm.enqueue(request);
}
});
}
}
}

Related

The data is getting stored in firebase real time database but the data is not getting displayed in the recycler view of the UI

I am new to android and I couldn't solve this issue. The terminal says that the string cannot be converted into purchasemodel.
But I am getting the data from purchasemodel only.
I don't know where the mistake is happening.
The data is getting stored in the realtime database but could not display in the recycler view UI.
Terminal error statements
com.google.firebase.database.DatabaseException: Can't convert object of type
java.lang.String to type com.example.books.purchasemodel
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.example.books.AdminBookDetails$2.onChildAdded(AdminBookDetails.java:99)
at com.google.firebase.database.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:79)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
AdminBookDetails.java
package com.example.books;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class AdminBookDetails extends AppCompatActivity implements
purchaseadapter.PurchaseClickInterface{
private RecyclerView booksRV;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private ConstraintLayout purchaseCL;
private purchaseadapter purchaseAdapter;
private Button Addbookdetails;
private Button Editbutton;
private RelativeLayout RLbottomsheet;
private ArrayList<purchasemodel> purchasemodelArrayList;
private FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_book_details);
getSupportActionBar().setTitle("Admin Book Details");
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
booksRV = findViewById(R.id.idRVpurchasebooks);
Addbookdetails = findViewById(R.id.Editdetails);
RLbottomsheet = findViewById(R.id.design_bottom_sheet);
//RLbottomsheet = findViewById(R.id.design_bottom_sheet);
firebaseDatabase = FirebaseDatabase.getInstance();
fAuth = FirebaseAuth.getInstance();
purchasemodelArrayList = new ArrayList<purchasemodel>();
databaseReference = firebaseDatabase.getReference("books");
Addbookdetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AdminBookDetails.this, admin_enterbookdetails.class);
startActivity(i);
}
});
//purchaseDbref = FirebaseDatabase.getInstance().getReference().child("Books");
//purchaseCL = findViewById(R.id.purchasebooksCL);
// we are initializing our adapter class and passing our arraylist to it.
purchaseAdapter = new purchaseadapter(purchasemodelArrayList,this,this::onCourseClick);
System.out.println("\n\narray passed\n\n");
// below line is for setting a layout manager for our recycler view.
// here we are creating vertical list so we will provide orientation as vertical
LinearLayoutManager linearLayoutManage = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
// in below two lines we are setting layoutmanager and adapter to our recycler view.
booksRV.setLayoutManager(linearLayoutManage);
booksRV.setAdapter(purchaseAdapter);
getAllBooks();
}
private void getAllBooks(){
purchasemodelArrayList.clear();
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
purchasemodelArrayList.add(snapshot.getValue(purchasemodel.class));
purchaseAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
purchaseAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
purchaseAdapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
purchaseAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCourseClick(int position) {
System.out.println("course clicked");
displaybottomsheetdialog(purchasemodelArrayList.get(position));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// on below line we are inflating our menu
// file for displaying our menu options.
getMenuInflater().inflate(R.menu.drawer_menu, menu);
return true;
}
private void displaybottomsheetdialog(purchasemodel Purchasemodel){
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
View layout = LayoutInflater.from(this).inflate(R.layout.bottomsheet, RLbottomsheet);
// setting content view for bottom sheet on below line.
bottomSheetDialog.setContentView(layout);
// on below line we are setting a cancelable
bottomSheetDialog.setCancelable(false);
bottomSheetDialog.setCanceledOnTouchOutside(true);
// calling a method to display our bottom sheet.
bottomSheetDialog.show();
TextView Booktitle = layout.findViewById(R.id.TVBooktitle);
TextView Author = layout.findViewById(R.id.TVauthor);
ImageView BookImg = layout.findViewById(R.id.IVbook);
TextView Publisher = layout.findViewById(R.id.TVPublisher);
//Button Editbutton = layout.findViewById(R.id.BtnEdt);
// Button Viewbutton = layout.findViewById(R.id.BtnView);
Booktitle.setText(Purchasemodel.getBook_title());
Author.setText(Purchasemodel.getAuthor_name());
//BookImg.setText(Purchasemodel.getBook_image());
Publisher.setText(Purchasemodel.getpublisher());
Picasso.get().load(Purchasemodel.getBook_image()).into(BookImg);
Editbutton = findViewById(R.id.BtnEdt);
Editbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AdminBookDetails.this, admin_editbookdetails.class);
// on below line we are passing our course modal
i.putExtra("books", Purchasemodel);
startActivity(i);
}
});

how to move from a fragment to a new activity when i clicked an item of recyclerview?

I am using recyclerview in fragment dynamically, now i want to open new activity on click of items with the same object / item.
AllCoursesFeagment.java
package com.example.learningapp.ui.NavigationDrawer.AllCourses;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.learningapp.Adapters.AllCoursesMyAdapter;
import com.example.learningapp.Interface.APIinterface;
import com.example.learningapp.Models.CourseListModel;
import com.example.learningapp.R;
import com.example.learningapp.Responses.CourseListResponse;
import com.example.learningapp.RetrofitAPIs.RetrofitAPI;
import com.example.learningapp.utility.ConstantData;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AllCoursesFragment extends Fragment {
private RecyclerView recyclerView;
private List<CourseListModel> courseListModelList;
public AllCoursesFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static AllCoursesFragment newInstance() {
return new AllCoursesFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_courses,null);
recyclerView = view.findViewById(R.id.allCourseList_RV);
APIinterface apIinterface = RetrofitAPI.getClient().create(APIinterface.class);
Call<CourseListResponse> call = apIinterface.getAllCourses(ConstantData.AppKey);
call.enqueue(new Callback<CourseListResponse>() {
#Override
public void onResponse(Call<CourseListResponse> call, Response<CourseListResponse> response){
if (response.isSuccessful()){
courseListModelList = response.body().getCourseList();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new AllCoursesMyAdapter(getActivity(),courseListModelList));
}
}
#Override
public void onFailure(Call<CourseListResponse> call, Throwable t) {
Toast.makeText(getActivity(),"Something went wrong",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AllCoursesMyAdapter.java
This is my adapter class.
package com.example.learningapp.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.learningapp.Activities.CheckoutActivity;
import com.example.learningapp.Models.CourseListModel;
import com.example.learningapp.R;
import java.util.List;
public class AllCoursesMyAdapter extends RecyclerView.Adapter<AllCoursesMyAdapter.RecyclerVH> {
Context context;
List<CourseListModel> courseListModelList;
public AllCoursesMyAdapter(Context context, List<CourseListModel> courseListModelList) {
this.context = context;
this.courseListModelList = courseListModelList;
}
#NonNull
#Override
public RecyclerVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_row_design_allcourses,parent,false);
return new RecyclerVH(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerVH holder, int position) {
final CourseListModel courseListModel = courseListModelList.get(position);
holder.courseTitle.setText(courseListModel.getCourseName());
holder.courseDesc.setText(courseListModel.getCourseDescription());
holder.buyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveToNewActivity();
//Toast.makeText(context,"Item Clicked"+position,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, CheckoutActivity.class);
intent.putExtra("coursetitle",courseListModel.getCourseName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
private void moveToNewActivity () {
Activity activity = new Activity();
Intent i = new Intent(activity, CheckoutActivity.class);
context.startActivity(i);
((Activity) context).overridePendingTransition(0, 0);
}
#Override
public int getItemCount() {
return courseListModelList.size();
}
public class RecyclerVH extends RecyclerView.ViewHolder {
TextView courseTitle,courseDesc;
Button buyBtn;
public RecyclerVH(#NonNull View itemView) {
super(itemView);
courseTitle = itemView.findViewById(R.id.course_title);
courseDesc = itemView.findViewById(R.id.course_desc);
buyBtn = itemView.findViewById(R.id.btn_buycourse);
}
}
}
I'm gettng crashed when i clicked item
holder.buyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveToNewActivity();
//Toast.makeText(context,"Item Clicked"+position,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, CheckoutActivity.class);
intent.putExtra("coursetitle",courseListModel.getCourseName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Here i am using a stored list of objects and now i want to move to the new activity when i clicked on an item with given position, but i am not able to do that.
private void moveToNewActivity () {
Activity activity = new Activity(); //this is wrong, delete this
...
}
you can't and shouldn't create an instance of an activity like this, it's something the OS has to schedule and handle for you.
you already seem to have context defined somewhere, so that means:
private void moveToNewActivity () {
Intent i = new Intent(context, CheckoutActivity.class);
context.startActivity(i);
...
}
so that means:
#Override
public void onClick(View v) {
moveToNewActivity();
}

How can I create new recycle views starting from a different recycle view on another activity

can anyone explain to me how can I create a new recycle and add items to that recycle view staring from another recycle view inside another activity?
Basically I want to create a shopping cart, for now, I retrieved the data from Firebase dataset and displayed it inside a recycle view but now I would like to send this data to the shopping cart(the shopping cart is inside another activity), I'm able to send the data but I can't understand how to display the data inside the new recycle view of this new activity. I need this because I want to see the items that I added to the shopping list so then I can pay.
Below I will attach a photo to explain myself better.
My problem is that I can't understand how to add the sent data to a recycle view again in the new activity.
I'm new to android so it's the first time I'm doing this thing.
Thank you in advance for your help.
My code:
SearchItemsActivity :
package com.example.ipill;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.ArrayList;
import java.util.List;
public class FirebaseSearch extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;
String searchText="";
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
private static ArrayList<Users> arrayList = new ArrayList<>();
public static int cart_count = 0;
RecyclerView productRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firebasesearch);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");
mSearchField = findViewById(R.id.search_field);
mSearchBtn = findViewById(R.id.search_btn);
mResultList = findViewById(R.id.result_list_cart);
AddToCart = findViewById(R.id.imageButton2);
Cart = findViewById(R.id.cartButton);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
Cart.setOnClickListener(new View.OnClickListener() {
private Object Tag="Activity";
#Override
public void onClick(View v) {
if (cart_count < 1) {
} else {
startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
}
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery =
mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
invalidateOptionsMenu();
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
String nome;
String surname;
Long prezzo;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);
addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cart_count++;
Context context = v.getContext();
Intent intent = new Intent(context, CartActivity.class);
intent.putExtra("Name",nome);
intent.putExtra("Surname",surname);
intent.putExtra("Prezzo",Long.toString(prezzo));
context.startActivity(intent);
}
});
}
public void getDetails(String name,String cognome,Long price){
nome=name;
surname=cognome;
prezzo=price;
}
public void setDetails(String name, String surname, Long price) {
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
TextView user_price = (TextView)mView.findViewById(R.id.price);
user_name.setText(name);
user_surname.setText(surname);
user_price.setText(Long.toString(price));
}
}
}
enter code here
The second activity where I receive the data and where I want to create the recycle view
package com.example.ipill;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
public class CartActivity extends AppCompatActivity {
public static TextView grandTotal;
public static int grandTotalplus;
// create a temp list and add cartitem list
public static ArrayList<Users> temparraylist;
RecyclerView cartRecyclerView;
Button proceedToBook;
Context context;
String name,surname,price;
private static ArrayList<Users> arrayList2 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
context = this;
temparraylist = new ArrayList<>();
proceedToBook = findViewById(R.id.buyNow);
grandTotal = findViewById(R.id.TotalPrice);
cartRecyclerView=findViewById(R.id.cartList);
String passedArg = getIntent().getExtras().getString("Name");
name=passedArg;
String passedArg2 = getIntent().getExtras().getString("Surname");
surname=passedArg2;
String passedArg3 = getIntent().getExtras().getString("Price");
price=passedArg3;
System.out.println("DATA"+name+surname+price);
cartRecyclerView.setHasFixedSize(true);
cartRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
you can re use the cart adapter just implement a recylerView into new Activity and make the cart adater object and set it into the new reyclerView and it done

How i can download and read "PDF file" with AsyncTask

I am creating an application for School Students so that they do not miss their huge BOOKS. In this project, the student clicks “RecylerView”, immediately downloads the book “Pdf” and saves it to external storage. "like whatsapp" without database
At the moment, I have a problem in that it only sees the file, but does not save!
I am using AsyscTask "My PDF Viewer" activity which bottom
please help!!!
My Main Activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
> public class MainActivity extends AppCompatActivity {
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_about_card_show);
RelativeLayout relativeLayout = findViewById(R.id.rl);
relativeLayout.startAnimation(animation);
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
//adding some items to our list
productList.add(
new Product(
1,
"TEst 11111 \n",
60000,
R.drawable.android,
"link1"
));
productList.add(
new Product(
1,
" More types, Methods, Conditionals \n",
60000,
R.drawable.android,
"link2"
));
productList.add(
new Product(
1,
"Loops, Arrays ",
60000,
R.drawable.android,
"lin3"
));
productList.add(
new Product(
1,
"Strings",
60000,
R.drawable.android,
"https://firebasestorage.googleapis.com/v0/b/firepdf-4c1d6.appspot.com/o/2.intro.pdf?alt=media&token=75731b04-c1e7-42c4-b988-e50a8f7e5f6b "
));
//creating recyclerview adapter
ProductAdapter adapter = new ProductAdapter(this, productList);
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
> public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
//this context we will use to inflate the layout
private Context mCtx;
//we are storing all the products in a list
private List<Product> productList;
//getting the context and product list with constructor
public ProductAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, final int position) {
//getting the product of the specified position
final Product product = productList.get(position);
//binding the data with the viewholder views
holder.textViewTitle.setText(product.getTitle());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getImage()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), pdf.class);
i.putExtra("title",productList.get(position).getTitle());
i.putExtra("product",productList.get(position).getTitle());
i.putExtra("link",productList.get(position).getLink());
mCtx.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
ImageView imageView;
CardView cardView;
public ProductViewHolder(View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardview);// card intial
textViewTitle = itemView.findViewById(R.id.textViewTitle);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
My Pdf Viewer
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.github.barteksc.pdfviewer.PDFView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class pdf extends AppCompatActivity {
String link="",productList="",product="";
PDFView pdfView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
product =getIntent().getStringExtra("title");
productList=getIntent().getStringExtra("productList");
link=getIntent().getStringExtra("link");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle(productList);
pdfView=findViewById(R.id.pdfv);
//pdfView.fromAsset(link).load();
if (isConnected()) {
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(pdf.this);
builder.setTitle("NoInternet Connection Alert")
.setMessage("GO to Setting ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(pdf.this,"Go Back TO HomePage!",Toast.LENGTH_SHORT).show();
}
});
//Creating dialog box
AlertDialog dialog = builder.create();
dialog.show();
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
link = getIntent().getStringExtra("link");
}
new pdf.RetrievePDFStream().execute(link);
}
public boolean isConnected() {
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
}
class RetrievePDFStream extends AsyncTask<String, Void, InputStream> {
ProgressDialog progressDialog;
protected void onPreExecute()
{
progressDialog = new ProgressDialog(pdf.this);
progressDialog.setTitle("getting the book content...");
progressDialog.setMessage("Please wait...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL urlx = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
progressDialog.dismiss();
}
}
#Override public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)//means home default hai kya yesok
{
onBackPressed();
return true;
}
return false;
}
}

how can i sort firebase data according to their ratings after getting title of value vikas?

Means I want to sort my firebaserecycleradapter according to highest no of ratings first after applying query on data having title with value "vikas"
This is my code:
package com.onlinetuto;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.onlinetuto.model.blog;
import static com.onlinetuto.EmptyActivity.EXTRA_POST_KEY;
public class GetLocation extends AppCompatActivity {
private static final String TAG = "MainActivity";
private RecyclerView re;
private DatabaseReference d,dref;
private FirebaseAuth mauth;
FirebaseRecyclerAdapter<blog,BlogViewholder> firebaseRecyclerAdapter;
DatabaseReference users, comments;
ProgressBar progressBar;
String locname;
SharedPreferences sharedPreferences;
LinearLayoutManager linearLayoutManager;
AutoCompleteTextView autoCompleteTextView;
Intent intent;
Button button;
Long code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location);
intent=getIntent();
if(intent!=null)
{
code= intent.getLongExtra("queryname",110094);
}
Toast.makeText(this, code.toString(), Toast.LENGTH_SHORT).show();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mauth = FirebaseAuth.getInstance();
d = FirebaseDatabase.getInstance().getReference().child("Products");
users = FirebaseDatabase.getInstance().getReference().child("Users");
comments = FirebaseDatabase.getInstance().getReference().child("post-comments");
Query nm=d.orderByChild("pincode").equalTo(code);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
// mquery = dtop.orderByChild("title").equalTo("hul");
// mquery2 = dtop.orderByChild("likeCount").limitToFirst(100);
//for offline capabilities of database
// d3.keepSynced(true);
d.keepSynced(true);
// mdatabaselike.keepSynced(true);
re = (RecyclerView) findViewById(R.id.blog_list);
re.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
re.setLayoutManager(linearLayoutManager);
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<blog, BlogViewholder>(
blog.class,
R.layout.blog_row,
BlogViewholder.class,
nm
) {
#Override
protected void populateViewHolder(final BlogViewholder viewHolder, final blog model, int position) {
final String post_key = getRef(position).getKey();
//for retrieving each post key getRef() method is used for this.
final DatabaseReference post_ref = getRef(position);
viewHolder.setTitle(model.getClassname());
viewHolder.setImage(getApplicationContext(), model.getImageone());
viewHolder.setReviews(model.getReviews());
viewHolder.setTypo(model.getType());
viewHolder.setNoofComments(model.getNoofreviews());
viewHolder.setratings(model.getNetrat());
viewHolder.setTextRating(model.getNoofreviews());
viewHolder.vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newIntent = new Intent(GetLocation.this, EmptyActivity.class);
newIntent.putExtra(EXTRA_POST_KEY, post_key);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(newIntent);
}
});
progressBar.setVisibility(View.GONE);
}
};
re.setAdapter(firebaseRecyclerAdapter);
}
private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit) {
finish(); // finish activity
} else {
Toast toast=Toast.makeText(this, "Press Back again to exit", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(getResources().getColor(R.color.toa));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(getResources().getColor(R.color.blackm));
/*Here you can do anything with above textview like text.setTextColor(Color.parseColor("#000000"));*/
toast.show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 2 * 1000);
}
}
public static class BlogViewholder extends RecyclerView.ViewHolder {
View vi;
FirebaseAuth mauth;
EditText e1;
public BlogViewholder(View itemView) {
super(itemView);
vi = itemView;
mauth = FirebaseAuth.getInstance();
}
/* public void setImage(Context context,String image){
ImageView imageView=(ImageView)vi.findViewById(R.id.post_iamge);
Picasso.with(context).load(image).into(imageView);
}*/
public void setTitle(String classname) {
TextView textView = (TextView) vi.findViewById(R.id.textViewTitle);
textView.setText(classname);
}
public void setImage(Context context, String image){
ImageView imageView=(ImageView)vi.findViewById(R.id.imageView);
Glide.with(context).load(image).into(imageView);
}
public void setReviews(String reviews) {
TextView textView = (TextView) vi.findViewById(R.id.reviews);
textView.setText(reviews);
}
public void setTypo(String type) {
TextView textView = (TextView) vi.findViewById(R.id.type);
textView.setText(type);
}
public void setTextRating(long comme) {
TextView textView = (TextView) vi.findViewById(R.id.textViewRating);
textView.setText(comme + "");
}
public void setNoofComments(long comme) {
TextView textView = (TextView) vi.findViewById(R.id.reviews);
textView.setText(comme+" Reviews");
}
public void setratings(Long rat) {
RatingBar textView = (RatingBar) vi.findViewById(R.id.img);
Integer myNum=0;
if(rat==null)
myNum=0;
else
{
Integer integer=(int)(long)rat;
myNum=integer;
}
if(myNum>5)
{
myNum=myNum%5;
textView.setRating(myNum);
}
else
{
textView.setRating(myNum);
}
}
}
}
this is my code please help me.i want to sort query data according to their ratings before passing it to the firebase recycleradapter .how can i acheive that?
Product database reference one key data:-
i am using firebase realtime database here
I'm using this one to sort it by latest post.
#Override
public blog getItem(int position) {
return super.getItem(getItemCount() - (position + 1));
}

Categories

Resources