Use External Database in Recyclerview - java

I try to lunch a recyclerview of external database. so i prepared mydatabase.db.zip and putt it into assets/database folder.after writing codes i found an error NullPointerException.i dont know where the problem is. please help
Data model:
package com.example.myapplication.DataModel;
public class Name {
public int id;
public String name;
public String meaning;
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 getMeaning() {
return meaning;
}
public void setMeaning(String meaning) {
this.meaning = meaning;
}
}
MyDatabase.java
package com.example.myapplication;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "niniaad.db";
private static final int DATABASE_VERSION = 1;
private static final String TBL_NAME="names";
private static final String COL_ID="id";
private static final String COL_NAME="name";
private static final String COL_MEAN="mean";
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getData(){
SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
Cursor cursor=sqLiteDatabase.rawQuery("SELECT * FROM "+TBL_NAME,null);
return cursor;
}
}
SecondRecycler.java
package com.example.myapplication;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.RelativeLayout;
import com.example.myapplication.Adapter.NameAdapter;
import com.example.myapplication.Adapter.StudentAdapter;
import com.example.myapplication.DataModel.Name;
import com.example.myapplication.DataModel.Students;
import java.util.ArrayList;
import java.util.List;
public class SecondRecycler extends AppCompatActivity {
RecyclerView recyclerView;
List<Name> nameList;
MyDatabase myDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_recycler);
setupviews();
getDataFromSqlite();
}
private void getDataFromSqlite() {
Cursor cursor= myDatabase.getData();
for (cursor.moveToFirst(); !cursor.isAfterLast() ; cursor.moveToNext()) {
Name name=new Name();
name.setName(cursor.getString(0));
name.setMeaning(cursor.getString(1));
nameList.add(name);
}
recyclerView.setAdapter(new NameAdapter(SecondRecycler.this,nameList));
}
private void setupviews() {
MyDatabase myDatabase=new MyDatabase(this);
recyclerView = (RecyclerView) findViewById(R.id.rv_secondrecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(SecondRecycler.this));
}
}
Adapter
package com.example.myapplication.Adapter;
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 com.example.myapplication.DataModel.Name;
import com.example.myapplication.R;
import java.util.List;
public class NameAdapter extends RecyclerView.Adapter<NameAdapter.NameViewHolder> {
public Context context;
public List<Name> nameList;
public NameAdapter(Context context, List<Name> nameList) {
this.context = context;
this.nameList = nameList;
}
#NonNull
#Override
public NameViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.secondrecycler_row, viewGroup, false);
return new NameViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NameViewHolder nameViewHolder, int position) {
Name name = nameList.get(position);
nameViewHolder.txtName.setText(name.getName());
nameViewHolder.txtMean.setText(name.getMeaning());
}
#Override
public int getItemCount() {
return nameList.size();
}
public class NameViewHolder extends RecyclerView.ViewHolder {
TextView txtName, txtMean;
public NameViewHolder(#NonNull View itemView) {
super(itemView);
txtName = (TextView) itemView.findViewById(R.id.txt_name_Secondrecycler);
txtMean = (TextView) itemView.findViewById(R.id.txt_mean_seconrecycler);
}
}
}
activity_second_recycler.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondRecycler">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_secondrecycler"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
recycler_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 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:layout_margin="10dp"
tools:context=".SecondRecycler">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txt_name_Secondrecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textColor="#000"
tools:text="name"
android:textAlignment="center"
/>
<TextView
android:layout_below="#id/txt_name_Secondrecycler"
android:id="#+id/txt_mean_seconrecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textColor="#FF0000"
tools:text="mean"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>

Related

Trying to show Recycler View in fragment of Navigation Drawer

I've created a Navigation Drawer in Android Studio, using the default Navigation Drawer Activity (Android Studio Bublebee 2021.1.1.1).
And I put a Recycler view in the fragment layout. After that I tried to get data from Firebase database, and put it in Recycler view, using Firebase UI. And since the default code is different, than in many tutorials and etc. I tried to find out how to do it myself. I did it in Fragment java file, from ui package folder.
Everything is working, no errors, no crashes, but the page is empty.
My Navigation Drawer Activity java file:
package com.example.project;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.widget.TextView;
import com.example.project.classes.User;
import com.example.project.classes.product;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.project.databinding.ActivityStoreBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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;
public class Store extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityStoreBinding binding;
private FirebaseUser user;
private DatabaseReference dbReference;
private String uID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityStoreBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarStore.toolbar);
/*binding.appBarStore.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
View headerView = navigationView.getHeaderView(0);
final TextView StoreNavUsername = headerView.findViewById(R.id.store_nav_header_username);
user = FirebaseAuth.getInstance().getCurrentUser();
dbReference = FirebaseDatabase.getInstance().getReference("Users");
uID = user.getUid();
dbReference.child(uID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userData = snapshot.getValue(User.class);
if (userData != null){
String usernameData = userData.username;
StoreNavUsername.setText(usernameData);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_cart, R.id.nav_orders, R.id.nav_categories)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_store);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
// product
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.store, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_store);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
Main XML file of the activity:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
android:id="#+id/app_bar_store"
layout="#layout/app_bar_store"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_store"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
The fragment layout of the page with the Recycler View:
<?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"
tools:context=".ui.home.HomeFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/store_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
The class of the item, needed to put into the Recycler View:
package com.example.project.classes;
public class product {
private String name, price, producer, imageurl, category, productid, sellerid;
public product() {
}
public product(String name, String price, String producer, String imageurl, String category, String productid, String sellerid) {
this.name = name;
this.price = price;
this.producer = producer;
this.imageurl = imageurl;
this.category = category;
this.productid = productid;
this.sellerid = sellerid;
}
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 getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getProductid() {
return productid;
}
public void setProductid(String productid) {
this.productid = productid;
}
public String getSellerid() {
return sellerid;
}
public void setSellerid(String sellerid) {
this.sellerid = sellerid;
}
}
The layout of the single item, to put into Recycler View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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:scrollbars="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<ImageView
android:id="#+id/product_image"
android:layout_width="wrap_content"
android:layout_height="200dp"/>
<TextView
android:id="#+id/product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/product_image"
android:layout_marginTop="5dp"
android:textSize="20dp"
android:textAlignment="center"
android:textColor="#color/black"
android:textStyle="bold"
android:text="#string/product_name"
/>
<TextView
android:id="#+id/product_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/product_name"
android:layout_marginTop="5dp"
android:textSize="18dp"
android:textAlignment="center"
android:textColor="#color/black"
android:textStyle="bold"
android:text="#string/product_price"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
The Adapter:
package com.example.project;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.project.classes.product;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
public class productAdapter extends FirebaseRecyclerAdapter<
product, productAdapter.productViewholder> {
public productAdapter(
#NonNull FirebaseRecyclerOptions<product> options)
{
super(options);
}
#Override
protected void onBindViewHolder(#NonNull productAdapter.productViewholder holder, int position, #NonNull product model) {
holder.name.setText(model.getName());
holder.price.setText(model.getPrice());
}
#NonNull
#Override
public productViewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product_layout, parent, false);
return new productAdapter.productViewholder(view);
}
class productViewholder extends RecyclerView.ViewHolder {
TextView name, price;
public productViewholder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.product_name);
price = itemView.findViewById(R.id.product_price);
}
}
}
The Java file of the page fragment:
package com.example.project.ui.home;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.project.classes.product;
import com.example.project.databinding.FragmentHomeBinding;
import com.example.project.productAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
productAdapter adapter;
DatabaseReference productDbReference;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
HomeViewModel homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
/*final TextView textView = binding.textHome;
homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);*/
return root;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
productDbReference = FirebaseDatabase.getInstance("https://health-mentor-12edb-default-rtdb.europe-west1.firebasedatabase.app/").getReference("Products");
final RecyclerView StoreRecyclerView = binding.storeRecyclerView;
StoreRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
FirebaseRecyclerOptions<product> options = new FirebaseRecyclerOptions.Builder<product>()
.setQuery(productDbReference, product.class)
.build();
adapter = new productAdapter(options);
StoreRecyclerView.setAdapter(adapter);
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
I'm trying to put just the name and price, without the image, for now. But the page is just empty. I feel like, I got the data from database, but just didn't write, how it should put the data into the Recycler View.

E/Volley: [6074] BasicNetwork.performRequest: Unexpected response code 403 for

activity_main.xml
<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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
2.activity_frame.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="500dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="411dp"
android:layout_height="360dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars"
android:contentDescription="#string/todo" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/textview1"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.173" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/textview2"
android:maxLines="1"
android:ellipsize="end"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/textView1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
HDNews.java
package com.example.android.hdnews;
public class HDNews {
private String title;
private String author;
private String image;
public HDNews(String title, String author, String image) {
this.title = title;
this.author = author;
this.image = image;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getImage() {
return image;
}
}
MainActivity.java
package com.example.android.hdnews;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.LinearLayout;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList al;
private HDNewsAdapter hdNewsAdapter;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.rView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
al=new ArrayList<HDNews>();
requestQueue= Volley.newRequestQueue(this);
extractingDataFromInternet();
}
//http://newsapi.org/v2/top-headlines?country=in&apiKey=94bf8bcc374b494485309e325e3656f9
public void extractingDataFromInternet(){
String url="http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=94bf8bcc374b494485309e325e3656f9";
JsonObjectRequest JsonObjReq=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ca = jsonArray.getJSONObject(i);
String authorNames = ca.optString("author");
String titleNames = ca.optString("title");
String imageUrls = ca.getString("urlToImage");
al.add(new HDNews(titleNames, authorNames, imageUrls));
}
hdNewsAdapter = new HDNewsAdapter(MainActivity.this, al);
recyclerView.setAdapter(hdNewsAdapter);
} catch ( JSONException e ) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(JsonObjReq);
}
}
HDNewsAdapter
package com.example.android.hdnews;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class HDNewsAdapter extends RecyclerView.Adapter<HDNewsAdapter.ViewHolder>{
private Context context;
private ArrayList<HDNews> al;
public HDNewsAdapter(Context context, ArrayList<HDNews> al) {
this.context = context;
this.al = al;
}
#NonNull
#Override
public HDNewsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View views= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_frame,parent,false);
return new ViewHolder(views);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
HDNews currentposition=al.get(position);
String imgurl=currentposition.getImage();
String athName=currentposition.getAuthor();
String ttleName=currentposition.getTitle();
holder.titleName01.setText(ttleName);
holder.authorName01.setText(athName);
Glide.with(context).load(imgurl).into(holder.imageurl01);
}
#Override
public int getItemCount() {
return al.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView authorName01;
public TextView titleName01;
public ImageView imageurl01;
public ViewHolder(#NonNull View itemView) {
super(itemView);
authorName01=itemView.findViewById(R.id.textView1);
titleName01=itemView.findViewById(R.id.textView2);
imageurl01=itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View view) {
}
}
}

in RecyclerView i want onclicklistner operation

Code is for recyclerview I want to implement click operation in child option separately.
how should i implement the given code below this code?
this my project code with adapter,child,parent
adapter.java
package com.blipclap.engineering_solution.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.Adapter.ExpandableRecyclerAdapter;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import com.blipclap.engineering_solution.Models.TitleChild;
import com.blipclap.engineering_solution.Models.TitleParent;
import com.blipclap.engineering_solution.R;
import com.blipclap.engineering_solution.ViewHolder.TitleChildViewHolder;
import com.blipclap.engineering_solution.ViewHolder.TitleParentViewHolder;
import java.util.List;
public class adapter extends ExpandableRecyclerAdapter<TitleParentViewHolder,TitleChildViewHolder> {
LayoutInflater inflater;
public adapter(Context context, List<ParentObject> parentItemList) {
super(context, parentItemList);
inflater=LayoutInflater.from(context);
}
#Override
public TitleParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view=inflater.inflate(R.layout.list_parent,viewGroup,false);
return new TitleParentViewHolder(view);
}
#Override
public TitleChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view=inflater.inflate(R.layout.list_child,viewGroup,false);
return new TitleChildViewHolder(view); }
#Override
public void onBindParentViewHolder(TitleParentViewHolder titleParentViewHolder, int i, Object o) {
TitleParent title =(TitleParent)o;
titleParentViewHolder._textview.setText(title.getTitle());
}
#Override
public void onBindChildViewHolder(TitleChildViewHolder titleChildViewHolder, int i, Object o) {
TitleChild title =(TitleChild)o;
titleChildViewHolder.op1.setText(title.getop1());
titleChildViewHolder.op2.setText(title.getop2());
titleChildViewHolder.op3.setText(title.getop3());
titleChildViewHolder.op4.setText(title.getop4());
titleChildViewHolder.op5.setText(title.getop5());
}
}
TitleChild.java
package com.blipclap.engineering_solution.Models;
public class TitleChild {
public String op1;
public String op2;
public String op3;
public String op4;
public String op5;
public TitleChild(String op1, String op2, String op3, String op4,String op5) {
this.op1 = op1;
this.op2 = op2;
this.op3 = op3;
this.op4 = op4;
this.op5 = op5;
}
public String getop1() {return op1;}
public void setop1(String op1) {this.op1 = op1;}
public String getop2() {return op2;}
public void setop2(String op2) {this.op2 = op2;}
public String getop3() {return op3;}
public void setop3(String op3) {this.op3 = op3;}
public String getop4() {return op4;}
public void setop4(String op4) {this.op4 = op4;}
public String getop5() {return op5;}
public void setop5(String op5) {this.op5 = op5;}
}
TitleCreator.java
package com.blipclap.engineering_solution.Models;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public class TitleCreator {
static TitleCreator _titleCreator;
List<TitleParent> _titleParents;
public TitleCreator(Context context) {
_titleParents = new ArrayList<>();
for (int i=1;i<=8;i++)
{
TitleParent title = new TitleParent(String.format("SEM%d",i));
_titleParents.add(title);
}
}
public static TitleCreator get(Context context)
{
if (_titleCreator==null)
_titleCreator=new TitleCreator(context);
return _titleCreator;
}
public List<TitleParent> getall() {
return _titleParents;
}
}
**TitleParent.java**
package com.blipclap.engineering_solution.Models;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import java.util.List;
import java.util.UUID;
public class TitleParent implements ParentObject {
private List<Object> mChildrenList;
private UUID _id;
private String title;
public TitleParent(String title) {
this.title = title;
_id=UUID.randomUUID();
}
public UUID get_id() {
return _id;
}
public void set_id(UUID _id) {
this._id = _id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public List<Object> getChildObjectList() {
return mChildrenList;
}
#Override
public void setChildObjectList(List<Object> list) {
mChildrenList=list;
}
}
TitleChildViewHolder.java
package com.blipclap.engineering_solution.ViewHolder;
import android.view.View;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ChildViewHolder;
import com.blipclap.engineering_solution.R;
public class TitleChildViewHolder extends ChildViewHolder {
public TextView op1,op2,op3,op4,op5;
public TitleChildViewHolder(View itemView) {
super(itemView);
op1 =(TextView)itemView.findViewById(R.id.op1);
op2 =(TextView)itemView.findViewById(R.id.op2);
op3 =(TextView)itemView.findViewById(R.id.op3);
op4 =(TextView)itemView.findViewById(R.id.op4);
op5 =(TextView)itemView.findViewById(R.id.op5);
}
}
TitleParentViewHolder.java
package com.blipclap.engineering_solution.ViewHolder;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ParentViewHolder;
import com.blipclap.engineering_solution.R;
public class TitleParentViewHolder extends ParentViewHolder {
public TextView _textview;
public ImageButton _imagebutton;
public TitleParentViewHolder(View itemView) {
super(itemView);
_textview = (TextView)itemView.findViewById(R.id.parentTitle);
_imagebutton =(ImageButton) itemView.findViewById(R.id.expandArrow);
}
}
SYFragment.java
package com.blipclap.engineering_solution;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import com.blipclap.engineering_solution.Adapter.adapter;
import com.blipclap.engineering_solution.Models.TitleChild;
import com.blipclap.engineering_solution.Models.TitleCreator;
import com.blipclap.engineering_solution.Models.TitleParent;
import java.util.ArrayList;
import java.util.List;
public class SYFragment extends Fragment {
RecyclerView recyclerView;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
((adapter)recyclerView.getAdapter()).onSaveInstanceState(outState);
}
private List<ParentObject> initData() {
TitleCreator titleCreator =TitleCreator.get(getActivity());
List<TitleParent> titles = titleCreator.getall();
List<ParentObject> parentObjects =new ArrayList<>();
for (TitleParent title:titles)
{
List<Object> childList =new ArrayList<>();
childList.add(new TitleChild("I.T","C.E","EXTC","MECH","CIVIL" ));
title.setChildObjectList(childList);
parentObjects.add(title);
}
return parentObjects;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
super.onCreate(savedInstanceState);
View rootView =inflater.inflate(R.layout.fragment_sy, container, false);
recyclerView =(RecyclerView)rootView.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter adapter =new adapter(getActivity(),initData());
adapter.setParentClickableViewAnimationDefaultDuration();
adapter.setParentAndIconExpandOnClick(true);
recyclerView.setAdapter(adapter);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Syllabus");
}
}
list_child.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/op1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="op1" />
<TextView
android:id="#+id/op2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/op1"
android:padding="8dp"
android:text="op2" />
<TextView
android:id="#+id/op3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/op2"
android:padding="8dp"
android:text="op3" />
<TextView
android:id="#+id/op4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/op3"
android:padding="8dp"
android:text="op4" />
<TextView
android:id="#+id/op5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/op4"
android:padding="8dp"
android:text="op5" />
</RelativeLayout>
</android.support.v7.widget.CardView>
**list_parent.xml**
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/parentTitle"
android:padding="16dp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/expandArrow"
android:visibility="gone"
android:layout_alignParentRight="true"
android:layout_margin="8dp"
android:src="#android:drawable/arrow_down_float"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
fragment_sy.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.blipclap.engineering_solution.SYFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview"></android.support.v7.widget.RecyclerView>
</FrameLayout>
click code
How should i implement this code in my project it should be like whenever i click clid option specific pdf should open
Anyone can help with this.
whenever i add this i end up with errors.
#Override
public void onBindChildViewHolder(IssueViewHolder issueViewHolder, int position, Object childListItem) {
Issue issue = (Issue) childListItem;
issueViewHolder.bind(issue);
issueViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//your code
}
});
}
Define interface in your adapter class
public interface onItemClickListener {
void onItemClicked(View view, int position);
}
public void setOnItemClickListener(onItemClickListener listener) {
this.onItemClickListener = listener;
}
On your Custom View Holder Implement View.OnClickListner and set Click Listener for required view.
public static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CustomViewHolder(View itemView){
super(itemView);
yourview.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onItemClickListener.onItemClicked(view, getAdapterPosition());
}
}
Now in the Adapter object just add setOnItemClickListener and you can bifurcate click event using the id of the view.
yourAdapter.setOnItemClickListener(new YourAdapter.onItemClickListener() {
#Override
public void onItemClicked(View view, int position) {
// view.getId()
});

RecyclerView not displaying all properties of arraylist

I am trying to make my first app using android studio. On the main activity I am trying to create a menu in the style of a grid using the RecyclerView. I want each menu option to have a title, description and a image.
Currently there are only 3 options on the menu whilst I'm testing. When I debug my app it kinda works but not as I expected. In that when it loads it shows the titles of the 3 options in my arrayList but not the descriptions or the images. I have checked that the description and image fields are correctly populated in my arrayList. I am not sure why it is only showing the titles? Below is my code.
code - XML
activity_main
<?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="match_parent"
tools:context="com.example.mark.spanishapp.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/esp_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
menu_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/menuImg"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
code - Java
MainActivity
package com.example.mark.spanishapp;
import android.database.sqlite.SQLiteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
DBHandler dbHandler = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHandler = new DBHandler(this);
try {
dbHandler.createDataBase();
}catch (IOException ioe){
throw new Error("unable to create database");
}
try{
dbHandler.openDataBase();
}catch (SQLException sqle)
{
Log.e(TAG, sqle.getMessage());
}
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.esp_menu);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(layoutManager);
ArrayList<MenuEsp> menuList = dbHandler.Get_MenuList();
MyAdapter adapter = new MyAdapter(getApplicationContext(), menuList);
recyclerView.setAdapter(adapter);
}
}
MenuEsp
package com.example.mark.spanishapp;
public class MenuEsp {
public String getMenu() {
return menu;
}
public void setMenu(String menu) {
this.menu = menu;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
private String menu;
private String description;
private String imageName;
}
MyAdapter
package com.example.mark.spanishapp;
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 java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<MenuEsp> menuList;
private Context context;
public MyAdapter(Context context, ArrayList<MenuEsp> menuList){
this.context = context;
this.menuList = menuList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
holder.title.setText(menuList.get(position).getMenu());
holder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
int id = this.context.getResources().getIdentifier(menuList.get(position).getImageName(), "drawable", this.context.getPackageName());
holder.img.setImageResource(id);
}
#Override
public int getItemCount() {
return menuList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private TextView descirption;
private ImageView img;
public ViewHolder(View view) {
super(view);
descirption = (TextView)view.findViewById(R.id.description);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.menuImg);
}
}
}
Set value of description in onBindViewholder
ie
holder.descirption.setText(menuList.get(position).getDescription());
next,
change code from
int id = this.context.getResources().getIdentifier(menuList.get(position).getImageName(), "drawable", this.context.getPackageName());
holder.img.setImageResource(id);
To
holder.img.setImageResource(Integer.parseInt(menuList.get(position).getImageName()));
make changes to your onBindViewHolder() method in your Adapter class
int id = this.context.getResources().getIdentifier(menuList.get(position).getImageName(), "drawable", this.context.getPackageName());
holder.img.setImageResource(id);
holder.descirption.setText(menuList.get(position).getDescription());

Retrieve data from SQLite in RecyclerView

having problem in showing data in fragment from SQLite via recyclerView. When i click showfragment button it crash and show "Unfortunately App stoped".It has 6 java class and 4 xml
I'm giving my code below
DbHelperAdapter.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DbHelperAdapter{
DbHelper helper;
public DbHelperAdapter(Context context){
helper=new DbHelper(context);
}
public long insetData(String name,String password){
SQLiteDatabase db=helper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(DbHelper.NAME,name);
contentValues.put(DbHelper.PASSWORD,password);
long id=db.insert(DbHelper.TABLE_NAME,null,contentValues);
db.close();
return id;
}
public String getAllData(){
SQLiteDatabase db= helper.getWritableDatabase();
String[] columns={DbHelper.UID,DbHelper.NAME,DbHelper.PASSWORD};
Cursor cursor=db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
int cid=cursor.getInt(cursor.getColumnIndex(DbHelper.UID));
String name = cursor.getString(cursor.getColumnIndex(DbHelper.NAME));
String pass = cursor.getString(cursor.getColumnIndex(DbHelper.PASSWORD));
buffer.append(cid+" "+name+" "+pass+"\n");
}
return buffer.toString();
}
public List<Information> getAllData_a(){
SQLiteDatabase db= helper.getWritableDatabase();
String[] columns={DbHelper.UID,DbHelper.NAME,DbHelper.PASSWORD};
Cursor cursor=db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, null);
List<Information> data=new ArrayList<>();
while (cursor.moveToNext()){
int cid=cursor.getInt(cursor.getColumnIndex(DbHelper.UID));
String name = cursor.getString(cursor.getColumnIndex(DbHelper.NAME));
String pass = cursor.getString(cursor.getColumnIndex(DbHelper.PASSWORD));
Information current = new Information();
current.u_id=cid;
current.user=name;
current.pass=pass;
data.add(current);
}
return data;
}
public String getData(String name){
SQLiteDatabase db= helper.getWritableDatabase();
String[] columns={DbHelper.NAME,DbHelper.PASSWORD};
Cursor cursor=db.query(DbHelper.TABLE_NAME, columns, DbHelper.NAME+" = '"+name+"' ", null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
String PersonName = cursor.getString(cursor.getColumnIndex(DbHelper.NAME));
String pass = cursor.getString(cursor.getColumnIndex(DbHelper.PASSWORD));
buffer.append(PersonName+" "+pass+"\n");
}
return buffer.toString();
}
static class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "demo";
private static final String TABLE_NAME = "tbl_demo";
private static final int VERSION_NAME=3;
private static final String UID="_id";
private static final String NAME="name";
private static final String PASSWORD="Password";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255),"+PASSWORD+" VARCHAR(255));";
private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME+"";
private Context context;
public DbHelper(Context context){
super(context,DATABASE_NAME,null,VERSION_NAME);
this.context=context;
Message.message(context, "constructorCalled");
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
Message.message(context, "onCreateCalled");
}catch (android.database.SQLException e){
Message.message(context, ""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context, "onUpgradeCalled");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (android.database.SQLException e) {
Message.message(context, ""+e);
}
}
}
}
Information.java
public class Information {
int u_id;
String user;
String pass;}
MainActivity.java
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.support.v4.app.Fragment;
public class MainActivity extends ActionBarActivity {
DbHelperAdapter dbHelperAdapter;
EditText userName;
EditText password;
EditText selectionName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelperAdapter = new DbHelperAdapter(this);
userName= (EditText) findViewById(R.id.username);
password= (EditText) findViewById(R.id.password);
selectionName= (EditText) findViewById(R.id.selection_name);
}
public void addUser(View view){
String user = userName.getText().toString();
String pass = password.getText().toString();
long id = dbHelperAdapter.insetData(user,pass);
if(id<0){
Message.message(this,"Unsuccessful");
}
else {
Message.message(this,"Successfully insert A Row");
}
}
public void getTheFragment(View view){
Intent i= new Intent(this,MainActivity2.class);
startActivity(i);
}
public void viewDetails(View view){
String data=dbHelperAdapter.getAllData();
Message.message(this,data);
}
public void getDataBySelection(View view){
String name = selectionName.getText().toString();
String selections=dbHelperAdapter.getData(name);
Message.message(this,selections);
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}}
MainActivity2.java
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.support.v7.app.ActionBarActivity;
import android.os.Bundle;
public class MainActivity2 extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
return new MyFragment();
}
#Override
public int getCount() {
return 1;
}
}}
Myfragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFragment extends Fragment {
RecyclerView recyclerView;
RecyclerViewAdapter adapter;
DbHelperAdapter dbHelperAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout=inflater.inflate(R.layout.fragment_new, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.list);
adapter = new RecyclerViewAdapter(getActivity(),dbHelperAdapter.getAllData_a());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}}
RecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private LayoutInflater inflater;
List<Information> data= Collections.emptyList();
public RecyclerViewAdapter(Context context, List<Information> data){
inflater = LayoutInflater.from(context);
this.data =data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.custom_raw,parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.UID.setText(current.u_id);
holder.USER.setText(current.user);
holder.PASS.setText(current.pass);
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView UID;
TextView USER;
TextView PASS;
public MyViewHolder(View itemView) {
super(itemView);
UID= (TextView) itemView.findViewById(R.id.u_id);
USER = (TextView) itemView.findViewById(R.id.user);
PASS = (TextView) itemView.findViewById(R.id.pass);
}
}}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText"
/>
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:onClick="addUser"
android:text="#string/add_user" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="viewDetails"
android:text="View Details"
android:id="#+id/view_details_btn"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/selection_name"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="GetSelectedData"
android:onClick="getDataBySelection"
android:id="#+id/getDataBySelection" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Fragment"
android:onClick="getTheFragment"
android:id="#+id/show_fragment"
/>
</LinearLayout>
activity_main_activity2.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
custom_raw.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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/u_id"
android:layout_gravity="center"
android:text="UID"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/user"
android:layout_gravity="center"
android:text="NAME"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/pass"
android:layout_gravity="center"
android:text="PASSWORD"/>
</LinearLayout>
fagment_new.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.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
google drive link: https://drive.google.com/folderview?id=0B0uBfXsWeMlgX0U5OE8tREhxQkk&usp=sharing
logcat errors:
02-02 22:15:27.455 10562-10562/com.maticoders.databasetest E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.NullPointerException
at com.maticoders.databasetest.MyFragment.onCreateView(MyFragment.java:29)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:15635)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15635)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
at android.view.View.measure(View.java:15635)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15635)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1411)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:698)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15635)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2200)
at android.view.View.measure(View.java:15635)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2165)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1249)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1443)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4872)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Errors were in my RecyclerViewAdapter Class
i didn't pass the context and passed an integer in textView
here is my RecylerViewAdapter Class
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context context;
private LayoutInflater inflater;
List<Information> data= Collections.emptyList();
public RecyclerViewAdapter(Context context, List<Information> data){
this.context=context;
inflater = LayoutInflater.from(context);
this.data =data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.custom_raw,parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.UID.setText(String.valueOf(current.u_id));
holder.USER.setText(current.user);
holder.PASS.setText(current.pass);
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView UID;
TextView USER;
TextView PASS;
public MyViewHolder(View itemView) {
super(itemView);
UID= (TextView) itemView.findViewById(R.id.u_id);
USER = (TextView) itemView.findViewById(R.id.user);
PASS = (TextView) itemView.findViewById(R.id.pass);
}
}
}

Categories