How to retrieve a part of the data from Firebase Android - android

Contacts Fragment
ListView usersList;
TextView noUsersText;
ArrayList<String> al = new ArrayList<>();
int totalUsers = 0;
ProgressDialog mProgressDialogue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
usersList = (ListView)rootView.findViewById(R.id.usersList);
noUsersText = (TextView)rootView.findViewById(R.id.noUsersText);
mProgressDialogue = new ProgressDialog(getActivity());
mProgressDialogue.setMessage("Loading...");
mProgressDialogue.show();
String url = "https://messageplus-cd647.firebaseio.com/Users.json";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
doOnSuccess(s);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError);
}
});
RequestQueue rQueue = Volley.newRequestQueue(getActivity());
rQueue.add(request);
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserDetails.chatWith = al.get(position);
Intent intent = new Intent(getActivity(), Chat.class);
startActivity(intent);
}
});
return rootView;
}
doOnSuccess Method
public void doOnSuccess(String s){
try {
JSONObject obj = new JSONObject(s);
Iterator i = obj.keys();
String key = "";
while(i.hasNext()){
key = i.next().toString();
if(!key.equals(UserDetails.phonenumber)) {
al.add(key);
}
totalUsers++;
}
} catch (JSONException e) {
e.printStackTrace();
}
if(totalUsers <=1){
noUsersText.setVisibility(View.VISIBLE);
usersList.setVisibility(View.GONE);
}
else{
noUsersText.setVisibility(View.GONE);
usersList.setVisibility(View.VISIBLE);
usersList.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1 , al));
}
mProgressDialogue.dismiss();
}
}
My Database strucuture - http://ibb.co/eMGhWb
I want to display only the names of the users. How do i achieve this.
with the current code, when i open the fragment It just says "Loading..." and doesnt load anything... do i have to do anything with exporting json file or anything? please help i'm still a beginner

In order to query a Firebase database you only need to create a DatabaseReference, attach a listener and iterate over the DataSnapshot object like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> arrayList = new ArrayList<>();
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, arrayList);
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("Name").getValue(String.class);
arrayList.add(name);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
The output will be only tne name of the users.

Related

Recycler View data is duplicated after doing swipeToRefresh multiple times

I am showing Firebase data in a RecyclerView and it is working fine.
I have also implemented a SwipeRefreshLayout and when user swipe it, it is getting latest data from Firebase. But whenever I swipe it more than once, it is showing duplicate values although I am clearing the ArrayList and also I am using `swipeRefresh.setEnabled(true)``
Here I am implementing SwipeRefreshLayout:
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
if (swipeRefresh.isEnabled())
swipeRefresh.setEnabled(false);
}
});
Here is my getData() function:
public void getData() {
pd.setTitle("Loading Data");
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
infoList = new ArrayList<>();
distributorList = new ArrayList<>();
infoList.clear();
distributorList.clear();
countChilds = 0;
counter = 0;
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference hotelRef = rootRef.child("Orders");
hotelRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String key = String.valueOf(dataSnapshot.getKey());
final String hotelName = String.valueOf(dataSnapshot.child("hotelName").getValue());
final String location = String.valueOf(dataSnapshot.child("location").getValue());
final String quantity = String.valueOf(dataSnapshot.child("quantity").getValue());
final String time = String.valueOf(dataSnapshot.child("time").getValue());
final DatabaseReference progressRef = rootRef.child("Progress").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
shipment = String.valueOf(dataSnapshot.child("shipment").getValue());
firstMile = String.valueOf(dataSnapshot.child("firstMile").getValue());
distributor = String.valueOf(dataSnapshot.child("distributor").getValue());
}
if (shipment.equals("1") && firstMile.equals("2") && !distributor.equals("2")) {
counter++;
Information information = new Information(key, hotelName, location, quantity, time);
infoList.add(information);
distributorList.add(distributor);
try {
adapter = new DistributorItemAdapter(infoList, distributorList, getContext(), DistributorListFragment.this);
recyclerView.setAdapter(adapter);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
} catch (NullPointerException e) {
Toast.makeText(getContext(), "No more Orders", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else {
shipment = "";
distributor = "";
firstMile = "";
}
if (counter == 0) {
emptyView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(null);
} else
emptyView.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Database Error", databaseError.getMessage());
}
};
progressRef.addListenerForSingleValueEvent(eventListener);
countChilds++;
if (countChilds >= dataSnapshot.getChildrenCount()) {
if (pd.isShowing())
pd.dismiss();
if (!swipeRefresh.isEnabled())
swipeRefresh.setEnabled(true);
swipeRefresh.setRefreshing(false);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
You should initialize your adapter where you initialize your recylerview and set adapter to recylcerView like the following.
//recyclerView = findViewById.....
infoList = new ArrayList<>();
distributorList = new ArrayList<>();
adapter = new DistributorItemAdapter(infoList, distributorList, getContext(), DistributorListFragment.this);
recyclerView.setAdapter(adapter);
Now modify your getData() like below.
public void getData() {
pd.setTitle("Loading Data");
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
infoList.clear();
distributorList.clear();
countChilds = 0;
counter = 0;
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference hotelRef = rootRef.child("Orders");
hotelRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String key = String.valueOf(dataSnapshot.getKey());
final String hotelName = String.valueOf(dataSnapshot.child("hotelName").getValue());
final String location = String.valueOf(dataSnapshot.child("location").getValue());
final String quantity = String.valueOf(dataSnapshot.child("quantity").getValue());
final String time = String.valueOf(dataSnapshot.child("time").getValue());
final DatabaseReference progressRef = rootRef.child("Progress").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
shipment = String.valueOf(dataSnapshot.child("shipment").getValue());
firstMile = String.valueOf(dataSnapshot.child("firstMile").getValue());
distributor = String.valueOf(dataSnapshot.child("distributor").getValue());
}
if (shipment.equals("1") && firstMile.equals("2") && !distributor.equals("2")) {
counter++;
Information information = new Information(key, hotelName, location, quantity, time);
infoList.add(information);
distributorList.add(distributor);
// notify your adapter that data set is changed
adapter.notifyDatasetChanged();
} else {
shipment = "";
distributor = "";
firstMile = "";
}
if (counter == 0) {
emptyView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(null);
} else
emptyView.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Database Error", databaseError.getMessage());
}
};
progressRef.addListenerForSingleValueEvent(eventListener);
countChilds++;
if (countChilds >= dataSnapshot.getChildrenCount()) {
if (pd.isShowing())
pd.dismiss();
if (!swipeRefresh.isEnabled())
swipeRefresh.setEnabled(true);
swipeRefresh.setRefreshing(false);
}
}
//....
});
}

Recycler updates with duplicate values

I use wipe to delete method to delete a row, When i delete one row from the recycler list view it duplicates the value just below the one I had deleted.
If I delete "Test 3" from the list
it shows a duplicate of "Test 4" in 3rd and 4th position
my whole code used for list creation and deletion, can any one help me with this
public class fragmnetPendingAct extends Fragment {
private SwipeRefreshLayout refreshLayout;
private RecyclerView recyclerView;
ArrayList<String> activitynames;
FirebaseAuth mAuth;
View view;
List<modelclasspendingact> modelclasspendingactList = new ArrayList<>();
public fragmnetPendingAct() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pendingactivity,container,false);
refreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_activitypend);
recyclerView = v.findViewById(R.id.recyclerviewpendingact);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
new ItemTouchHelper(itemtouchHelpercalback).attachToRecyclerView(recyclerView);
//listen to swipe horizontal
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Get new Instance ID token
FirebaseUser mUser = mAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
// Send token to your backend via HTTPS
getdatafromserver(token);
} else {
// Handle error -> task.getException();
Log.w(TAG, "getInstanceId failed second", task.getException());
}
}
});
refreshitems();
}
});
// Get new Instance ID token
FirebaseUser mUser = mAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
Log.d(TAG, "onComplete lead: "+token);
// Send token to your backend via HTTPS
getdatafromserver(token);
} else {
// Handle error -> task.getException();
Log.w(TAG, "getInstanceId failed second", task.getException());
}
}
});
return v;
}
public void getdatafromserver(String token){
//new code using curl
String serverurl="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, serverurl,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "activity list: "+response);
JSONObject alldata=response.getJSONObject("payload");
JSONArray assetaarray=alldata.getJSONArray("activities");
modelclasspendingactList.removeAll(modelclasspendingactList);
for(int i=0;i<assetaarray.length();i++)
{
JSONObject getactivity=assetaarray.getJSONObject(i);
String activityid = String.valueOf(getactivity.getInt("id"));
String activityname = getactivity.getString("title");
String activitydesc = getactivity.getString("description");
Log.d(TAG, "activity name: "+activityname);
//list crreation
modelclasspendingactList.add(new modelclasspendingact(activityname,activitydesc,activityid));
pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers=new HashMap<String,String>();
headers.put("Accept","*/*");
headers.put("Cache-Control","no-cache");
headers.put("cache-control","no-cache");
headers.put("token",token);
return headers;
}
};
singletonclasshttp.getInstance(getActivity()).addtorequestque(jsonObjectRequest);
}
private void refreshitems()
{
refreshLayout.setRefreshing(false);
}
//swipe function
ItemTouchHelper.SimpleCallback itemtouchHelpercalback = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
Log.d(TAG, "onSwiped: "+modelclasspendingactList.get(viewHolder.getAdapterPosition()).getPendid());
Log.d(TAG, "onSwiped: position "+viewHolder.getAdapterPosition());
String activeid = modelclasspendingactList.get(viewHolder.getAdapterPosition()).getPendid();
// Get new Instance ID token
FirebaseUser mUser = mAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
//send token and activity id to update function
markascompleted(activeid,token);
} else {
// Handle error -> task.getException();
Log.w(TAG, "getInstanceId failed second", task.getException());
}
}
});
Log.d(TAG, "onSwiped: position "+viewHolder.getAdapterPosition());
Log.d(TAG, "onSwiped: first list size "+modelclasspendingactList.size());
pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
modelclasspendingactList.remove(viewHolder.getAdapterPosition());
recyclerView.removeViewAt(viewHolder.getAdapterPosition());
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
// adapter.notifyItemRangeChanged(viewHolder.getAdapterPosition(), modelclasspendingactList.size());
// adapter.notifyDataSetChanged();
Log.d(TAG, "onSwiped: list size "+modelclasspendingactList.size());
// pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
// modelclasspendingactList.remove(viewHolder.getAdapterPosition());
// adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
};
private void markascompleted(String activeid,String token)
{
//send data to server
//curl function
String serverurl="xxxxxxxxxxxxxxxxxxxxxxx";
Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("id", activeid);
jsonParams.put("activityStatus", "COMPLETED");
jsonParams.put("targetEmployeeId", "1001");
jsonParams.put("score", "1");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, serverurl,new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "response: "+response);
try {
if (response.optBoolean("success")==true)
{
Toast.makeText(getActivity(), response.getString("message"),Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getActivity(),"Data Not Updated",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(),"Data Not Updated",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Data Not Saved",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers=new HashMap<String,String>();
headers.put("Accept","*/*");
headers.put("Cache-Control","no-cache");
headers.put("Connection","keep-alive");
headers.put("Content-Type","application/json");
headers.put("cache-control","no-cache");
headers.put("token",token);
return headers;
}
};
singletonclasshttp.getInstance(getActivity()).addtorequestque(jsonObjectRequest);
}
}
First I'll explain why you get this behavior, then we'll get to solution.
In this code:
Problem #1:
pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
You are creating an adapter and pass it your current data. Note that the adapter will have its own copy of the list you passed in constructor.
modelclasspendingactList.remove(viewHolder.getAdapterPosition());
This list that you are removing Item from is different from the one you just sent in Adapter, so the Adapter still has old list.
Then you call removed and adapter tries to update values but your removed item is still in the list that adapter has.
Solution:
Create A Function/Method in Adapter that removes the item from the list in adapter.
Problem #2 with Solution:
You are creating a new Adapter instance/object every time a view is swiped, it is unnecessary. Create the Adapter in class instead of function and instantiate it in onCreateView().
A couple things.
First, the removeViewAt is a function of RecyclerView.LayoutManager. I imagine you meant to say recyclerView.LayoutManager.removeViewAt.
Second, the call to removeViewAt should not be necessary as RecyclerView does this automatically when notifyItemRemoved is called correctly.
Third, you do not need to re-bind the entire list when removing an item. You can remove the notifyItemRangeChanged.
Fourth, you do not need to invalidate the entire adapter when removing an item either. You can remove notifyDataSetChanged. In fact, this function should only be used as a last resort.
Initializing your RecyclerView:
pendingactAdapter adapter = new pendingactAdapter(modelclasspendingactList);
RecyclerView recyclerView = view.findViewById(R.id.my_recycler_view);
recyclerView.adapter = adapter;
recyclerView.layoutManager = LinearLayoutManager(getActivity());
So your removal sequence should be
modelclasspendingactList.remove(viewHolder.getAdapterPosition());
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

I want to retrieve a part of the data in Firebase. How do i achieve this?

Fragment Code
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
usersList = (ListView)rootView.findViewById(R.id.usersList);
noUsersText = (TextView)rootView.findViewById(R.id.noUsersText);
mProgressDialogue = new ProgressDialog(getActivity());
mProgressDialogue.setMessage("Loading...");
mProgressDialogue.show();
String url = "https://messageplus-cd647.firebaseio.com/.json";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
doOnSuccess(s);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError);
}
});
RequestQueue rQueue = Volley.newRequestQueue(getActivity());
rQueue.add(request);
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserDetails.chatWith = al.get(position);
Intent intent = new Intent(getActivity(), Chat.class);
startActivity(intent);
}
});
return rootView;
doOnSuccess Method
public void doOnSuccess(String s){
try {
JSONObject obj = new JSONObject(s);
Iterator i = obj.keys();
String key = "";
while(i.hasNext()){
key = i.next().toString();
if(!key.equals(UserDetails.phonenumber)) {
al.add(key);
}
totalUsers++;
}
} catch (JSONException e) {
e.printStackTrace();
}
if(totalUsers <=1){
noUsersText.setVisibility(View.VISIBLE);
usersList.setVisibility(View.GONE);
}
else{
noUsersText.setVisibility(View.GONE);
usersList.setVisibility(View.VISIBLE);
usersList.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1 , al));
}
mProgressDialogue.dismiss();
}
The problem is, In the URL mentioned above, the data present is Unique Id of users. Inside Unique id there are 4 fields - Name, Number, Email, Gender. I want to retrieve only the names of the users How do i achieve this? Thanks in advance

Firebase Chat After login

I want to select displayName show in UserList. but i don't know how to select displayName in Database users plase can you help me.
eg. i select 6Z86LIYRMaM9vtmOrd23kAeICO63 but i want to show displayName
ListView usersList;
TextView noUsersText;
ArrayList<String> al = new ArrayList<>();
int totalUsers = 0;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
usersList = (ListView)findViewById(R.id.usersList);
noUsersText = (TextView)findViewById(R.id.noUsersText);
pd = new ProgressDialog(Users.this);
pd.setMessage("Loading...");
pd.show();
String url = "https://chatapp.firebaseio.com/users.json";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
doOnSuccess(s);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError);
}
});
RequestQueue rQueue = Volley.newRequestQueue(Users.this);
rQueue.add(request);
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserDetails.chatWith = al.get(position);
startActivity(new Intent(Users.this, Chat.class));
}
});
}
public void doOnSuccess(String s){
try {
JSONObject obj = new JSONObject(s);
Iterator i = obj.keys();
String key = "";
while(i.hasNext()){
key = i.next().toString();
if(!key.equals(UserDetails.username)) {
al.add(key);
}
totalUsers++;
}
} catch (JSONException e) {
e.printStackTrace();
}
if(totalUsers <=1){
noUsersText.setVisibility(View.VISIBLE);
usersList.setVisibility(View.GONE);
}
else{
noUsersText.setVisibility(View.GONE);
usersList.setVisibility(View.VISIBLE);
usersList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al));
}
pd.dismiss();
}
As suggested in the comments, you should go to the firebase documentation and see how you use the SDK.
https://firebase.google.com/docs/database/android/start/
Specific to your question, you need to create a POJO class of your user so that you can later serialize an object when retrieving the user from the db.
User.java
public class User {
private int avatarId;
private String connection;
private Long createAt;
private String displayName;
private String email;
public User() {
}
public int getAvatarId() {
return avatarId;
}
public void setAvatarId(int avatarId) {
this.avatarId = avatarId;
}
public String getConnection() {
return connection;
}
public void setConnection(String connection) {
this.connection = connection;
}
public Long getCreateAt() {
return createAt;
}
public void setCreateAt(Long createAt) {
this.createAt = createAt;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Then you can fetch users info from the db like this.
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference()
DatabaseReference userReference = databaseRef.child("users").child("6Z86LIYRMaM9vtmOrd23kAeICO63");
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Create a User POJO class with the same values you have in your db
//and its getters and setters
User user = dataSnapshot.getValue(User.class);
//This is how you get the displayName from a user from the db
user.getDisplayName();
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
userReference.addValueEventListener(userListener);
I hope this helps

Listview not updated in android after spinner selection

hello guys i am working an app where i want to update my listview but everything is working perfect only list view is not updated i don't understand where i am doing wrong help me
code is
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
private Spinner spinner;
private ArrayList<String> students;
private JSONArray result;
CallbackManager callbackManager;
ShareDialog shareDialog;
// listveiw data
private static final String TAG = MainActivity.class.getSimpleName();
String url = "http://www.example.com/json/json.php";
private ProgressDialog pDialog;
private List<Model> movieList = new ArrayList<Model>();
private ListView listView;
private CustomListAdapter adapter;
final Model model = new Model();
final Json_Data j_data = new Json_Data();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
students = new ArrayList<String>();
spinner = (Spinner) findViewById(R.id.txtSpinner);
listView = (ListView) findViewById(R.id.list);
spinner.setOnItemSelectedListener(this);
getData();
listdata();
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final TextView tv_id = (TextView) view.findViewById(R.id.title);
String txt = tv_id.getText().toString();
model.setItemText(txt);
Log.e(TAG, "====>" + txt);
_Dialog_Custom();
}
});
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void listdata(){
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hidePDialog();
Log.e(TAG, response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Model model = new Model();
String status = obj.getString("txt");
String cate = obj.getString("category");
model.setList_category(cate);
model.setTitle(status);
movieList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
private void getData() {
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j_obj = null;
try {
j_obj = new JSONObject(response);
result = j_obj.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text_spinner = spinner.getSelectedItem().toString();
//Log.e("Selected value in","==>"+text_spinner);
j_data.setSpintext(text_spinner);
makeJsonArrayRequest();
Toast.makeText(MainActivity.this, "Get Value from spinner" +text_spinner, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private void _Dialog_Custom() {
final Dialog dialog = new Dialog(this);
final String txt1 = model.getItemText().toString();
Log.e("Hello Dialog", ":=>" + txt1);
dialog.setContentView(R.layout.dialogbox);
dialog.setTitle("Share via");
dialog.setCanceledOnTouchOutside(true);
ImageButton _Fb_Sharebtn = (ImageButton) dialog.findViewById(R.id.share_facebook);
_Fb_Sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
// https://developers.facebook.com/docs/sharing/android
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription(
"The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
}
});
ImageButton _Sharebtn_google = (ImageButton) dialog.findViewById(R.id.share_btn_google);
_Sharebtn_google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new PlusShare.Builder(MainActivity.this)
.setType("text/plain")
.setText(txt1)
.getIntent();
try {
startActivity(shareIntent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.plus&hl=en")));
}
}
});
ImageButton whtsapp_sahre = (ImageButton) dialog.findViewById(R.id.whatsapp_btn);
whtsapp_sahre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
String result = txt1;
whatsappIntent.putExtra(Intent.EXTRA_TEXT, result);
try {
startActivity(whatsappIntent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.whatsapp")));
}
}
});
ImageButton _Twwiterbtn = (ImageButton) dialog.findViewById(R.id.twwiter_btn);
_Twwiterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
String result = txt1;
intent.setType("text/plain")
.setPackage("com.twitter.android");
intent.putExtra(Intent.EXTRA_TEXT, result);
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.twitter.android&hl=en")));
}
}
});
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
dialog.show();
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent backintent = new Intent(getApplicationContext(), Main_Selected_Activity.class);
startActivity(backintent);
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private void makeJsonArrayRequest() {
String spinner_data =j_data.getSpintext().toString().trim();
Log.e(TAG, spinner_data.toString());
String arrayurl = "http://www.example.com/jsoncategory.php?category="+spinner_data;
Log.e("Link is here","==>"+arrayurl);
ArrayList<String> newdata = new ArrayList<String>();
movieList = new ArrayList<Model>();
JsonArrayRequest movieReq = new JsonArrayRequest(arrayurl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "link response=>" + response);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
String name = obj.getString("txt");
model.setList_category(name);
movieList.add(model);
}catch (JSONException e) {
e.printStackTrace();
Log.e("Hello error","==>"+e);
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
}
please help me
Follow The Below approach
Create a public method in your adapter class:
private List<Model> adapterInitialMovieList = null;
public void setDataOnSpinnerSelected(List<Model> movieList){
adapterInitialMovieList = movieList;
notifyDataSetChanged();
}
In Your Activity Class Inside Spinner onClick method:
if(adapter != null){
adapter.setDataOnSpinnerSelected(yourChangedArrayListOfModelClass);
}
use
movieList.clear();
instead of
movieList = new ArrayList<Model>();
The problem is about the creation of a new arraylist. So, the ArrayAdapter do not 'know' you when you want to create a new one ArrayList (with the different address).
In line
adapter = new CustomListAdapter(this, movieList);
you push a some address of arraylist. In a new line later you generates a new arraylist with the different one and work with it. But the adapter works with the 'old variant' of arraylist.
Remove this line from makeJsonArrayRequest() :
movieList = new ArrayList<Model>();
You are assigning a new object(ArrayList) to the movieList and adding values in the new object instead of the one which you passed to the list adapter. Hence the reference of the object which is being used by the list adapter is lost and when you call adapter.notifyDataSetChanged(); there is no updation as the object which is used by the list adapter is unchanged.

Categories

Resources