I've got an app which saves a number and the date it was recorded in a recycler View, however when the array is empty and then I try to save my number, the RecyclerView does not show the item. The item did save, but it isn't displayed in the view. I know it save because when I go back to the view the item is there. I have looked ages for answer online and have seen nobody with the same issue. Thank you in advance for your help!
Activity 2:
package com.pinet.count;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class Activity2 extends AppCompatActivity {
private ExampleAdapter mAdapter;
private static final Date currentTime = Calendar.getInstance().getTime();
private ArrayList<ExampleItem> mexampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Intent intent = getIntent();
String dateString= DateFormat.format("dd/MM/yyyy",currentTime).toString();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
buildRecyclerView();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
mexampleList.add(0, new ExampleItem(String.valueOf(count), dateString));
mAdapter.notifyItemInserted(0);
mAdapter.notifyItemRangeChanged(0,mexampleList.size());
}
saveList();
}
private void buildRecyclerView(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mAdapter= new ExampleAdapter(mexampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
private void removeItem(int position){
mexampleList.remove(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, mexampleList.size());
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",0);
sharedPreferences.edit().remove("count list").apply();
}package com.pinet.count;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class Activity2 extends AppCompatActivity {
private ExampleAdapter mAdapter;
private static final Date currentTime = Calendar.getInstance().getTime();
private ArrayList<ExampleItem> mexampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Intent intent = getIntent();
String dateString= DateFormat.format("dd/MM/yyyy",currentTime).toString();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
buildRecyclerView();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
mexampleList.add(0, new ExampleItem(String.valueOf(count), dateString));
mAdapter.notifyItemInserted(0);
mAdapter.notifyItemRangeChanged(0,mexampleList.size());
}
saveList();
}
private void buildRecyclerView(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mAdapter= new ExampleAdapter(mexampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
private void removeItem(int position){
mexampleList.remove(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, mexampleList.size());
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",0);
sharedPreferences.edit().remove("count list").apply();
}
private void saveList(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mexampleList);
editor.putString("count list", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("count list", null);
Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
mexampleList = gson.fromJson(json, type);
}
}
`
private void saveList(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mexampleList);
editor.putString("count list", json);
editor.apply();
}
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("count list", null);
Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
mexampleList = gson.fromJson(json, type);
}
}
Main Activity:
package com.pinet.count;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int count = 0;
public static final String EXTRA_NUMBER ="com.pinet.count.EXTRA_NUMBER";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView= findViewById(R.id.textView);
Button buttonPos = findViewById(R.id.button);
Button buttonNeg = findViewById(R.id.button2);
Button buttonReset = findViewById(R.id.button3);
Button buttonSave = findViewById(R.id.button4);
Button butonHistory = findViewById(R.id.button5);
buttonPos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count +=1;
textView.setText(String.valueOf(count));
}
});
buttonNeg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count-=1;
textView.setText(String.valueOf(count));
}
});
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count = 0;
textView.setText(String.valueOf(count));
}
});
butonHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenActivity2();
}
});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity2();
}
});
}
private void openActivity2(){
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(EXTRA_NUMBER, count);
startActivity(intent);
}
private void OpenActivity2(){
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
}
ExampleAdapter:
package com.pinet.count;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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 ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private final ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
final TextView mTextView1;
final TextView mTextView2;
final ImageView mDeleteImage;
ExampleViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1=itemView.findViewById(R.id.textView);
mTextView2=itemView.findViewById(R.id.textView2);
mDeleteImage=itemView.findViewById(R.id.image_delete);
mDeleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener !=null){
int position = getAdapterPosition();
if (position!=RecyclerView.NO_POSITION){
listener.onDeleteClick(position);
}
}
}
});
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList){
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
return new ExampleViewHolder(v, mListener);
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mTextView1.setText(currentItem.getmText1());
holder.mTextView2.setText(currentItem.getmText2());
}
#Override
public int getItemCount() {
if (mExampleList !=null) {
return mExampleList.size();
}
else {
return 0;
}
}
}
ExampleItem :
package com.pinet.count;
class ExampleItem {
private final String mText1;
private final String mText2;
public ExampleItem(String text1, String text2){
mText1= text1;
mText2= text2;
}
public String getmText1(){
return mText1;
}
public String getmText2(){
return mText2;
}
}
If you could also help me figure out animating the recycler view that would be appreciated !
PiNet
Change your onCreate() method inside the "Activity2" Activity to look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
String dateString = DateFormat.format("dd/MM/yyyy",currentTime).toString();
Intent intent = getIntent();
int count = intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);
loadData();
if (count!=0){
if (mexampleList == null){
mexampleList = new ArrayList<ExampleItem>();
}
String value = String.valueOf(count);
ExampleItem exampleItem = new ExampleItem(value, dateString);
mexampleList.add(0, exampleItem);
}
buildRecyclerView();
saveList();
}
I've changed the order of adding the new data to the ArrayList. This way the "new item" will be added to the list before you set the adapter. I have also extrapolated some if the code into distinct code lines. I recommend this because it will be easier to debug.
A few additional comments:
The method removeItem(int position) appears to remove the entire list from your SharedPreferences instead of what I assume you only want to remove the one item.
Also in your "MainActivity" you have two methods:
openActivity2()
and
OpenActivity2()
Firstly, Java naming convention dictates that method names begin with lower case. Secondly, this is very poor programing style to give methods indistinguishable method names.
Related
I am working with a project and I am trying to fetch some link from a json data and I want to connect the link with a button in my recycleview so that whenever the button is clicked, it'll automatically connet to the respective websites. I gave user permission to interner in Manifest. So, How to connect it?
package com.example.covidcuretemplate1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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 RequestQueue requestQueue;
private ExampleAdapter exampleAdapter;
private ArrayList<ExampleItem> exampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL,false));
exampleList = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "https://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=*************************";
JsonObjectRequest request = 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 article = jsonArray.getJSONObject(i);
if(article.isNull("description") || article.isNull("urlToImage")) {
continue;
}
if(article.getString("description").isEmpty() || article.getString("urlToImage").isEmpty())
continue;
String title = article.getString("title");
String description = article.getString("description");
String date = article.getString("publishedAt");
String imageurl = article.getString("urlToImage");
//How to connect this??????
String newsurl = article.getString("url");
exampleList.add(new ExampleItem(imageurl,title,description,date));
}
exampleAdapter = new ExampleAdapter(MainActivity.this,exampleList);
recyclerView.setAdapter(exampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
My Adapter class, Here can anybody suggest anything in the place of toast? The Toast is working fine !!!
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
public Context mcontext;
public ArrayList<ExampleItem> marrayList;
public ExampleAdapter(Context mcontext, ArrayList<ExampleItem> marrayList) {
this.mcontext = mcontext;
this.marrayList = marrayList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mcontext).inflate(R.layout.card_item,parent,false);
ExampleViewHolder exampleViewHolder = new ExampleViewHolder(view);
return exampleViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem examplItem = marrayList.get(position);
String imageurl = examplItem.getMimgurl();
String title = examplItem.getMtitle();
String description = examplItem.getMdescription();
String date = examplItem.getMdate();
/////////////
final String newsurl = examplItem.getMurl();
////////////
holder.textview_title.setText(title);
holder.textview_description.setText(description);
holder.textview_date.setText(date);
Glide.with(mcontext).load(imageurl).into(holder.imageview_news);
///////////////////////////
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//////////////////////////////////NEED HELP!!!!!!!!!!!!!!!!!!/////////
Toast.makeText(mcontext,newsurl,Toast.LENGTH_LONG).show();
}
});
//////////////////////////
}
#Override
public int getItemCount() {
return marrayList.size();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public ImageView imageview_news;
public TextView textview_title;
public TextView textview_description;
public TextView textview_date;
///////////////////////////
public Button button;
///////////////////////////
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
imageview_news = itemView.findViewById(R.id.imageview_news);
textview_title = itemView.findViewById(R.id.textview_title);
textview_description = itemView.findViewById(R.id.textview_description);
textview_date = itemView.findViewById(R.id.textview_date);
/////////////////////////
button = itemView.findViewById(R.id.button);
////////////////////////
}
}
}
Try to set intent for the website inside the onClickListener. Something like this:
Button button= findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = "http://www.YourWebsite.com"; //insert the link you prase
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
You can use this code inside onClickListener to open it in the browser.
Uri uri = Uri.parse(newsurl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
I made small app that gets some values from the user and display it in custom listview in another activity (2nd) after pressing the button in the 1st activity.
The situation now it's works but only after I closing the app and reopen it.
I want it will work immediately after I press the button.
Can someone help me with this issue please ?
mainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList<exampleItem> mExampleList = new ArrayList<>();
RecyclerView mRecyclerView;
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
setInsertButton();
loadData();
buildRecyclerView();
}
private void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new exampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences8", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list8", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
}
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences8", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list8", json);
editor.apply();
}
private void setInsertButton() {
Button buttonInsert = findViewById(R.id.insert2);
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText line1 = findViewById(R.id.categ2);
final EditText lineimg = findViewById(R.id.summ2);
final EditText line2 = findViewById(R.id.date22);
String lin1 = line1.getText().toString();
String lin2 = line2.getText().toString();
String lin3 = lineimg.getText().toString();
mExampleList.add(new exampleItem(lin1, lin3, lin2));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
saveData();
}
});
}
}
mainActivity2
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<exampleItem> mExampleList = new ArrayList<>();
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setInsertButton();
loadData();
//buildRecyclerView();
}
private void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new exampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences8", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list8", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
}
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences8", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list8", json);
editor.apply();
}
private void setInsertButton() {
Button buttonInsert = findViewById(R.id.insert);
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText line1 = findViewById(R.id.categ);
final EditText lineimg = findViewById(R.id.summ);
final EditText line2 = findViewById(R.id.date2);
String lin1 = line1.getText().toString();
String lin2 = line2.getText().toString();
String lin3 = lineimg.getText().toString();
mExampleList.add(new exampleItem(lin3, lin2, lin1));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
saveData();
finish();
}
});
}
}
Adapter
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class exampleAdapter extends RecyclerView.Adapter<exampleAdapter.ExampleViewHolder> {
private ArrayList<exampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewLine1;
public TextView mTextViewLine2;
public ImageView imageView;
public ExampleViewHolder(View itemView) {
super(itemView);
mTextViewLine1 = itemView.findViewById(R.id.textview_line1);
mTextViewLine2 = itemView.findViewById(R.id.textview_line2);
imageView = itemView.findViewById(R.id.icond);
}
}
public exampleAdapter(ArrayList<exampleItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
exampleItem currentItem = mExampleList.get(position);
holder.mTextViewLine1.setText(currentItem.getLine1());
holder.mTextViewLine2.setText(currentItem.getLine2());
if (currentItem.getLineimg().equalsIgnoreCase("s")) {
holder.imageView.setImageResource(R.drawable.salary);
}
if (currentItem.getLineimg().equalsIgnoreCase("e")){
holder.imageView.setImageResource(R.drawable.money);
}
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Inside loadData() you need to call notifyDataSetChanged() on the mAdapter.
In the class MainActivity under the function "loadData()" you must update the adapter notifying that the data has changed.
The function (loadData()) should look something like:
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared
preferences8", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list8", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
mAdapter.notifyDataSetChanged()
}
This is my HomeActivity
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> mlist;
TextView btnSignOut, UserName;
RecyclerView courseRecycler;
String CourseCode, CourseName;
/*---- Firebase Database stuff ----*/
FirebaseDatabase mFirebaseDatabase;
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
Button btnShow = findViewById(R.id.show);
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
courseRecycler = findViewById(R.id.recyclerviewcourse);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getInstance().getReference();
UserName.setText(user.getDisplayName());
/*------------------------------------------------------------------*/
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.
mlist = new ArrayList<CourseModel>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) {
CourseModel value = dataSnapshot1.getValue(CourseModel.class);
CourseModel course = new CourseModel();
String userID = value.getUserId();
course.setUserId(userID);
String courseCode = value.getCourseCode();
course.setCourseCode(courseCode);
for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) {
CourseModel value2 = dataSnapshot2.getValue(CourseModel.class);
String courseName = value2.getCourseName();
course.setCourseName(courseName);
mlist.add(course);
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse recyclerAdapter = new RecyclerViewAdapterCourse(mlist, HomeActivity.this);
RecyclerView.LayoutManager recycler = new GridLayoutManager(HomeActivity.this, 2);
/// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
// recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
courseRecycler.setLayoutManager(recycler);
courseRecycler.setItemAnimator(new DefaultItemAnimator());
courseRecycler.setAdapter(recyclerAdapter);
}
}
This is My RecyclerViewCourse.class
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
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.TextView;
import java.util.List;
class RecyclerViewAdapterCourse extends RecyclerView.Adapter<RecyclerViewAdapterCourse.CourseViewHolder> {
private Context mContext ;
private List<CourseModel> mlist ;
public RecyclerViewAdapterCourse(List<CourseModel> mData, Context mContext) {
this.mContext = mContext;
this.mlist = mData;
}
#Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =LayoutInflater.from(mContext).inflate(R.layout.item_course,parent,false);
CourseViewHolder courseViewHolder = new CourseViewHolder(view);
return courseViewHolder;
}
#Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
CourseModel courselist = mlist.get(position);
holder.userID.setText(courselist.getUserId());
holder.courseCode.setText(courselist.getCourseCode());
holder.courseName.setText(courselist.getCourseName());
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(mlist.size()==0){
arr = 0;
}
else{
arr=mlist.size();
}
}catch (Exception e){
}
return arr;
}
class CourseViewHolder extends RecyclerView.ViewHolder{
TextView userID,courseCode,courseName;
public CourseViewHolder(View itemView) {
super(itemView);
userID = (TextView) itemView.findViewById(R.id.userid);
courseCode= (TextView) itemView.findViewById(R.id.coursecode);
courseName= (TextView) itemView.findViewById(R.id.coursename);
}
}
}
This is My CourseModel.class
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
public class CourseModel {
public String UserId, CourseCode, CourseName;
public String getUserId() {
return UserId;
}
public String getCourseCode() {
return CourseCode;
}
public String getCourseName() {
return CourseName;
}
public void setUserId(String userid) {
this.UserId = userid;
}
public void setCourseCode(String coursecode) {
this.CourseCode = coursecode;
}
public void setCourseName(String coursename) {
this.CourseCode = coursename;
}
}
I want the array list like:
{"***", "TMI4013", "System Programming"}
{"***", "TMI4033", "LogicProgramming"}
I am not really experienced with firebase data retrieval in array. I tried many answers posted in stack. none worked. in some answers, sometime it shows data after a while and then in the realtime database the data get removed, i don't even understand why.
I did not provide the XML files since I tried with local file and generating array in HomeActivity and it worked perfectly.
mlist = new ArrayList<>();
mlist.add(new CourseModel("012223","TMN4013","System Programming"));
mlist.add(new CourseModel("34566","TMN4013","System Programming"));
RecyclerView myrv = (RecyclerView) findViewById(R.id.recyclerview_id);
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,mlist);
myrv.setLayoutManager(new GridLayoutManager(this,3));
myrv.setAdapter(myAdapter);
Retrieve data from firebase and convert list into array like this
for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) {
CourseModel value = dataSnapshot1.getValue(CourseModel.class);
CourseModel course = new CourseModel();
String userID = value.getUserId(); course.setUserId(userID);
String courseCode = value.getCourseCode();
course.setCourseCode(courseCode);
for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) {
CourseModel value2 = dataSnapshot2.getValue(CourseModel.class);
String courseName = value2.getCourseName();
course.setCourseName(courseName);
mlist.add(course);
}
}
CourseModel[] array = mlist.toArray(new CourseModel[mlist.size()]);
EDIT:
Change your adapter like this
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this, array);
Change the constructor of recyclerView to CourseModel array
public RecyclerViewAdapterCourse(CourseModel[] mData, Context mContext) {
this.mContext = mContext;
this.mArray = mData;
}
#Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
CourseModel courselist = marray[position];
holder.userID.setText(courselist.getUserId());
holder.courseCode.setText(courselist.getCourseCode());
holder.courseName.setText(courselist.getCourseName());
}
I have a ListView fragment that has the option to save specific table values. You can click a button to toggle the table to only show saved values. When the toggle is active instead of saving you have the option to delete values. I have noticed however that while the delete will delete the value permanently so long as the app is open, If i close the app and reopen it, the value will reappear. Also if I delete the app and reinstall this same value reappears. I'm not sure how this value is getting added in and why it refuses to go. Debugging shows me saving the correct values in SharedPreferences but that does not stay.
EDIT: After some more testing it appears that the first item saved in the specific SharedPreferences remains permanently saved. It cannot be removed and all other values saved will not remain there.
Fragment:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.os.StrictMode;
import com.tble.brgo.HTMLPull;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.text.TextUtils;
import java.util.HashSet;
import java.util.Set;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Websites#newInstance} factory method to
* create an instance of this fragment.
*/
public class Websites extends Fragment implements SearchView.OnQueryTextListener, displayInterface {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private SearchView mSearchView;
private ListView mListView;
public Boolean toggle = false;
public ArrayList<InfoArticle> mData = new ArrayList<InfoArticle>();
public StandardCellAdapter mAdapter;
public ArrayList<InfoArticle> fDataSet = new ArrayList<InfoArticle>();
public Websites webTable;
public Websites() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment Websites.
*/
// TODO: Rename and change types and number of parameters
public static Websites newInstance() {
Websites fragment = new Websites();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toggle = false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_websites, container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<InfoArticle> data = new ArrayList<InfoArticle>();
webTable = this;
try {
data = getData();
} catch (IOException e) {
e.printStackTrace();
}
mListView = (ListView) view.findViewById(R.id.WebsiteTable);
final StandardCellAdapter adapter = new StandardCellAdapter(getActivity(), data, 1,this);
fDataSet = data;
mData = data;
mListView.setAdapter(adapter);
mAdapter = adapter;
mSearchView = (SearchView) view.findViewById(R.id.searchView);
mListView.setTextFilterEnabled(true);
FloatingActionButton myFab = (FloatingActionButton) view.findViewById(R.id.dataToggle);
myFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggleView();
}
});
setupSearchView();
final SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.webRefresh);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
try {
mData = getData();
mAdapter = new StandardCellAdapter(getContext(), mData, 1,webTable);
mListView.setAdapter(mAdapter);
} catch (IOException e) {
e.printStackTrace();
}
swipeLayout.setRefreshing(false);
}
});
return view;
}
private void setupSearchView() {
mSearchView.setOnQueryTextListener(this);
mSearchView.setIconifiedByDefault(true);
}
private ArrayList<InfoArticle> getData() throws IOException {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
int school = sharedPref.getInt("School", 14273);
HTMLPull Connection = new HTMLPull();
Connection.getStaff(school);
Connection.Results.remove(0);
return Connection.Results;
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText);
}
return true;
}
public ArrayList<InfoArticle> toData(ArrayList<String> t, ArrayList<String> d) {
ArrayList<InfoArticle> temp = new ArrayList<InfoArticle>();
if (t.size() == 0) {
temp.add(new InfoArticle("Slide to Save Teachers", "google.com"));
} else {
for (int i = 0; i < t.size(); i++) {
temp.add(new InfoArticle(t.get(i), d.get(i)));
}
}
return temp;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private void toggleView(){
if (!toggle) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
HashSet<String> defv = new HashSet<String>();
ArrayList<String> teachers = new ArrayList<String>(sharedPref.getStringSet("teachPref", defv));
ArrayList<String> links = new ArrayList<String>(sharedPref.getStringSet("linkPref", defv));
mAdapter = new StandardCellAdapter(getContext(), toData(teachers, links),2,this);
mListView.setAdapter(mAdapter);
toggle = true;
} else {
mAdapter = new StandardCellAdapter(getContext(), mData, 1,this);
mListView.setAdapter(mAdapter);
toggle = false;
}
}
/**public void displayWebpage(int position){
if (toggle == true) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(mAdapter.getItem(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
} else {
if (!mSearchView.isIconified()) {
for (InfoArticle a : fDataSet) {
if (a.title.equals(((InfoArticle) mListView.getAdapter().getItem(position)).title)) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(a.description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
} else {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(fDataSet.get(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
}*/
public void displayWebpage(String Link){
WebsiteDisplay fullView = WebsiteDisplay.newInstance(Link);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
CellAdapter:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.Image;
import android.nfc.Tag;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.view.View;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.preference.PreferenceManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.graphics.Typeface;
import android.widget.Filterable;
import android.widget.Filter;
import org.w3c.dom.Text;
/**
* Created by Praveen on 8/21/16.
*/
public class StandardCellAdapter extends ArrayAdapter<InfoArticle> implements Filterable {
public ArrayList<InfoArticle> orig;
public ArrayList<InfoArticle> Teachers;
public SwipeRevealLayout swipeV;
public TextView deleteButton;
public TextView saveButton;
public int tableType;
public displayInterface activity;
public Context ct;
public StandardCellAdapter(Context context, ArrayList<InfoArticle> titles, int tableType, displayInterface inter) {
super(context, 0, titles);
this.Teachers = titles;
this.tableType = tableType;
saveButton = new TextView(context);
deleteButton = new TextView(context);
activity = inter;
ct = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String title = getItem(position).title;
String desc = getItem(position).description;
Holder TagHolder = null;
TextView Ctitle;
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
if (tableType == 0) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.nclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
else if(tableType == 1){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.sclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.scSwipe);
saveButton = (TextView)convertView.findViewById(R.id.saveButton);
TagHolder.Save = saveButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
else{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.tclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.tcSwipe);
deleteButton = (TextView) convertView.findViewById(R.id.deleteButton);
TagHolder.Delete = deleteButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
}
else {
TagHolder = (Holder) convertView.getTag();
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
if(tableType == 1) {
TagHolder.Save.setTag(position);
TagHolder.Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTeacher((int)v.getTag());
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
else if(tableType == 2) {
TagHolder.Delete.setTag(position);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteTeacher((int)v.getTag());
if(Teachers.size() == 0)
Teachers.add(new InfoArticle("Slide to Save Teachers", "google.com"));
notifyDataSetChanged();
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
Typeface customFont = Typeface.SERIF;
Ctitle.setTypeface(customFont);
Ctitle.setText(title);
return convertView;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<InfoArticle> results = new ArrayList<InfoArticle>();
if (orig == null)
orig = Teachers;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final InfoArticle g : orig) {
if (g.title.toLowerCase()
.contains(constraint.toString().toLowerCase())) {
results.add(g);
}
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
Teachers = (ArrayList<InfoArticle>)results.values;
notifyDataSetChanged();
}
};
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public ArrayList<InfoArticle> toIA(ArrayList<String> data){
ArrayList<InfoArticle> converted = new ArrayList<InfoArticle>();
for(String a: data)
{
converted.add(new InfoArticle(a,""));
}
return converted;
}
#Override
public int getCount() {
return Teachers.size();
}
#Override
public InfoArticle getItem(int position) {
return Teachers.get(position);
}
public void saveTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
teach.add(Teachers.get(position).title);
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
link.add(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
new AlertDialog.Builder(getContext())
.setTitle("Teacher Saved")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(true);
}
private void deleteTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
teach.remove(Teachers.get(position).title);
link.remove(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
HashSet<String> defv = new HashSet<String>();
Teachers.remove(position);
new AlertDialog.Builder(getContext())
.setTitle("Teacher Deleted")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(false);
}
class Holder{
TextView Delete;
TextView Save;
TextView Cell;
}
}
I'm using volley to load data using JSON Parsing in to a recycler view. I've used recylcer view before, but somehow, the downloaded data is persistent this time, meaning its still there after the app is closed, maybe stays in cache. I'm not sure, what I'm doing wrong here. Any help is appreciated, thanks.
Edit: The application is storing downloaded data after the app is closed, which doesn't happen when using recycler view.
This is my Activity Class:
package com.example.recyclerview;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity implements
OnItemClick{
private ArrayList<PostData> posts = new ArrayList<>();
private PostRecycleViewAdapter viewAdapter;
private String listingJsonUrl = "https://jsonplaceholder.typicode.com/posts/";
Toolbar toolbar;
private ProgressDialog progressDialog;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
final RecyclerView.LayoutManager viewLayoutManager = new LinearLayoutManager(getApplicationContext());
viewAdapter = new PostRecycleViewAdapter(posts);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(viewLayoutManager);
recyclerView.setAdapter(viewAdapter);
viewAdapter.setClickListener(this);
new DownloadData().execute(listingJsonUrl);
}
#Override
public void onClick(View view, int position) {
final PostData data = posts.get(position);
String title;
int id;
Intent commentIntent = new Intent(this, CommentsActivity.class);
id = data.getId();
title = data.getTitle();
if(title.length() > 25){
title = title.substring(0,25);
title = title.concat("..");
}
commentIntent.putExtra("title",title) ;
commentIntent.putExtra("id", id);
startActivity(commentIntent);
}
class DownloadData extends AsyncTask<String, String, String>{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... url) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url[0], new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PostData postData = new PostData(jsonObject.getInt("id"),jsonObject.getString("title"), jsonObject.getString("body"));
posts.add(postData);
viewAdapter.notifyDataSetChanged();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JsonError", error.getMessage());
}
});
getRequestQueue().add(jsonArrayRequest);
return null;
}
}
public RequestQueue getRequestQueue()
{
if (requestQueue == null)
{
requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
}
This is my RecyclerView Adapter Class:
package com.example.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostRecycleViewAdapter extends RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>
{
private List<PostData> postData;
private OnItemClick itemClick;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView title, body;
public ViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.title);
body = (TextView) view.findViewById(R.id.body);
view.setTag(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(itemClick != null) itemClick.onClick(view, getAdapterPosition());
}
}
public PostRecycleViewAdapter(List<PostData> postData)
{
this.postData = postData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_recycler_view,parent,false);
return new ViewHolder(itemLayout);
}
#Override
public void onBindViewHolder(PostRecycleViewAdapter.ViewHolder holder, int position) {
PostData data = postData.get(position);
holder.title.setText(data.getTitle());
holder.body.setText(data.getBody());
}
#Override
public int getItemCount() {
return postData.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);}
public void setClickListener(OnItemClick itemClick) {
this.itemClick = itemClick;
}
}
And this is the data item class:
package com.example.recyclerview;
public class PostData {
private String title, body;
private int id;
public PostData(int id, String title, String body)
{
this.id = id;
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getId() {
return id;
}
}