How I can Remove NullpointerException in this case? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am using firebase database and want to show data in a listview.When I call onDataChange() of firebase database it shows nullpointer excetion. I find my best on google and many other sites but nothing helps me to get rid of this error, so please help me, I,m stuck on this error from last three hours...
Here is Mainactiviy named as Articles_from_firebase.java:
public class Articles_from_fireabse extends AppCompatActivity {
EditText editTextName;
Spinner spinnerGenre;
Button buttonAddArtist;
ListView listViewArtists;
DatabaseReference databaseArtists;
//a list to store all the artist from firebase database
List<Artist> artists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_articles_from_fireabse);
databaseArtists = FirebaseDatabase.getInstance().getReference("artists");
editTextName = (EditText) findViewById(R.id.editTextName);
spinnerGenre = (Spinner) findViewById(R.id.spinnerGenres);
listViewArtists = (ListView) findViewById(R.id.listViewArtists);
buttonAddArtist = (Button) findViewById(R.id.buttonAddArtist);
buttonAddArtist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//calling the method addArtist()
//the method is defined below
//this method is actually performing the write operation
addArtist();
}
});
}
private void addArtist() {
//getting the values to save
String name = editTextName.getText().toString().trim();
String genre = spinnerGenre.getSelectedItem().toString();
//checking if the value is provided
if (!TextUtils.isEmpty(name)) {
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Artist
String id = databaseArtists.push().getKey();
//creating an Artist Object
Artist artist = new Artist(id, name, genre);
//Saving the Artist
databaseArtists.child(id).setValue(artist);
//setting edittext to blank again
editTextName.setText("");
//displaying a success toast
Toast.makeText(this, "Artist added", Toast.LENGTH_LONG).show();
} else {
//if the value is not given displaying a toast
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStart() {
super.onStart();
//attaching value event listener
databaseArtists.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
artists.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
Artist artist = postSnapshot.getValue(Artist.class);
//adding artist to the list
artists.add(artist);
}
//creating adapter
ArtistList artistAdapter = new ArtistList(Articles_from_fireabse.this, artists);
//attaching adapter to the listview
listViewArtists.setAdapter(artistAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Here is my 2nd class ArtistList.java :
public class ArtistList extends ArrayAdapter<Artist> {
private Activity context;
List<Artist> artists;
public ArtistList(Activity context, List<Artist> artists) {
super(context, R.layout.list_layout, artists);
this.context = context;
this.artists = artists;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewGenre = (TextView) listViewItem.findViewById(R.id.textViewGenre);
Artist artist = artists.get(position);
textViewName.setText(artist.getArtistName());
textViewGenre.setText(artist.getArtistGenre());
return listViewItem;
}
This is my Stacktrace:
java.lang.NullPointerException
at com.example.e_agriculture10.Articles_from_fireabse$2.onDataChange(Articles_from_fireabse.java:92)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.1.0:75)
This is the critical block of my code where error exists.
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
artists.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
Artist artist = postSnapshot.getValue(Artist.class);
//adding artist to the list
artists.add(artist);
}
//creating adapter
ArtistList artistAdapter = new ArtistList(Articles_from_fireabse.this, artists);
//attaching adapter to the listview
listViewArtists.setAdapter(artistAdapter);
}
According to my opinion in this line [artists.clear()], artists getting the null value. Why artists getting null value?

Easy Solution
Whenever you call artists.clear(); check to make sure it is not null.
if(artists != null)
artists.clear();
else
artists = new ArrayList<>();
Sustainable Solution
You should consider what the role of the artists object arry is. In this case, you have both a database and an array that both store information about artists. The database should store persistent data, that is data that lives after program execution. Whereas, your artists object is just around during runtime.
Therefore, you should have code at the start of your program that loads in data from the database into the artists object. Reference / edit / add to the artist object during runtime. Finally, have cleanup code at the end of runtime that updates the artist table in the database.

yes initialize List artists; inside onCreate(){}
Something like this
artists = new ArrayList<>();

Related

How to retrieve a Boolean value from Firebase to a TextView?

I'm making a shopping app and User has to subscribe to the 'Fast-delivery' option if he needs to order it faster. When the User puts a tick to the 'Fast-delivery' Checkbox, the boolean value is being uploaded to the Firebase realtime database -->
database
And I want to see if the User has subscribed to the 'Fast-delivery' option from the Admin Panel. I retrieve all the order information to a RecyclerView in the Admin Panel. I want to set a TextView as "Fast Delivery : On/Off" when the Admin views the order details from the Admin Panel.
This is what I have tried:
#Override
protected void onStart()
{
super.onStart();
ordersRef = FirebaseDatabase.getInstance().getReference().child("Orders");
FirebaseRecyclerOptions<AdminOrders> options =
new FirebaseRecyclerOptions.Builder<AdminOrders>()
.setQuery(ordersRef, AdminOrders.class)
.build();
FirebaseRecyclerAdapter<AdminOrders, AdminOrdersViewHolder> adapter =
new FirebaseRecyclerAdapter<AdminOrders, AdminOrdersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final AdminOrdersViewHolder holder, final int position, final #NonNull AdminOrders model)
{
holder.userName.setText("Name: "+ model.getName());
holder.userPhoneNumber.setText("Phone Number: : "+ model.getPhone());
holder.userTotalPrice.setText("Total Amount: $"+ model.getTotalAmount());
holder.userDateTime.setText("Order Time: "+ model.getDate() + model.getTime());
holder.userShippingAddress.setText("Shipping Address: "+ model.getAddress() + "," + model.getCity());
holder.showOrdersBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String uID = getRef(position).getKey();
Intent intent = new Intent(AdminNewOrdersActivity.this, AdminUserProductsActivity.class);
intent.putExtra("uid", uID);
startActivity(intent);
}
});
ordersRef.child(userID).child("fast_delivery").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
TextView switch1 = (TextView) findViewById(R.id.switch1);
switch1.setText(String.valueOf(this));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
And I'm getting this error
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
You have a NullPointerException indicating that userID is not initialized, hence this error:
Can't pass null for argument 'pathString' in child()
To solve this, please add the following line of code:
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
Right in front of:
ordersRef.child(userID).child("fast_delivery").addValueEventListener(/* ... */);
i guess if im right.. you have created separate tree for orders where you are getting orders
create model class give name as same as childname are where you're getting boolean value of fast_delivery use that boolean value to convert it to string and hence compare that value if String.valueof(boolean)is="true" then print to textview or vise versa with off

How to save retrieved data from firebase to string variable in android?

Hy Developers, I am new to android development so that's why facing an issue in saving and viewing data to my android app.
I know that data can only be retrieved while you are connected to internet.
But the thing is it is retrieving data and also showing to android log.
But when i try to save it to a string variable or to arraylist to show
it on main activity using that list or variable, its not working.
I am declaring a private string variable to store value from firebase database before onCreate method.
Sorry for my nob question. But this is the issue i am facing.
Following is the code that i am using and some screenshots to make the question understandable.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Firelog" ;
Button ans1, ans2, ans3, ans4;
TextView uscore, question, timer;
private String mAnswer;
private ArrayList<String> fbquestions = new ArrayList<String>();
private String quest;
private int mScore = 0;
Random r = new Random();
private int res = 0;
private int c = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uscore = (TextView) findViewById(R.id.uscore);
question = (TextView) findViewById(R.id.question);
timer = (TextView) findViewById(R.id.timer);
ans1 = (Button) findViewById(R.id.ans1);
ans2 = (Button) findViewById(R.id.ans2);
ans3 = (Button) findViewById(R.id.ans3);
ans4 = (Button) findViewById(R.id.ans4);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("mcqs");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Map <String, String> map = (Map)dataSnapshot.getValue();
quest = map.get("question");
fbquestions.add(quest);
Log.v("E_Value","Question is" + quest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
question.setText(String.valueOf(fbquestions.get(0)));
}
}
In above pic you can see that question is retrieved successfully from firebase and visible in log.
But here when i try to display question on main screen after assigning, its showing blank.
After adding the code to add value to arraylist, application crashes..
You cannot simply get the value of fbquestions.get(0) outside the onDataChange() method because this method has an asynchronous behavior. So you cannot simply create your fbquestions list as a global variable and use it's value outside the callbakc because it will always be empty. Basically, you're trying to use a value synchronously from an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.
A quick solve for this problem would be to move the following line of code:
question.setText(String.valueOf(fbquestions.get(0)));
Inside the callback right after this line of code:
Log.v("E_Value","Question is" + quest);
And your problem will be solved. If you want to use the list outside, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
Pass quest value to Textview..
ArrayList<String> questionArrrayList =new Arraylist<>();
questionArrrayList .clear();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Map <String, String> map = (Map)dataSnapshot.getValue();
quest = map.get("question");
question.setText(quest);
questionArrrayList .add(quest);
Log.v("E_Value","Question is" + quest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

how to save the state of those items which have been selected in recyler view even after the app is closed

What I want to do is to show the same selected items on a recycler view even after the activity has been closed and only change items color when I again click on it. For now I have achieved changing the color on click but the state doesn't get saved?
This is my adapter:
public class LightsRecyclerViewAdapter extends
RecyclerView.Adapter<LightsRecyclerViewAdapter.ViewHolder> {
// private List<Integer> mViewColors;
private List<String> mAnimals;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
LightsRecyclerViewAdapter(Context context, List<String>
animals) {
this.mInflater = LayoutInflater.from(context);
this.mAnimals = animals;
}
// inflates the row layout from xml when needed
#Override
#NonNull
public ViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view = mInflater.inflate(R.layout.item, parent,
false);
return new ViewHolder(view);
}
// binds the data to the view and textview in each row
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int
position) {
// int color = mViewColors.get(position);
String animal = mAnimals.get(position);
// holder.myView.setBackgroundColor(color);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mAnimals.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
View myView;
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
// myView = itemView.findViewById(R.id.colorView);
myTextView =
itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null)
mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mAnimals.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener
itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
And this is my activity:
public class DevicesList extends AppCompatActivity implements
LightsRecyclerViewAdapter.ItemClickListener{
private LightsRecyclerViewAdapter adapter,adapter1;
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_devices_list);
title = (TextView)findViewById(R.id.textGrid);
// data to populate the RecyclerView with
ArrayList<Integer> viewColors = new ArrayList<>();
viewColors.add(Color.BLUE);
viewColors.add(Color.YELLOW);
viewColors.add(Color.MAGENTA);
viewColors.add(Color.RED);
viewColors.add(Color.BLACK);
ArrayList<String> Lab1LightsList = new ArrayList<>();
Lab1LightsList.add("Light 1");
Lab1LightsList.add("Light 2");
Lab1LightsList.add("Light 3");
Lab1LightsList.add("Light 4");
Lab1LightsList.add("Light 5");
ArrayList<String> Lab1ACList = new ArrayList<>();
Lab1ACList.add("AC 1");
Lab1ACList.add("AC 2");
Lab1ACList.add("AC 3");
Lab1ACList.add("AC 4");
Lab1ACList.add("AC 5");
ArrayList<String> Lab2LightsList = new ArrayList<>();
Lab2LightsList.add("Light 1");
Lab2LightsList.add("Light 2");
Lab2LightsList.add("Light 3");
Lab2LightsList.add("Light 4");
Lab2LightsList.add("Light 5");
Lab2LightsList.add("Light 6");
ArrayList<String> Lab2ACList = new ArrayList<>();
Lab2ACList.add("AC 1");
Lab2ACList.add("AC 2");
Lab2ACList.add("AC 3");
Lab2ACList.add("AC 4");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.list1);
RecyclerView recyclerView1 =findViewById(R.id.list2);
LinearLayoutManager horizontalLayoutManagaer
= new LinearLayoutManager(DevicesList.this, LinearLayoutManager.HORIZONTAL, false);
LinearLayoutManager horizontalLayoutManager
= new LinearLayoutManager(DevicesList.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManagaer);
recyclerView1.setLayoutManager(horizontalLayoutManager);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("labno", 0);
if(intValue==0) {
adapter = new LightsRecyclerViewAdapter(this, Lab1LightsList);
adapter1 = new LightsRecyclerViewAdapter(this, Lab1ACList);
adapter.setClickListener(this);
adapter1.setClickListener(this);
recyclerView.setAdapter(adapter);
recyclerView1.setAdapter(adapter1);
}
if(intValue==1) {
adapter = new LightsRecyclerViewAdapter(this, Lab2LightsList);
adapter1 = new LightsRecyclerViewAdapter(this, Lab2ACList);
adapter.setClickListener(this);
adapter1.setClickListener(this);
recyclerView.setAdapter(adapter);
recyclerView1.setAdapter(adapter1);
}
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " +
adapter.getItem(position) + " on item position " + position,
Toast.LENGTH_SHORT).show();
view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
Please help on this.
Create one selected item position list and store it in prefs when an app goes to background or closed. Load that list when launching an app and compare that list in an adapter's onBindViewHolder's position parameter and marks it selected/unselected based on a comparison.
As per my understandings about your question, you want to save the state of the selected items even after the app is closed, and then you want to reload it whenever the app is launched again. You need to refer to this link Android Save Data
For the above solution, there can be various ways to save state, I am mentioning a few below:
Use SQLite Database to save the selected items. Then, whenever the app is loaded, fetch all the selected data from the DB and then mark them selected with whatever colour you want on the list.
You can also use Shared Preferences, to store the selection. And, same as above, you can reload the data when the app is launched.
You can also store the data in a specific format, maybe CSV, JSON, XML etc., in a file and save it either in Internal Storage or External Storage of the device. And when the app is launched, fetch all the selected values from the file and process accordingly.
You can also use a web server, Firebase Storage, or other cloud storage services to save the data and then fetch the data on new app launch.
Do note: All these techniques require you to save the state before the app is closed. So it is better to store the states, either on click of the item, or onPause method of the activity.
If you face any problems with these solutions, you can post another comment and I will give it a look.
Save these clicked item position in a hashmap in Shareprefence. suppose u close the activity after u coming back the activity just pass the saved list with ur data in adapter and compare the shareprefence list with ur data list if position or data match than make the itemview layout colored.
// save clicked item is a list and save it sharePreference.
List<Integer> clikedList = new ArrayList<>();
if (clicked item){
ClikedList.add(position)
}
String value = gson.toJson(list);
SharedPreferences prefs = context.getSharedPreferences("mylist",
Context.MODE_PRIVATE);
Editor e = prefs.edit();
e.putString("list", value);
e.commit();
// for getting cliked position list from SharePreference
SharedPreferences prefs = context.getSharedPreferences("mylist",
Context.MODE_PRIVATE);
String value = prefs.getString("list", null);
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
MyObject[] list = gson.fromJson(value, MyObject[].class);
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// suppose clicked position 4 u get from shaved cliked list
in here u neddd to retreive cliked list position and clored those item
int select = 4;
if (select == position) {
holder.itemView.setBackgroundColor(Color.BLUE);
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
} else {
holder.itemView.setBackgroundColor(Color.parseColor("#214F4B"));
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
}
holder.tv_title.setText(data.get(position));
}

Chat Fragment not updating recyclerview

I have Fragment where i have recyclerview which works fine on first launch (When fragment start for the first time). i can send and receive message. But when i go to the chat fragment from notification it stops updating recyclerview. i have to clear app from recent app, then when i go to chat fragment from notification it works fine.
Whenever i received message as notification after tapping on notification it open same chat screen (Load all previous message first) and when i click on send button to send message it send to other user but not updating my recyclerview.
Loading chat Fragment Normally
getFragmentManager().beginTransaction().add(R.id.Navigation_Drawer, chatFragment).commit();
Loading Fragment from Notification via Asynctask
((Navigation_Drawer)context).getFragmentManager().beginTransaction().replace(R.id.Navigation_Drawer, chatFragment).commit();
ChatScreenFragment
public class Chat_Screen_Fragment extends Fragment implements View.OnClickListener, ChildEventListener{
public static final String TAG = "###CHAT SCREEN###";
List<Chat_Wrapper> message = new ArrayList<>();
Chat_Adapter adapter;
RecyclerView recyclerView;
LinearLayoutManager layoutManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.chat_screen_main_fragment,container,false);
setRetainInstance(true);
// GET INTENT VALUES FROM USER PROFILE CLASS
UserName_Intent = getArguments().getString("Get_Name");
UserImage_Intent = getArguments().getString("Get_Image");
UserPhone_Intent = getArguments().getString("Get_Phone");
UserID_Intent = getArguments().getString("Get_ID");
FirebaseToken_Intent = getArguments().getString("Get_Token"); //Firebase Token of other person
Room_Name_Intent = getArguments().getString("Get_Other"); // Room Name of chat
UserLastSeen_Intent=getArguments().getString("LastSeen");
//Sender_FCMToken = Session.getFirebaseID();
// RECYCLER VIEW
recyclerView = v.findViewById(R.id.Chat_Screen_Message_List);
layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
databaseReference = FirebaseDatabase.getInstance().getReference().child(Room_Name_Intent);
databaseReference.addChildEventListener(this);
adapter = new Chat_Adapter(getActivity(), message);
recyclerView.setAdapter(adapter);
// FETCH OLD MESSAGE FROM DATABASE
chatDatabase();
return v;
}
// FIREBASE REAL TIME DATABASE WHICH FETCH ALL MESSAGES (SYNC) FROM ONLINE DATABASE
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
private synchronized void append_chat_conversation(DataSnapshot dataSnapshot) {
iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()) {
// NOW GET ALL DATA FROM FIREBASE DATABASE AND SAVE IT INTO STRINGS THEN CHECK EACH BY ITS MESSAGE TYPE
Chat_Msg = (String) ((DataSnapshot) iterator.next()).getValue();
Chat_FROM = (String) ((DataSnapshot) iterator.next()).getValue();
Chat_FCM_TO= (String) ((DataSnapshot) iterator.next()).getValue();
Chat_Database tempChatDatabase = new Chat_Database(getActivity());
boolean hasValue=tempChatDatabase.CheckValueExist(_ID);
if (!hasValue) {
Log.d(TAG,"Chat Message "+Chat_Msg);
long id=chat_database.Insert_Chat(Session.getUserID(),Room_Name_Intent, UserID_Intent, "Text", Chat_Msg, Chat_FROM, Chat_TO, Chat_TimeStamp, Chat_FCM_FROM, Chat_FCM_TO, Session.getPhoneNO(), UserPhone_Intent,Random_ID,UserImage_Intent,UserLastSeen_Intent,Chat_FROM_ID);
//Adding Chat Data Into Database
Log.d(TAG,"Database Entry ID "+id);
if (id==0){
Log.d(TAG,"Database Already Has Value Of This Random Id ");
return;
}
Chat_Wrapper chat_wrapper = new Chat_Wrapper(Chat_Msg, null, null, null, null, null, null, Chat_TimeStamp, User_Intent, UserImage_Intent, Chat_FROM, null,null,id);
message.add(chat_wrapper);
adapter.notifyDataSetChanged();
Log.d(TAG, "FIREBASE STORAGE PHOTO-3-MESSAGE ARRAY SIZE " + message.size());
recyclerView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Moving to Bottom");
recyclerView.smoothScrollToPosition(adapter.getItemCount());
}
});
}
}
}
Log.d(TAG, "MESSAGE ARRAY SIZE " + message.size());
tempChatDatabase.isDatabaseClose();
}
adapter.notifyDataSetChanged();
recyclerView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Moving to Bottom");
recyclerView.smoothScrollToPosition(message.size()-1);
//recyclerView.smoothScrollToPosition(adapter.getItemCount());
}
});
}
private void chatDatabase(){
//Database Init and Filling Adapter
Log.d(TAG,"Chat Database Function");
chat_database=new Chat_Database(getActivity());
chatCursor=chat_database.getUserChat(UserID_Intent);
boolean checkDB_Exist=functions.DatabaseExist(getActivity(),"CHAT_DATABASE.DB");
boolean chatItemsCounts=chatCursor.getCount()>0;
chatCursor.moveToFirst();
Log.d(TAG,"Value At Chat Database "+ checkDB_Exist+" "+chatItemsCounts);
if (checkDB_Exist && chatCursor.getCount()>0 && chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_USER_ID")).equals(UserID_Intent)){
Log.d(TAG,"Database Exist Chat Database");
message.clear();
chatCursor.moveToFirst();
do {
database_rowID=chatCursor.getInt(chatCursor.getColumnIndex("ID"));
database_userID=chatCursor.getString(chatCursor.getColumnIndex("USER_ID"));
database_RoomName =chatCursor.getString(chatCursor.getColumnIndex("ROOM_NAME"));
database_ReceiverID=chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_USER_ID"));
database_MessageType=chatCursor.getString(chatCursor.getColumnIndex("MESSAGE_TYPE"));
database_Message=chatCursor.getString(chatCursor.getColumnIndex("USER_MESSAGE"));
database_MsgFrom=chatCursor.getString(chatCursor.getColumnIndex("SENDER_NAME"));
database_MsgTo=chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_NAME"));
database_TimeStamp=chatCursor.getString(chatCursor.getColumnIndex("TIME_STAMP"));
database_FCMfrom=chatCursor.getString(chatCursor.getColumnIndex("SENDER_TOKEN"));
database_FCMto=chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_TOKEN"));
database_LocalPath=chatCursor.getString(chatCursor.getColumnIndex("DOWNLOADED_AT"));
database_PhoneFrom=chatCursor.getString(chatCursor.getColumnIndex("MY_PHONE"));
database_PhoneTo=chatCursor.getString(chatCursor.getColumnIndex("OTHER_PHONE"));
Log.d(TAG,"Value Of Database Message String = "+database_Message);
Log.d(TAG,"Row ID of Database "+database_rowID);
// Check Message Type
Log.d(TAG,"Message Type Is Text");
Chat_Wrapper text = new Chat_Wrapper(database_Message, null, null, null, null, null, null, database_TimeStamp, database_PhoneTo, UserImage_Intent, database_MsgFrom,null,null,database_rowID);
message.add(text);
}
while(chatCursor.moveToNext());
Room_Name_Intent = database_RoomName;
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter.notifyDataSetChanged();
chatCursor.close();
boolean value = chat_database.isDatabaseClose();
recyclerView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Moving to Bottom");
recyclerView.smoothScrollToPosition(message.size()-1);
}
});
Log.d(TAG,"Value Of Database Close or Not "+value);
}
}
}
I also notice that method which is fetching earlier messages from local database when i comment chatDatabase() function it works fine. but still not able to fix the issue.
Works perfect in case.
When i clear app from recent app
Comment chatDatabase() function
When i First Launch of fragment.
While Fragment instance itself is retained, it is destroying and recreating its View whenever its detached/replaced.
Move your firebase and adapter initialization logic to onCreate, leaving only RecyclerView initialization in onCreateView.
You should also override onDestroyView and clear reference to layoutManager and recyclerView there.
Note that in this case you must either detach your firebase callbacks or handle case where getView() (or recyclerView if reference is cleared in onDestroyView) is null and skip updating UI then.

Add the values on ArrayList in Android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have develop one application. Here i have to add the value on ArrayList. if i have to click Button means that value have to add on that ArrayList. I have to click another Button means that added list is displaying. How can i do? Please give me solution.
These are my values:
product_id = getIntent().getStringExtra("id");
product_title = getIntent().getStringExtra("title");
product_image = getIntent().getStringExtra("image");
product_price = getIntent().getStringExtra("price");
product_desc = getIntent().getStringExtra("description");
arrayList = new ArrayList<String>();
arrayList.add(product_title);
arrayList.add(product_price);
arrayList.add(product_id);
arrayList.add(product_image);
arrayList.add(product_desc);
I have to add these values on ArrayList while clicking the Button:
valueaddlist = (Button) findViewById(R.id.valueaddlist);
valueaddlist.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Intent intent = new Intent(this,AddedListProducts.class);
intent.putExtra("WishListProducts", arrayList);
startActivity(intent);
}
In the AddedListProducts have to displaying all added products list.
How can i do ?
please give me solution for these ?
EDIT:
This is my AddedListProducts class code:
wishlist_products = (ListView) findViewById(R.id.wishlist_products);
if(getIntent().getExtras() !=null){
WishListProducts = (ArrayList<String>) getIntent().getExtras().getSerializable("WishListProducts");
System.out.println(WishListProducts);
wishlistproductsAdapter = new WishListAdapter(this,WishListProducts);
wishlist_products.setAdapter(wishlistproductsAdapter);
}
In these arraylist am getting values.how can i set the value on adapter file and UI.
This is my adapter file code:
public class WishListAdapter extends BaseAdapter{
WishListAdapter mListViewAdapter;
private Activity mActivity;
private ArrayList<String> mwishlistProducts;
public ImageLoader mImageLoader;
private static LayoutInflater inflater=null;
public WishListAdapter(Activity activity, ArrayList<String> products) {
mActivity = activity;
this.mwishlistProducts=products;
inflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
class ViewHolder{
private ImageView productImageView;
private TextView productTitleView;
private TextView productPriceView;
private TextView productDescView;
public ViewHolder(ImageView productImageView, TextView productTitleView,TextView productPriceView,TextView productDescView) {
super();
this.productImageView = productImageView;
this.productTitleView = productTitleView;
this.productPriceView = productPriceView;
this.productDescView = productDescView;
}
} // ViewHolder-class
public int getCount() {
return mwishlistProducts.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
final String wishlistproductList = mwishlistProducts.get(position);
if( convertView == null )
{
convertView = inflater.inflate(R.layout.list_product, null);
ImageView productImage=(ImageView)convertView.findViewById(R.id.productimage);
TextView productTitle = (TextView)convertView.findViewById(R.id.producttitle);
TextView productPrice = (TextView)convertView.findViewById(R.id.productprice);
TextView productDesc = (TextView)convertView.findViewById(R.id.productdescription);
holder = new ViewHolder(productImage,productTitle,productPrice,productDesc);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.productTitleView.setText();
holder.productPriceView.setText();
holder.productDescView.setText();
mImageLoader=new ImageLoader();
mImageLoader.DisplayImage();
return convertView;
}
}
In these holder file what i have to set ????
How can i set that arraylist value here.please help me yaar..
EDIT:
More products is displaying on one listview.
Now i have to click one list item means its go to detail description page.here i have to click button means that product detail value is adding and have to display on AddedListProducts Page.
now i ll go to back and click another product means click button means that product detail also added and have to display on AddedListProducts page with that old added products...
i have to add products from that listview and go to next page and clicking button means have to display that all added products on AddedListProducts page.how can i do ???
Above code ly displaying last added product ly.I want to display all added products on that list.
After getting value from intent:
ArrayList<String> arrayList = new ArrayList<String>();
valueaddlist = (Button) findViewById(R.id.valueaddlist);
valueaddlist.setOnClickListener(new OnClickListener() {
public void onClick(View v){
arrayList.add(product_id);
arrayList.add(product_title);
arrayList.add(product_image);
arrayList.add(product_price);
arrayList.add(product_desc);
}
valuedisplaylist = (Button) findViewById(R.id.valuedisplaylist);
valuedisplaylist.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Intent intent = new Intent(this,AddedListProducts.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) arrayList);
startActivity(intent);
}
May be this will help you.
In your second activity get the arraylist like :
ArrayList<String> ar1=getIntent().getExtras().getStringArrayList("arrayList"); ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ar1);
lv.setAdapter(arrayAdapter);
Then have a look at this question to display arraylist: Populating a ListView using an ArrayList?
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(5);

Categories

Resources