Retrieve data from SQLite in RecyclerView inside fragment - android

I have an activity that contain custom Tablayout.
the Tablayot has pageViewer and link to a fragment.
I want to show data from my SQLite database in RecyclerView in fragment.
this is my codes:
DatabaseHelper.java:
package ir.shirazmetro;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
public static final String DATABASE_NAME = "MetroDB.db";
public static final String TABLE_NAME = "estation";
public static final String COL_1 = "station";
public static final String COL_2 = "time";
public static final String COL_3 = "line";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (COL_1,COL_2,COL_3)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String station, String time, String line) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, time);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("select "+COL_2+" from " + TABLE_NAME, null);
}
}
My activity(station.java):
package ir.shirazmetro.views.activities;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.design.widget.TabLayout;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import ir.shirazmetro.DatabaseHelper;
import ir.shirazmetro.R;
import ir.shirazmetro.other.components.ButtonCell;
import ir.shirazmetro.other.components.TextViewCell;
import ir.shirazmetro.views.adapters.BasePagerAdapter;
import ir.shirazmetro.views.adapters.MoviesAdapter;
public class estation extends BaseActivity {
Toolbar mToolbar;
private TabLayout tbLayout;
private ViewPager vPager;
private List<DatabaseHelper> movies = new ArrayList<DatabaseHelper>();
private RecyclerView recyclerView;
private MoviesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_estation);
mToolbar = findViewById(R.id.tlbr1);
setSupportActionBar(mToolbar);
initView();
setupWithViewPager();
tbLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
recyclerView = findViewById(R.id.myRecycler);
adapter = new MoviesAdapter(movies);
recyclerView.setLayoutManager(new LinearLayoutManager(estation.this));
recyclerView.setAdapter(adapter);
DatabaseHelper getData = (DatabaseHelper) new DatabaseHelper(this).getData();
movies.add(getData);
adapter.notifyDataSetChanged();
}
}
private void setupWithViewPager() {
BasePagerAdapter basePagerAdapter = new BasePagerAdapter(this, getSupportFragmentManager());
vPager.setAdapter(basePagerAdapter);
tbLayout.setupWithViewPager(vPager);
}
private void initView() {
vPager = findViewById(R.id.view_pager);
tbLayout = findViewById(R.id.tab_layout);
backBtn = findViewById(R.id.backBtn);
backBtn.setOnClickListener((View.OnClickListener) this);
}
}
and this code is my Adapter:
package ir.shira.views.adapters;
import android.content.Context;
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;
import ir.shira.DatabaseHelper;
import ir.shira.R;
import ir.shira.models.movie;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
private List<movie> movies;
private Context context;
public MoviesAdapter(List<DatabaseHelper> movies) {
movies = movies;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_to_dastgheyb,parent,false);
return new MovieViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.txtTime.setText(movies.get(position).getTime());
}
#Override
public int getItemCount() {
return movies.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder
{
public TextView txtTime;
public MovieViewHolder(View itemView)
{
super(itemView);
txtTime = itemView.findViewById(R.id.textView);
}
}
}
my app crash when I run the project, any ideas?

movies.get(position).getTime() retrieve DatabaseHelper, I think it is checked exception.

You are making mistake hear
When You creating List Obj.
private List<DatabaseHelper> movies = new ArrayList<DatabaseHelper>();
//.. List Type DatabaseHelper But You want movie ? so change this line to like this
private List<movie> movies = new ArrayList<movie>();
//movie is your model

Related

How do I access a String variable from another class?

I have a RecyclerView that displays a custom layout that is filled with two things:
An Image URL to display
A text name for the image
I query the SQLite database to get specific songs from the artist that is clicked on. I have this working, except for one thing.
I want to use the text name for the image (2) to be used as the variable in the query because the string is set to the value that I want to be used in the search query.
I cannot figure out how to access this variable.
Artists.java
package com.apps.robloxmusic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
public class Artists extends AppCompatActivity {
private static final String TAG = "Artists";
//Variables
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImagesUrls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artists);
Log.d(TAG, "onCreate: started.");
initImageBitmaps();
}
private void initImageBitmaps() {
Log.d(TAG, "initImageBitmaps: preparing bitmaps.");
mImagesUrls.add("https://cdn.blocktoro.com/wp-content/uploads/2019/07/bts-1097661412_1-e1562687430275-800x400.jpg");
mNames.add("BTS");
mImagesUrls.add("https://hdqwalls.com/download/post-malone-new-tattoo-2018-4k-lg-1920x1080.jpg");
mNames.add("Post Malone");
initRecyclerView();
}
private void initRecyclerView() {
Log.d(TAG, "initRecyclerView: preparing recycler view.");
RecyclerView recyclerView = findViewById(R.id.artistView);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(mNames, mImagesUrls, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
RecyclerViewAdapter.java
package com.apps.robloxmusic;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private static final String TAG = "RecyclerViewAdapter";
public ArrayList<String> mImagesNames = new ArrayList<>();
private ArrayList<String> mImages = new ArrayList<>();
private Context mContext;
public RecyclerViewAdapter(ArrayList<String> mImagesNames, ArrayList<String> mImages, Context mContext) {
this.mImagesNames = mImagesNames;
this.mImages = mImages;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_artistlist, viewGroup, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewerHolder: called.");
Glide.with(mContext)
.asBitmap()
.load(mImages.get(position))
.into(holder.artistImage);
holder.artistName.setText(mImagesNames.get(position));
holder.artistLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked on:" + mImagesNames.get(position));
Intent intent = new Intent(mContext, BandView.class);
intent.putExtra("image_url", mImages.get(position));
//might not need this?
intent.putExtra("image_name", mImagesNames.get(position));
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mImagesNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView artistImage;
TextView artistName;
RelativeLayout artistLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
artistImage = itemView.findViewById(R.id.artistImage);
artistName = itemView.findViewById(R.id.artistName);
artistLayout = itemView.findViewById(R.id.artistLayout);
}
}
}
DatabaseAccess.java
private String allArtistSongs is what I'd like to set the text variable to. "BTS"; is just a placeholder.
package com.apps.robloxmusic;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DatabaseAccess instance;
private String allArtistSongs = "BTS";
/**
* Private constructor to avoid object creation from outside classes.
*
* #param context
*/
private DatabaseAccess(Context context) {
this.openHelper = new DatabaseOpenHelper(context);
}
/**
* Return a singleton instance of DatabaseAccess.
*
* #param context the Context
* #return the instance of DatabaseAccess
*/
public static DatabaseAccess getInstance(Context context) {
if (instance == null) {
instance = new DatabaseAccess(context);
}
return instance;
}
/**
* Open the database connection.
*/
public void open() {
this.database = openHelper.getWritableDatabase();
}
/**
* Close the database connection.
*/
public void close() {
if (database != null) {
this.database.close();
}
}
/**
* Read all songs from the database.
*
* #return a List of songs
*/
public List<String> getSongs() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM [Music_Codes]", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
public List<String> getArtistSongs() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM [Music_Codes] WHERE Song LIKE ?", new String[] {"%"+ allArtistSongs+ "%"});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
}
Where do you need to call getArtistSongs() ? I suspect you need to call this method in the new activity launched by the clickListener on the viewHolder.
if so, you can provide this string to the intent (image_name??). Then when the new activity starts up you can get the string from the intent and use it in the getArtistSongs().
getArtistSongs() need to have a parameter String for the query, something like
public List<String> getArtistSongs(String artist) {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM [Music_Codes] WHERE Song LIKE ?", new String[] {"%"+ artist + "%"});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}

Need Help Sorting ListView with Custom Adapter

I have a Main Activity that holds a viewpager that contains three fragments. In each fragment is a listview populated by a custom adapter. I need the ability to sort by date, name and quantity (the fields that the listview shows)
Here is my Main Activity
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager viewPager;
private String TAG = "MainActivity";
public ArrayList<Customer> packageData;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("BK Bee Sales - Pending Sales");
setSupportActionBar(toolbar);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dft = preferences.getString("default", "");
if(!dft.equalsIgnoreCase(""))
{
if (dft.equals("package")){
viewPager.setCurrentItem(0);
}else if (dft.equals("nuc")){
viewPager.setCurrentItem(1);
}else if (dft.equals("queen")){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
}
public void showAddCustomer(View view){
Intent intent = new Intent(this, AddCustomer.class);
startActivity(intent);
}
public void sortDate (View view){
Tab1 tab1 = new Tab1();
Tab2 tab2 = new Tab2();
Tab3 tab3 = new Tab3();
if (viewPager.getCurrentItem()==0){
tab1.sortDate();
}
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1(), "Packages");
adapter.addFragment(new Tab2(), "Nucs");
adapter.addFragment(new Tab3(), "Queens");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
return true;
} else if (id==R.id.action_viewList){
Intent intent = new Intent(this,SalesRecord.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
Here is my Tab1 Class
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Tab1 extends Fragment {
private CustomerAdapter customerAdapter;
private static final String TAG = "fragment_tab1";
private ListView tab1ListView;
private ArrayList<Customer> packageData = new ArrayList<>();
TextView totalPackages;
TextView totalGross;
View rootView;
public Tab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tab1ListView = (ListView) rootView.findViewById(R.id.tab1ListView);
totalPackages = (TextView)rootView.findViewById(R.id.totalPackages);
totalGross = (TextView)rootView.findViewById(R.id.totalGross);
return rootView;
}
#Override
public void onResume(){
super.onResume();
updatePackageList();
}
public void updatePackageList() {
packageData.clear();
tab1ListView.setAdapter(null);
int totalPackagesInt = 0;
try {
DatabaseHelper dbHelper = DatabaseHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM packageCustomers", null);
if (c != null) {
if (c.moveToFirst()) {
while (!c.isAfterLast()){
Customer cus = new Customer();
cus.setDate(c.getString(c.getColumnIndex("date")));
cus.setName(c.getString(c.getColumnIndex("name")));
cus.setPhone(c.getString(c.getColumnIndex("phone")));
cus.setEmail(c.getString(c.getColumnIndex("email")));
cus.setQuantity(c.getInt(c.getColumnIndex("quantity")));
cus.setNotes(c.getString(c.getColumnIndex("notes")));
cus.setId(c.getInt(c.getColumnIndex("id")));
packageData.add(cus);
totalPackagesInt = totalPackagesInt + cus.getQuantity();
c.moveToNext();
}
}
}
customerAdapter = new CustomerAdapter(this.getContext(), packageData);
tab1ListView.setAdapter(customerAdapter);
db.close();
c.close();
String totalPackagesText = totalPackagesInt + " Total Packages Reserved";
totalPackages.setText(totalPackagesText);
packageMath(totalPackagesInt);
tab1ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Customer cus = new Customer();
cus = customerAdapter.getItem(position);
int sqlId = cus.getId();
Intent intent = new Intent(getContext(), CustomerModel.class);
intent.putExtra("table", "packageCustomers");
intent.putExtra("id", sqlId);
startActivity(intent);
}
});
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
public void packageMath(int i){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(rootView.getContext());
String p = preferences.getString("packagePrice","");
if(!p.equals("")) {
int price = Integer.parseInt(p);
int totalGrossInt = i * price;
String grossText = "Projected Earnings: $" + String.valueOf(totalGrossInt);
totalGross.setText(grossText);
} else {
totalGross.setText("Edit Price Preferences");
}
}
public void sortDate(){
Collections.sort(packageData);
tab1ListView.setAdapter(customerAdapter);
updatePackageList();
}
}
Here is my Customer Class
package com.bkbeesites.bkbeesalessheet;
import android.support.annotation.NonNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by Brett on 12/6/2017.
*/
public class Customer implements Comparable<Customer>{
public String name;
private String email;
private String phone;
private int quantity;
private String notes;
private String date;
private int id;
private Date dateTime;
public Customer (){
this.name = "";
this.email="";
this.phone="";
this.quantity=0;
this.notes="";
this.date="";
}
public Customer (int id, String name, String phone, String email, int quantity, String notes, String date) {
this.name = name;
this.email = email;
this.phone = phone;
this.quantity = quantity;
this.notes = notes;
this.date = date;
}
public Date getDateTime() throws ParseException {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
Date convertedDate = new Date();
convertedDate = sdf.parse(date);
return convertedDate;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int compareTo(#NonNull Customer o) {
try {
return getDateTime().compareTo(o.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
And Lastly, here is my CustomerAdapter
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Brett on 12/6/2017.
*/
public class CustomerAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Customer> mDataSource;
public CustomerAdapter(Context context, ArrayList<Customer> items) {
super();
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mDataSource.size();
}
//2
#Override
public Customer getItem(int position) {
return mDataSource.get(position);
}
//3
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.list_item, parent, false);
// Get title element
TextView nameTextView =
(TextView) rowView.findViewById(R.id.nameTextView);
TextView quantityTextView =
(TextView) rowView.findViewById(R.id.quantityTextView);
TextView dateTextView =
(TextView) rowView.findViewById(R.id.dateTextView);
Customer cus = mDataSource.get(position);
nameTextView.setText(cus.getName());
quantityTextView.setText(String.valueOf(cus.getQuantity()));
dateTextView.setText(cus.getDate());
return rowView;
}
}
Sorry if that was a lot of unnecessary code but I'm a beginner here and did not know what you would want to see.
I'm trying to call Collections.sort when the Column Title Textview "Order Date" is clicked. The Data that contains the Customer objects is stored in an SQLite database (not sure if that's pertinent).
You need to write a method in adapter class that should look like this;
public void sort(){
Collections.sort(list, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
notifyDataSetChanged();
}
if you don't want to create comparator every method call you can create variable of comparator.
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
in this case you need to change sort method like;
public void sort(){
Collections.sort(list, comp);
notifyDataSetChanged();
}
whenever you want to sort in your activity class you need to call this sort method it will sort your list and update listview.
In your activity class you need to call method like below
adapter.sort();
Also if you want to compare according to other fields. You can create variable as
private int sortType;
You should pass parameter to adapter class.
public void sort(int sortType){
this.sortType = sortType;
Collections.sort(list, comp);
notifyDataSetChanged();
}
and change the comparator field as below
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
switch(sortType){
case 0: //By Name
return o1.getName().compareTo(o2.getName);
break;
case 1:
return o1.getQuantitiy() - o2.getQuantitiy();
break;
case 2:
return o1.compareTo(o2);
break;
default:
return 0;
}
}
});

com.google.firebase.database.databaseexception:firebase database error: Permission denied

im retrieving data in my database from firebase. and shoscription herew up this error can anyone help me? this is my mainactivity.java:
package com.example.infamouslegend.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef ;
List<FireModel> list;
RecyclerView recycle;
Button view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (Button) findViewById(R.id.view);
recycle = (RecyclerView) findViewById(R.id.recycle);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Complaints");
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.
list = new ArrayList<FireModel>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
FireModel value = dataSnapshot.getValue(FireModel.class);
FireModel fire = new FireModel();
String Description = value.getDescription();
String Date = value.getDate();
String MediaURL = value.getMediaURL();
fire.setDescription(Description);
fire.setDate(Date);
fire.setMediaURL(MediaURL);
list.add(fire);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
Toast.makeText(MainActivity.this, "Failed to read value !" + error.toException(), Toast.LENGTH_SHORT).show();
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list,MainActivity.this);
RecyclerView.LayoutManager recyce = new GridLayoutManager(MainActivity.this,2);
/// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
// recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recycle.setLayoutManager(recyce);
recycle.setItemAnimator( new DefaultItemAnimator());
recycle.setAdapter(recyclerAdapter);
}
});
}
}
and this is my firemodel.java:
package com.example.infamouslegend.myapplication;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class FireModel {
public String Description;
public String Date;
public String MediaURL;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
this.Description = description;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
this.Date = date;
}
public String getMediaURL() {
return MediaURL;
}
public void setMediaURL(String MediaURL) {
this.MediaURL = MediaURL;
}
}
and my recycleradapter.java:
package com.example.infamouslegend.myapplication;
import android.content.Context;
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 com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyHoder>{
List<FireModel> list;
Context context;
public RecyclerAdapter(List<FireModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public MyHoder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card,parent,false);
MyHoder myHoder = new MyHoder(view);
return myHoder;
}
#Override
public void onBindViewHolder(MyHoder holder, int position) {
FireModel mylist = list.get(position);
holder.Description.setText(mylist.getDescription());
holder.Date.setText(mylist.getDate());
//holder.MediaURL.setText(mylist.getMediaURL());
//Picasso.with(context).load(MediaURL.get(position).getMediaURL()).resize(120, 60).into(MyHoder.MediaURL);
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(list.size()==0){
arr = 0;
}
else{
arr=list.size();
}
}catch (Exception e){
}
return arr;
}
class MyHoder extends RecyclerView.ViewHolder{
TextView Description,Date;
//ImageView MediaURL;
public MyHoder(View itemView) {
super(itemView);
Description = (TextView) itemView.findViewById(R.id.vname);
Date= (TextView) itemView.findViewById(R.id.vemail);
//MediaURL= (ImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
Can anyone help me this? Im trying to retrieve data from firebase database to recyclerview with cardview. Thanks in advance
this is my firebase realtime database rule:
{
"rules": {
".read": true,
".write":true
}
}
If you have configured the app to connect with firebase correctly i would redownload the google-service.json and replace with an existing one.
check this solution

AS how to setOnClickListener in listview item from assets database file

i want to ask about OnClickListener. I called external database file[assets folder] in listview. I want to set onClicklistener at each item in listview. When listview item clicks, wanna appear a little fragment with data fields.I tried many sources but still not working.
Here is example fragment want to do.
enter image description here
Here is database structure.
enter image description here
Here is DatabaseHelper.java
package com.example.arlequina.sqlitefromassetexample.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.util.ArrayList;
import java.util.List;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbname = "sample.db";
public static final String dblocation = "/data/data/com.example.arlequina.sqlitefromassetexample/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context, dbname, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(dbname).getPath();
if(mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if(mDatabase != null){
mDatabase.close();
}
}
public List<Product> getListProduct(){
Product product = null;
List<Product> productList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery(" SELECT * FROM Product ", null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
product = new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
productList.add(product);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return productList;
}
}
Here is ListProductAdapter.java
package com.example.arlequina.sqlitefromassetexample.adapter;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.arlequina.sqlitefromassetexample.R;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class ListProductAdapter extends BaseAdapter{
private Context mContext;
private List<Product> mProductList;
public ListProductAdapter(Context mContext, List<Product> mProductList){
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return mProductList.get(position).getId();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.item_listview, null);
TextView tvName = (TextView)v.findViewById(R.id.tv_product_name);
TextView tvPrice = (TextView)v.findViewById(R.id.tv_product_price);
TextView tvDesc = (TextView)v.findViewById(R.id.tv_product_desc);
//ImageView tvImage = (ImageView)v.findViewById(R.id.tv_product_img);
tvName.setText(mProductList.get(position).getName());
tvPrice.setText(String.valueOf(mProductList.get(position).getPrice()) + " $");
tvDesc.setText(mProductList.get(position).getDesc());
// tvImage.setImageIcon(mProductList.get(position).getImage());
return v;
}
}
Here is MainActivity
package com.example.arlequina.sqlitefromassetexample;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.arlequina.sqlitefromassetexample.adapter.ListProductAdapter;
import com.example.arlequina.sqlitefromassetexample.database.DatabaseHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class MainActivity extends Activity {
private ListView lvProduct;
private ListProductAdapter adapter;
private List<Product> mProductList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProduct = (ListView)findViewById(R.id.listview_product);
mDBHelper = new DatabaseHelper(this);
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.dbname);
if(false == database.exists()){
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)){
Toast.makeText(this,"Copy database success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mProductList = mDBHelper.getListProduct();
//Init adapter
adapter = new ListProductAdapter(this,mProductList);
//Set adapter for listview
lvProduct.setAdapter(adapter);
}
private boolean copyDatabase(Context context){
try{
InputStream inputStream = context.getAssets().open(DatabaseHelper.dbname);
String outFileName = DatabaseHelper.dblocation + DatabaseHelper.dbname;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while((length = inputStream.read(buff)) > 0){
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("MainActivity", "DB copied");
return true;
} catch(Exception e){
e.printStackTrace();
return false;
}
}
}
item_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_product_name"
android:text = "Name"
android:textColor="#4bb6d6"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_price"
android:text="100$"
android:textColor="#b30000"
android:textSize="18dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_desc"
android:text="Description"
android:textSize="16dp"
android:textStyle="italic"/>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d1d1d1">
<ListView
android:id = "#+id/listview_product"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:divider="#d1d1d1"
android:dividerHeight="10dp"></ListView>
</LinearLayout>
Product.java
package com.example.arlequina.sqlitefromassetexample.model;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class Product {
private int id;
private String name;
private String price;
private String desc;
//private Blob img;
public Product(int id, String name, String price, String desc){
this.id = id;
this.name = name;
this.price = price;
this.desc = desc;
//this.img = img;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getPrice(){
return price;
}
public void setPrice(String price){
this.price = price;
}
public String getDesc(){
return desc;
}
public void setDesc(String desc){
this.desc = desc;
}
}
Since your problem is make your list item clickable, you can use this after init listview in activity.
lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
position is position of that clicked item in list. So you can get that item using mProductList.get(position)
After you can get that item, now it's time to show your item up. You can use custom dialog to make it like your demo (of cause you have to create 1 more xml):
Check section Custom Dialog in this official link: https://developer.android.com/guide/topics/ui/dialogs.html
You can use listview.setOnItemClickListener or v.setOnClickListener to solve your problem.That is the most basic ,man.

java.lang.NullPointerException in customize ArrayAdapter in android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to write a ListView with custom Adapter in android.when my code is done i got 'java.lang.NullPointerException' .
I checked again and again but can not fix this error.
this is MainActivity code:
package com.example.sayres.myapplication3_listview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
private EditText mainActivity_editText_userName, mainActivity_editText_password;
private Button mainActivity_btn_login, mainActivity_btn_exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mainActivity_editText_userName = (EditText) findViewById(R.id.mainActivity_editText_userName);
mainActivity_editText_password = (EditText) findViewById(R.id.mainActivity_editText_password);
mainActivity_btn_login = (Button) findViewById(R.id.mainActivity_btn_login);
mainActivity_btn_exit = (Button) findViewById(R.id.mainActivity_btn_exit);
mainActivity_btn_exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
mainActivity_btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginprocess();
}
});
}
private void loginprocess() {
String userName = mainActivity_editText_userName.getText().toString();
String password = mainActivity_editText_password.getText().toString();
Log.i("====>", "UserName= "+ userName+" Passwotd: "+ password);
Toast.makeText(getApplicationContext(),userName, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}
}
in MainActivity code i create intent for go to HomeActivity.
HomeActivity code:
package com.example.sayres.myapplication3_listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.example.sayres.myapplication3_listview.adapter.ContactAdapter;
import com.example.sayres.myapplication3_listview.model.Contact;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
private ListView listViewHome;
private List<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initViews();
}
private void initViews() {
listViewHome = (ListView) findViewById(R.id.listViewHome);
for (int i = 0; i < 1000; i++) {
int pic = 0;
if (i % 2 == 0) {
pic = R.drawable.man;
} else {
pic = R.drawable.female;
}
contacts.add(createContact("name " + i, "family " + i, "5526576", pic));
}
ContactAdapter adapter = new ContactAdapter(this, R.layout.row_contacts_list, contacts);
listViewHome.setAdapter(adapter);
}
private Contact createContact(String name, String family, String number, int picture) {
return new Contact(name, family, number, picture);
}
}
I got Error In this line: contacts.add(createContact("name " + i, "family " + i, "5526576", pic));
this error
at com.example.sayres.myapplication3_listview.HomeActivity.initViews(HomeActivity.java:34)
at com.example.sayres.myapplication3_listview.HomeActivity.onCreate(HomeActivity.java:21)
this is ContactAdapter extends ArrayAdapter code:
package com.example.sayres.myapplication3_listview.adapter;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.sayres.myapplication3_listview.R;
import com.example.sayres.myapplication3_listview.model.Contact;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class ContactAdapter extends ArrayAdapter<Contact> {
private Context context;
private int layout;
private List<Contact> contacts;
public ContactAdapter(Context context, int layout, List<Contact> contacts) {
super(context, layout, contacts);
this.context = context;
this.layout = layout;
this.contacts = contacts;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rootView = inflater.inflate(layout, null);
if (position % 2 == 0 ){
rootView.setBackgroundColor(Color.parseColor("#12ffff"));
}else {
rootView.setBackgroundColor(Color.parseColor("#FFFF12"));
}
/**
* set reference from row_contacts_list.xml
*/
TextView contactList_name = (TextView) rootView.findViewById(R.id.contactList_name);
TextView contactList_family = (TextView) rootView.findViewById(R.id.contactList_family);
CircleImageView profile_picture = (CircleImageView) rootView.findViewById(R.id.profile_picture);
contactList_name.setText(contacts.get(position).getContactName());
contactList_family.setText(contacts.get(position).getContactFamily());
profile_picture.setImageResource(contacts.get(position).getContactPicture());
return rootView;
}
}
my Contact class is a simple class with setter and getter:
package com.example.sayres.myapplication3_listview.model;
public class Contact {
private String contactName,contactFamily, contactNumber;
private int contactPicture;
public Contact() {
}
public Contact(String contactName, String contactFamily, String contactNumber, int contactPicture) {
this.contactName = contactName;
this.contactFamily = contactFamily;
this.contactNumber = contactNumber;
this.contactPicture = contactPicture;
}
where is my mistake?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Init the contacts
contacts = new ArrayList<Contact>();
initViews();
}

Categories

Resources