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()
}
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'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.
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());
}
Good afternoon guys, I am trying to fetch some data from the police data website.
Unfortunately, the application doesn't show any data saying "E/RecyclerView: No adapter attached; skipping layout".
I have attached the LatestCrimesActivity, adapter and the ListItem class.
Thank you for your help.
This is LatestCrimesActivity:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.cosmin.crimerate.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LatestCrimesActivity extends AppCompatActivity {
private static final String URL_DATA = "https://data.police.uk/api/crimes-street/all-crime?poly=52.268,0.543:52.794,0.238:52.130,0.478&date=2017-01";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_latest_crimes);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("");
for (int i=0; i<array.length();i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("category"),
o.getString("location_type"),
o.getString("street"),
o.getString("status")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Adapter:
package com.example.cosmin.crimerate.Latest_crimes_api;
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.Adapter;
import android.widget.TextView;
import com.example.cosmin.crimerate.R;
import java.util.List;
/**
* Created by Cosmin on 25/11/2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItems, LatestCrimesActivity latestCrimesActivity) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textViewCat.setText(listItem.getCategory());
holder.textViewLoc.setText(listItem.getLocation());
holder.textViewStreet.setText(listItem.getStreet());
holder.textViewStatus.setText(listItem.getStatus());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewCat;
public TextView textViewLoc;
public TextView textViewStreet;
public TextView textViewStatus;
public ViewHolder(View itemView) {
super(itemView);
textViewCat = (TextView) itemView.findViewById(R.id.textViewCat);
textViewLoc = (TextView) itemView.findViewById(R.id.textViewLoc);
textViewStreet = (TextView) itemView.findViewById(R.id.textViewStreet);
textViewStatus = (TextView) itemView.findViewById(R.id.textViewStatus);
}
}
}
This is ListItem class:
package com.example.cosmin.crimerate.Latest_crimes_api;
/**
* Created by Cosmin on 25/11/2017.
*/
public class ListItem {
private String category;
private String location;
private String street;
private String status;
public ListItem (String category, String location, String street, String status){
this.category=category;
this.location=location;
this.street=street;
this.status=status;
}
public String getCategory (){
return category;
}
public String getLocation (){
return location;
}
public String getStreet (){
return street;
}
public String getStatus (){
return status;
}
}
Just try to change some lines. First set adapter before your api call.
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
Then when you received the answer, fill listItems, then call notifyDataSetChange() method of your adapter object.
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;
}
}