Updating one fragment part with session from another fragment - java

I am using Volley for my data. I have an edit profile part of a fragment, its side is the main profile. I can successfully update my profile but when I Slide through my main profile the old data is still there. What should I put to update the mainprofile side of the fragment?
Here is MainProfile fragment I have MainProfileFragment
Here is its code:
public class MainProfileFragment extends Fragment{
private static final String TAG = "MainProfileFragment";
SessionManager sessionManager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mainprofile, container, false);
return view;
}
#NonNull
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
sessionManager = new SessionManager(getActivity());
TextView name = (TextView) getView().findViewById(R.id.name);
TextView phoneNumber = (TextView) getView().findViewById(R.id.number);
TextView gender = (TextView) getView().findViewById(R.id.gender);
TextView address = (TextView) getView().findViewById(R.id.address);
TextView occupation = (TextView) getView().findViewById(R.id.occupation);
TextView birthDate = (TextView) getView().findViewById(R.id.birthDate);
TextView userType = (TextView) getView().findViewById(R.id.userType);
TextView id = (TextView) getView().findViewById(R.id.userID);
Button logout = (Button) getView().findViewById(R.id.logoutBtn);
HashMap<String, String> user = sessionManager.getUserDetail();
String mName = user.get(sessionManager.NAME);
String mNumber = user.get(sessionManager.NUMBER);
String mGender = user.get(sessionManager.GENDER);
String mAddress = user.get(sessionManager.ADDRESS);
String mOccupation = user.get(sessionManager.OCCUPATION);
String mBirthDate = user.get(sessionManager.BIRTHDATE);
String mUserType = user.get(sessionManager.USERTYPE);
String mUserID = user.get(sessionManager.ID);
id.setText(mUserID);
name.setText(mName);
phoneNumber.setText(mNumber);
gender.setText(mGender);
address.setText(mAddress);
occupation.setText(mOccupation);
birthDate.setText(mBirthDate);
userType.setText(mUserType);
logout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LogoutEffect.class);
sessionManager.logout();
startActivity(intent);
}
});
}
}
Now beside it is the SideProfileFragment, it edits the profile data. Here is its code:
public class SideProfileFragment extends Fragment{
private static final String TAG = SideProfileFragment.class.getSimpleName();
private EditText name, birthDate, address, occupation, gender, number;
private Button btnSave;
SessionManager sessionManager;
String getId = "";
private static final String URL_READ = "http://isalonbyageeks.000webhostapp.com/readDetail.php";
private static final String URL_EDIT = "http://isalonbyageeks.000webhostapp.com/editDetail.php";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sideprofile, container, false);
return view;
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
sessionManager = new SessionManager(getActivity());
name = (EditText) getView().findViewById(R.id.userName);
birthDate = (EditText) getView().findViewById(R.id.userBirthDate);
address = (EditText) getView().findViewById(R.id.userAddress);
occupation = (EditText) getView().findViewById(R.id.userOccupation);
gender = (EditText) getView().findViewById(R.id.userGender);
number = (EditText) getView().findViewById(R.id.userNumber);
btnSave = (Button) getView().findViewById(R.id.buttonSaveEdit);
HashMap<String, String> user = sessionManager.getUserDetail();
getId = user.get(sessionManager.ID);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SaveEditProfile();
}
});
}
private void getUserDetail(){
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_READ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response);
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1")){
for(int i = 0; i < jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String strName = object.getString ("name");
String strNumber = object.getString("phone_number");
String strGender = object.getString("gender");
String strAddress = object.getString("address");
String strOccupation = object.getString("occupation");
String strBirthDate = object.getString("birth_date");
name.setText(strName);
birthDate.setText(strBirthDate);
address.setText(strAddress);
number.setText(strNumber);
gender.setText(strGender);
occupation.setText(strOccupation);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(getActivity(),"Error Reading Detail" +e.toString(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("id", getId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
#Override
public void onResume(){
super.onResume();
getUserDetail();
}
private void SaveEditProfile(){
final String name = this.name.getText().toString().trim();
final String birthdate = this.birthDate.getText().toString().trim();
final String address = this.address.getText().toString().trim();
final String number = this.number.getText().toString().trim();
final String gender = this.gender.getText().toString().trim();
final String occupation = this.occupation.getText().toString().trim();
final String id = getId;
final String userType = sessionManager.USERTYPE;
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Saving Details...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_EDIT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
Toast.makeText(getActivity(), "Edit Saved!", Toast.LENGTH_SHORT).show();
sessionManager.createSession(id, name, number, gender, address, occupation, birthdate,userType);
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error "+ error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("birth_date", birthdate);
params.put("address", address);
params.put("number", number);
params.put("gender", gender);
params.put("occupation", occupation);
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
I know I got too much code but all I am just needing is that when I click on the save edit I just wish that the mainfragment will be refreshed. or I just wished I can add the one like other apps like when I drag down the fragment refreshes.

This is just solved by getting my php codes right! :)
Seeing what table name i got and it's column names :) just be careful of what you put on guys! hihi

Related

Cant get my API data to display on other pages

The code I've done was followed closely by a few YouTube tutorials. I'm designing an Age of Empires app that takes in the data from a public API. When the user progresses through the pages then different parts of the API data are shown. What I wanted it to do was get the data from the main activity (where the API is retrieved) and put some of its many data into the UniqueUnit page. It's using something called serializable which I can't quite understand how it works yet.
For the record, it works in getting the data from page 'DetailedCivilization' but just completely breaks on 'UniqueUnit'page.
MainActivity.java
package com.example.ageofempires2;
import ...
public class MainActivity extends AppCompatActivity {
public static final String TAG = "tag";
RecyclerView itemList;
Adapter adapter;
List<Civilizations> all_civilizations;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Civilizations menu");
all_civilizations = new ArrayList<>();
itemList = findViewById(R.id.itemList);
itemList.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, all_civilizations);
itemList.setAdapter(adapter);
getJsonData();
}
private void getJsonData() {
String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray civilizations = response.getJSONArray("civilizations");
JSONObject civilizationsData = civilizations.getJSONObject(0);
Log.d(TAG, "onResponse "+ civilizationsData);
for (int i=0; i< civilizationsData.length();i++){
JSONObject civilization = civilizations.getJSONObject(i);
Civilizations v = new Civilizations();
v.setName(civilization.getString("name"));
v.setArmy_type(civilization.getString("army_type"));
v.setExpansion(civilization.getString("expansion"));
v.setCivilization_bonus(civilization.getString("civilization_bonus"));
v.setUnique_unit(civilization.getString("unique_unit"));
all_civilizations.add(v);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(objectRequest);
}
}
Adapter.java
package com.example.ageofempires2;
import ...
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Civilizations> allCivilizations;
private Context context;
public Adapter(Context ctx, List<Civilizations> civilizationsData){
this.allCivilizations = civilizationsData;
this.context = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.civilization_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.titleName.setText(allCivilizations.get(position).getName());
holder.vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putSerializable("civilizationsData", allCivilizations.get(position));
Intent i = new Intent(context, DetailedCivilization.class);
i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return allCivilizations.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleName;
TextView expansionName;
View vv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
titleName = itemView.findViewById(R.id.civilizationUniqueUnits);
expansionName = itemView.findViewById(R.id.civilizationUnitDescription);
vv = itemView;
}
}
}
Civilizations.java
package com.example.ageofempires2;
import java.io.Serializable;
public class Civilizations implements Serializable {
private String name;
private String expansion;
private String army_type;
private String civilization_bonus;
private String unique_unit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpansion() {
return expansion;
}
public void setExpansion(String expansion) {
this.expansion = expansion;
}
public String getArmy_type() {
return army_type;
}
public void setArmy_type(String army_type) {
this.army_type = army_type;
}
public String getCivilization_bonus() {
return civilization_bonus;
}
public void setCivilization_bonus(String civilization_bonus) {this.civilization_bonus = civilization_bonus; }
public String getUnique_unit() {
return unique_unit;
}
public void setUnique_unit(String unique_unit) {this.unique_unit = unique_unit; }
}
UniqueUnits.java
package com.example.ageofempires2;
import ...
public class UniqueUnit extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unique_unit);
getSupportActionBar().setTitle("Unique Unit");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent incomingIntent = getIntent();
Bundle incomingName = incomingIntent.getExtras();
Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData");
Log.d(TAG, "onCreate: IDK MAN IT SHOULD WORK??" +incomingName);
TextView unit = findViewById(R.id.civilizationUnitDescription);
unit.setText(v.getUnique_unit());
}
}
DetailedCivilization.java
package com.example.ageofempires2;
import ...
public class DetailedCivilization extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations v = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit();
}
});
}
private void activityTech(){
Intent intent = new Intent(this, UniqueTech.class);
startActivity(intent);
}
private void activityUnit(){
Intent intent = new Intent(this, UniqueUnit.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
Solutions is
private void activityUnit(Civilizations civ){
Bundle b = new Bundle();
b.putSerializable("civilizationsData", civ)
Intent intent = new Intent(this, UniqueUnit.class);
intent.putExtras(b);
startActivity(intent);
}
In DetailedCivilization.java
Rename v from line Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData"); to civ or something more descriptive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations civ = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit(civ);
}
});
}
And pass Civilizations when you call activityUnit function
Basically you forgot to pass Civilizations when you go from DetailedCivilization.java to UniqueUnits.java

Why do I keep getting null when trying to pass a bundle from my activity to my fragment?

I am trying to pass a value from my activity to my fragment but I keep getting this error "attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference". I am not sure why, some help would be greatly appreciated.
Fragment class
public class MessageFragment extends Fragment {
private RecyclerView displayMessagesRecycleView;
private View displayChatListView;
private RecyclerView.LayoutManager layoutManager;
private ChatListAdapter chatListAdapter;
private ArrayList<String> messageList;
private Message message;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
displayChatListView = inflater.inflate(R.layout.display_messages_layout, container, false);
createObjects();
initRecycleView();
populateRecycleView();
return displayChatListView;
}
//set up RecycleVIew/listener to detect taps
public void initRecycleView() {
displayMessagesRecycleView = displayChatListView.findViewById(R.id.chatListRecycleView);
layoutManager = new LinearLayoutManager(getContext());
((LinearLayoutManager) layoutManager).setStackFromEnd(true);
((LinearLayoutManager) layoutManager).setReverseLayout(true);
displayMessagesRecycleView.setLayoutManager(layoutManager);
chatListAdapter = new ChatListAdapter(getActivity(), messageList);
displayMessagesRecycleView.setAdapter(chatListAdapter);
displayMessagesRecycleView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, final int position) {
TextView textView = view.findViewById(R.id.textViewOptions);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("position", "item clicked");
}
});
}
})
);
}
#Override
public void onStart() {
super.onStart();
retreiveBundle();
}
//Instantiate objects
public void createObjects() {
messageList = new ArrayList<>();
}
public void populateRecycleView() {
messageList.add("HEy");
chatListAdapter.notifyDataSetChanged();
}
//retrieves selected user's name and profile pic from message activity and updates profile image and name
public void retreiveBundle() {
String data = getArguments().getString("data");// data whi
}
}
Message Activity
public class MessageActivity extends AppCompatActivity {
private RecyclerView messagesRecycleView;
private String userProfileName;
private String userProfilePic;
private String timeStamp;
private String messageTimeStamp;
private HashMap<String, Object> messageDictionary;
private FirebaseUser currentFirebaseUser;
private TextView userNameTextView;
private CircleImageView userProfilePicture;
private EditText messageInputEditText;
private DatabaseReference firebaseDatabase;
private DatabaseReference messesagesRef;
private DatabaseReference RootRef;
private String id;
private String messageSender, messageReceiver;
private Message messages;
private ArrayList<Message> messageList;
private MessageAdapter messageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
messageList = new ArrayList<>();
initRecycleView();
linkUpViews();
createObjects();
setUpFirebase();
retreiveBundle();
messageSender = currentFirebaseUser.getUid();
messageReceiver = id;
}
#Override
protected void onStart() {
super.onStart();
messageList.clear();
RootRef.child("Messages").child(messageSender).child(messageReceiver).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Message messages = dataSnapshot.getValue(Message.class);
messageList.add(messages);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//find views by id
public void linkUpViews() {
userNameTextView = findViewById(R.id.userNameTv);
userProfilePicture = findViewById(R.id.chatProfilePic);
messageInputEditText = findViewById(R.id.chatboxEditText);
}
//set up RecycleView
public void initRecycleView() {
messagesRecycleView = findViewById(R.id.messagesRecycleView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
messagesRecycleView.setLayoutManager(linearLayoutManager);
messageAdapter = new MessageAdapter(MessageActivity.this, messageList);
messagesRecycleView.setAdapter(messageAdapter);
}
//create objects
public void createObjects() {
messageDictionary = new HashMap<>();
//messageList = new ArrayList<>();
}
public void sendMessageButton(View view) {
sendMessages();
//saveMessages();
}
//retrieves selected user's name and profile pic from NewsFeedFragment and updates profile image and name
public void retreiveBundle() {
Bundle bundle = getIntent().getExtras();
userProfileName = bundle.getString("profileName");
userProfilePic = bundle.getString("profilePic");
timeStamp = bundle.getString("timestamp");
id = bundle.getString("id");
Log.i("timestamp", timeStamp);
userNameTextView.setText(userProfileName);
Picasso.get().load(userProfilePic).into(userProfilePicture);
}
//goes back to previous activity
public void backToShop(View view) {
Intent intent = new Intent(MessageActivity.this, MainActivity.class);
startActivity(intent);
}
//Set up Firebase connection
public void setUpFirebase() {
messesagesRef = FirebaseDatabase.getInstance().getReference();
RootRef = FirebaseDatabase.getInstance().getReference();
firebaseDatabase = FirebaseDatabase.getInstance().getReference();
currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
}
//Store messages to Firebase
public void sendMessages() {
if (TextUtils.isEmpty(messageInputEditText.getText().toString())) {
Toast.makeText(this, "Please enter a message", Toast.LENGTH_SHORT).show();
} else {
String messageSenderRef = "Messages/" + messageSender + "/" + messageReceiver;
String messageReceiverRef = "Messages/" + messageReceiver + "/" + messageSender;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSender).child(messageReceiver).push();
String messagePushKey = userMessageKeyRef.getKey();
messageDictionary.put("message", messageInputEditText.getText().toString());
messageDictionary.put("sender", messageSender);
messageDictionary.put("receiver", messageReceiver);
HashMap<String, Object> messageBodyDetails = new HashMap<>();
messageBodyDetails.put(messageSenderRef + "/" + messagePushKey, messageDictionary);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushKey, messageDictionary);
RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
messageInputEditText.setText("");
Toast.makeText(MessageActivity.this, "Sent message...", Toast.LENGTH_SHORT).show();
sendDataToFrag();
} else {
Log.e("Error", task.getException().getMessage().toString());
}
}
});
}
}
//sends data to message fragment...
public void sendDataToFrag(){
Bundle bundle = new Bundle();
bundle.putString("data", "From Activity");
// set Fragmentclass Arguments
MessageFragment fragobj = new MessageFragment();
fragobj.setArguments(bundle);
}
}
This code will work
public class MyFragment extends Fragment {
public static MyFragment newInstance(String data) {
Bundle args = new Bundle();
args.putString("data", data);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
public String getData() {
return getArguments().getString("data");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String data = getData();
return inflater.inflate(R.layout.test, container, false);
}
}
And you Activity must be like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uiView = findViewById(R.id.ui);
uiView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(new Runnable() {
#Override
public void run() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.fragment, MyFragment.newInstance("My Test"));
transaction.commit();
}
}).start();
}
});
}
}

How can I display Firebase items in Android ListView?

I am trying to display some Firebase records in an Android ListView. At present, my code is returning a solitary 0 to the ListView when I go to enter a new record, however my Firebase database is displaying the information that I want perfectly.
I have spent quite a bit of time over this issue and can't quite seem to pinpoint the problem.
Any help on this would be much appreciated.
Below is my code for displaying/adding new records:
TenantList tenantListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_tenants);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getUid();
//databaseTenantsList = FirebaseDatabase.getInstance().getReference("tenants").child(uid);
textViewPropertyName = (TextView) findViewById(R.id.textViewPropertyName);
editTextTenantsName = (EditText) findViewById(R.id.editTextTenantsName);
seekBarAge = (SeekBar) findViewById(R.id.seekBarAge);
buttonAddTenant = (Button) findViewById(R.id.buttonAddTenant);
listViewTenants = (ListView) findViewById(R.id.listViewTenants);
tenants = new ArrayList<>();
tenantListAdapter = new TenantList(this, tenants);
listViewTenants.setAdapter(tenantListAdapter);
Intent intent = getIntent();
tenants = new ArrayList<>();
String id = intent.getStringExtra(PropertyActivity.PROPERTY_ID);
String name = intent.getStringExtra(PropertyActivity.PROPERTY_NAME);
textViewPropertyName.setText(name);
databaseTenants = FirebaseDatabase.getInstance().getReference("tenants").child(uid).child(id).child(uid);
//databaseTenants = FirebaseDatabase.getInstance().getReference("tenants").child(id);
buttonAddTenant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTenant();
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseTenants.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tenants.clear();
for(DataSnapshot tenantSnapshot : dataSnapshot.getChildren()){
Tenant tenant = tenantSnapshot.getValue(Tenant.class);
tenants.add(tenant);
}
tenantListAdapter.notifyDatasetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void saveTenant() {
String tenantName = editTextTenantsName.getText().toString().trim();
int age = seekBarAge.getProgress();
if(!TextUtils.isEmpty(tenantName)){
String id = databaseTenants.push().getKey();
Tenant tenant = new Tenant(id, tenantName, age);
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getUid();
databaseTenants.child(uid).child(id).setValue(tenant);
Toast.makeText(this, "Tenant saved successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Tenant name should not be empty", Toast.LENGTH_LONG).show();
}
}
}
TenantList
public class TenantList extends ArrayAdapter<Tenant> {
private Activity context;
private List<Tenant> tenants;
public TenantList(Activity context, List<Tenant> tenants) {
super(context, R.layout.tenant_list_layout, tenants);
this.context = context;
this.tenants = tenants;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.tenant_list_layout, null, true);
TextView textViewTenant = (TextView) listViewItem.findViewById(R.id.textViewTenant);
TextView textViewAge = (TextView) listViewItem.findViewById(R.id.textViewAge);
Tenant tenant = tenants.get(position);
textViewTenant.setText(tenant.getTenantName());
textViewAge.setText(String.valueOf(tenant.getTenantAge()));
return listViewItem;
}
}
To add a bit more context, here is my data structure:
From what I'm seeing there's still one level until you get to the tennat object.
databaseTenants = FirebaseDatabase.getInstance().getReference("tenants").child(uid).child(id).child(uid);
Also, pull your adapter creation to the onCreate method so you can access it globally:
Add a member variable:
TenantList tenantListAdapter
and initialize it after your listview, pull the tennants to before the adapter instantiation so you can access it:
listViewTenants = (ListView) findViewById(R.id.listViewTenants);
tenants = new ArrayList<>();
tenantListAdapter = new TenantList(this, tenants);
listViewTenants.setAdapter(tenantListAdapter);
Then, in your event listener just do:
databaseTenants.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tenants.clear();
for(DataSnapshot tenantSnapshot : dataSnapshot.getChildren()){
for(DataSnapshot lastSnapshot: tenantSnapshot.getChildren()){
Tenant tenant = lastSnapshot.getValue(Tenant.class);
tenants.add(tenant);
}
}
tenantListAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Load JSON arraylist in separate class and load in another activity

I am trying to load some items from JSON, I am able to get and parse the JSON and load it up in listview when using one activity. However, I want to use a LoadJSON.class to load the JSON, and then the activity can call the json passed and show it in the listview in that activity.
Here is what I have tried:
SongsManager.class
public class SongsManager {
private String TAG = SongsManager.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxxxx.com/jame/mp3/songlist.json";
private List<SolTracks> solTracksList;
private ProgressDialog pDialog;
private final Activity activity;
public SongsManager(Activity activity) {
this.activity = activity;
solTracksList = new ArrayList<>();
pDialog = new ProgressDialog(activity);
fetchSongs();
}
private void fetchSongs() {
pDialog.setMessage("Fetching Playlist...");
pDialog.show();
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(API_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "Responser = " + response.toString());
pDialog.hide();
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
String songTitle = movieObj.getString("title");
String songId = movieObj.getString("id");
String streamUrl = movieObj.getString("stream_url");
SolTracks m = new SolTracks(songTitle, songId, streamUrl);
solTracksList.add(m);
Collections.sort(solTracksList, new TrackComparator());
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
pDialog.hide();
Snackbar snackbar = Snackbar
.make(activity.findViewById(android.R.id.content), "PLEASE CHECK YOUR INTERNET", Snackbar.LENGTH_LONG)
.setAction("DISMISS", new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Changing snackbar background
snackbar.getView().setBackgroundColor(ContextCompat.getColor(activity, R.color.colorPrimary));
// Changing message text color
snackbar.setActionTextColor(Color.YELLOW);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
});
req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
public List<SolTracks> getList() {
return solTracksList;
}
Activity class
public class TheMain1 extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
private String TAG = TheMain1.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxx.com/jame/mp3/songlist.json";
private ListView listView;
private SolTracksAdapter adapter;
private ProgressDialog pDialog;
private List<SolTracks> songslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.track_list_view);
songslist = new ArrayList<>();
SongsManager songsManager = new SongsManager(this);
songslist = songsManager.getList();
adapter = new SolTracksAdapter(this, songslist);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SolTracks track = songslist.get(position);
final String stream_url = track.stream_url;
final String id_url = track.id;
Intent intent = new Intent(TheMain1.this, PlayerActivity.class);
intent.putExtra("songPosition", position);
intent.putExtra("streamUrl", stream_url);
startActivity(intent);
}
}
);
}
As it is right now, I know the JSON is loaded from SongsManager, but its just not displaying in the listview of the Activity class. Can anyone help, and show what I'm doing wrong? Thanks
I was able to fix this by implementing Parcelable to send the list to the receiving activity.
public class SolTracks implements Parcelable {
public String title;
public String id;
public String stream_url;
}
Sending the list from the Activity A:
Intent intent = new Intent(TheMain.this, PlayerActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", solTracksList);
intent.putExtras(bundle);
intent.putExtra("songPosition", position);
startActivity(intent);
and then receiving in Activity B:
Bundle extras = getIntent().getExtras();
if (extras != null) {
songPosition = extras.getInt("songPosition");
trackList = extras.getParcelableArrayList("mylist");
}

How to pass data from activity to another activity on Android

I want to pass data from my Login Page to My Detail Page. However the Detail Page cannot accept the data because the String sent in Login Page has null value on Detail Page.
This is my Login Page Code:
public class MainActivity extends AppCompatActivity {
EditText editText, editText1;
Button button;
int success = 0;
ProgressDialog progressDialog;
JSONObject jsonObject;
HTTPURLConnection service;
String strname ="", strpass="";
String response;
String path = "http://sumbanggagasan.890m.com/select2.php";
Intent intent;
DetailGagasanku detailGagasanku;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.nik);
editText1 = (EditText) findViewById(R.id.pass);
button = (Button) findViewById(R.id.signin);
service = new HTTPURLConnection();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("") && !editText1.getText().toString().equals("")){
strname = editText.getText().toString();
strpass = editText1.getText().toString();
response = null;
new PostDataTOServer().execute();
} else{
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("NIK", strname);
postDataParams.put("pass", strpass);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
System.out.println(response + "menu");
jsonObject = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + jsonObject.get("successs"));
//success = jsonObject.getInt("success");
success = Integer.parseInt(jsonObject.getString("successs").trim());
System.out.println("Do in");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("Post 1");
System.out.println(strname);
if (progressDialog.isShowing()) {
System.out.println("Post 2");
System.out.println(strpass);
progressDialog.dismiss();
}
if(success==1) {
//Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
Intent intent;
Bundle b;
b = new Bundle();
b.putString("username", strname);
intent = new Intent(getApplicationContext(), LandingPage.class);
intent.putExtras(b);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "Login gagal", Toast.LENGTH_LONG).show();
}
}
}
And this is my Details code:
public class DetailGagasanku extends AppCompatActivity {
TextView judul, manfaat;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_gagasanku);
judul = (TextView)findViewById(R.id.textJudul);
manfaat = (TextView) findViewById(R.id.textManfaat);
bundle = getIntent().getExtras();
judul.setText(bundle.getString("judul_gagasan"));
if (bundle != null) {
if(bundle.containsKey("username"))
{
String s = bundle.getString("username");
manfaat.setText(s);
}
else
{
System.out.println("not send");
}
}
}
}
I want to ask why that username has null value. For your information, that "judul_gagasan" variable can receive value from another activity. I send it from My Adapter.
this is my Adapter code:
public class GagasanAdapter extends RecyclerView.Adapter<GagasanAdapter.GagasanHolder> {
List<String> gagasanList = new ArrayList<>();
public GagasanAdapter(List<String> gagasanList) {
this.gagasanList = gagasanList;
Log.v("gagasanSize", "" + gagasanList.size());
}
#Override
public GagasanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gagasan, parent, false);
return new GagasanHolder(v);
}
#Override
public void onBindViewHolder(final GagasanHolder holder, final int position) {
Log.v("Gagasan[" + position + "]", gagasanList.get(position));
String item = gagasanList.get(position);
holder.judulGagasan.setText(item);
holder.judulGagasan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailGagasanku.class);
intent.putExtra("judul_gagasan", holder.judulGagasan.getText().toString());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return gagasanList.size();
}
public class GagasanHolder extends RecyclerView.ViewHolder{
TextView judulGagasan;
public GagasanHolder(View itemView) {
super(itemView);
judulGagasan = (TextView) itemView.findViewById(R.id.tvListGagasan);
}
}
}
You pass "username" in Bundle to LandingPage Activity, so you can't access in DetailGagasanku Activity.
So to access "username" in DetailGagasanku Activity, pass username from adapter.

Categories