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
Related
I am trying to create an intent with bundle extras but I am getting null pointer exception error on the Array List.
Here is the error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getParcelableArrayList(java.lang.String)' on a null object reference
Am I implementing intents wrong?
Here is my application below for MP3 Player:
PlaylistSelector:
public class PlaylistSelector extends AppCompatActivity {
ListView listview;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
listview = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission()
{
Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
displaySongs();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong (File file)
{
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
for (File singlefile: files)
{
if (singlefile.isDirectory() && !singlefile.isHidden())
{
arrayList.addAll(findSong(singlefile));
}
else
{
if (singlefile.getName().endsWith(".mp3") || singlefile.getName().endsWith(".wav"))
{
arrayList.add(singlefile);
}
}
}
return arrayList;
}
void displaySongs()
{
final ArrayList<File> mySongs = findSong(Environment.getExternalStorageDirectory());
items = new String[mySongs.size()];
for(int i = 0; i<mySongs.size(); i++)
{
items[i] = mySongs.get(i).getName().toString().replace(".mp3","").replace(".wav","");
}
/*ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,songs);
listview.setAdapter(myAdapter);*/
customAdapter customAdapter = new customAdapter();
listview.setAdapter(customAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String songName = (String) listview.getItemAtPosition(i);
startActivity(new Intent(getApplicationContext(), MainActivity.class)
.putExtra("songs", mySongs)
.putExtra("songname", songName)
.putExtra("pos", i));
}
});
}
class customAdapter extends BaseAdapter{
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View myView = getLayoutInflater().inflate(R.layout.list_item, null);
TextView textsong = myView.findViewById(R.id.txtsongname);
textsong.setSelected(true);
textsong.setText(items[i]);
return myView;
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private InputSource inputSource;
Button playbtn, btnnext,btnprev,btnff,btnrw;
TextView txtsn, txtsstop,txtsstart;
SeekBar seekmusic;
BarVisualizer visualizer;
String sname;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList<File> mySongs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View frameLayoutMP = findViewById(R.id.preview_mp3_layout);
btnprev = findViewById(R.id.btnprev);
playbtn = findViewById(R.id.playbtn);
btnnext = findViewById(R.id.btnnext);
btnrw = findViewById(R.id.btnrw);
btnff = findViewById(R.id.btnff);
txtsn = findViewById(R.id.txtsn);
txtsstop = findViewById(R.id.txtsstop);
txtsstart = findViewById(R.id.txtsstart);
seekmusic = findViewById(R.id.seekbar);
visualizer = findViewById(R.id.blast);
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
}
Intent i = getIntent();
Bundle bundle = i.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
String songName = i.getStringExtra("songname");
position = bundle.getInt("pos",0);
txtsn.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString());
sname = mySongs.get(position).getName();
txtsn.setText(sname);
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
mediaPlayer.start();
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaPlayer.isPlaying())
{
playbtn.setBackgroundResource(R.drawable.ic_play);
mediaPlayer.pause();
}
else
{
playbtn.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
}
});
}
}
I am trying to get this intent to grab song lists from playlists and put it into the player
i have a problem and my problem is : when i kill the app or shutting down the device , all the information was erased and i can find it , first of all and what i want to do in the first place is: i want to check if this is the first time of the user to use this app or not , if that is the first time then save what he chosen in the sharedPreference xml and if not , then retrieve was chosen and show it , sorry for my bad english , it's not my mother tongue
this is the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quran);
readers= (CardView)findViewById(R.id.readers);
readers_name=(TextView)findViewById(R.id.readers_name);
rewaya=(TextView)findViewById(R.id.rewaya);
count=(TextView)findViewById(R.id.count);
Intent i = getIntent();
String txtData = i.getStringExtra("reciters_name");
String txtData1 = i.getStringExtra("reciters_rewaya");
String txtData2 = i.getStringExtra("reciters_count");
shareRef=getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor myedit = shareRef.edit();
boolean firstRun = shareRef.getBoolean("firstRun", true);
if(firstRun) {
myedit.clear();
myedit.putString("reciters", txtData);
myedit.putBoolean("firstRun", false);
myedit.putString("rewaya", txtData1);
myedit.putString("count", txtData2);
myedit.commit();
readers_name.setText(txtData);
rewaya.setText(txtData1);
count.setText(txtData2);
}else {
readers_name.setText(shareRef.getString("reciters", ""));
rewaya.setText(shareRef.getString("rewaya", ""));
count.setText(shareRef.getString("count", ""));
}
fav_suras=(RecyclerView)findViewById(R.id.fav_suras);
fav_suras.setLayoutManager(new LinearLayoutManager(this));
suras=(RecyclerView)findViewById(R.id.suras);
suras.setHasFixedSize(true);
suras.setLayoutManager(new LinearLayoutManager(this));
suras.setAdapter(Mquraan_adapter);
//mSuras_api = new ArrayList<>();
getRetrofit();
readers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (quran.this, Readers.class);
startActivity(intent);
}
});
}
public void getRetrofit() {
RequestInterface requestInterface = PostClient.getApiClient().create(RequestInterface.class);
Call<FomCombine> call = requestInterface.getPosts();
call.enqueue(new Callback <FomCombine>() {
#Override
public void onResponse(Call<FomCombine> call, retrofit2.Response <FomCombine> response) {
Toast.makeText(quran.this, "success", Toast.LENGTH_SHORT).show();
mSuras_api = response.body().getfom_combine();
Mquraan_adapter= new quran_adapter(quran.this, (ArrayList<suras_api>) mSuras_api);
suras.setAdapter(Mquraan_adapter);
Mquraan_adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<FomCombine> call, Throwable t) {
Log.d("Tag", t.getMessage());
}
});
}}
this is the adapter
private Context mContext ;
private ArrayList<Reciters_api> mReciters_api;
public Reciters_adapter(Context context, ArrayList<Reciters_api> mmReciters_api) {
mContext=context;
mReciters_api=mmReciters_api;
}
#NonNull
#Override
public Reciters_adapter.ReadersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.single_row,parent,false);
return new ReadersViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ReadersViewHolder holder, int position) {
Reciters_api reciters = mReciters_api.get(position);
String ID_number = reciters.getId1();
String Name =reciters.getName1();
String Rewaya = reciters.getRewaya();
String count =reciters.getCount();
holder.readers_names.setText(Name);
holder.countt.setText(count);
holder.rewayya.setText(Rewaya);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent Reciters = new Intent(context, quran.class);
Reciters.putExtra("reciters_name", Name);
Reciters.putExtra("reciters_rewaya", Rewaya);
Reciters.putExtra("reciters_count", count);
context.startActivity(Reciters);
}
});
}
#Override
public int getItemCount() {
return mReciters_api.size();
}
public class ReadersViewHolder extends RecyclerView.ViewHolder{
public TextView readers_names ,rewayya ,countt;
public ReadersViewHolder(#NonNull View itemView) {
super(itemView);
readers_names=itemView.findViewById(R.id.readers_names);
rewayya=itemView.findViewById(R.id.rewayya);
countt=itemView.findViewById(R.id.countt);
}
}
}
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();
}
});
}
}
i'm from indonesia, i want to refresh a fragment after i insert a data to it.. i have try many times to refresh a fragment. but it can't work.
please help me..
here's my code..
class MainActivity
public class MainActivity extends FragmentActivity {
public MainActivity() {
}
DatabaseReference dataBaseref;
StorageReference strRef;
TextView logout;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBaseref = FirebaseDatabase.getInstance().getReference();
strRef = FirebaseStorage.getInstance().getReference();
tabLayout = findViewById(R.id.tab_layout_isi_menu);
viewPager = findViewById(R.id.view_pager_isi_menu);
logout = findViewById(R.id.text_logout);
viewAdapter = new ViewPagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewAdapter.addFragment(new isi_list_beli(), "Beli");
viewAdapter.addFragment(new isi_list_cek(), "Cek Data");
viewPager.setAdapter(viewAdapter);
tabLayout.setupWithViewPager(viewPager);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logOut();
}
});
}
private void logOut() {
AuthUI.getInstance()
.signOut(MainActivity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
}
public void onBackPressed() {
super.finish();
}
}
class isi_list_cek
public class isi_list_cek extends Fragment {
private ListView listView;
public AdapterListCek adapterListCek = null;
private ArrayList<Cek> cekArrayList;
Cursor cursor;
View view;
FloatingActionButton fab;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
adapterListCek.notifyDataSetChanged();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #NonNull Bundle savedInstanceState) {
view = inflater.inflate(R.layout.list_barang, container, false);
listView = view.findViewById(R.id.list_item_barang);
fab = view.findViewById(R.id.tambah_barang);
cekArrayList = new ArrayList<>();
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
listView.setAdapter(adapterListCek);
cursor = fragment_input_data.sqlHelper.getData("SELECT * FROM CEK");
if(cursor.moveToFirst()){
cekArrayList.clear();
do{
int id = cursor.getInt(0);
String kode = cursor.getString(1);
String nama = cursor.getString(2);
String jumlah = cursor.getString(3);
String harga = cursor.getString(4);
byte[] gambar = cursor.getBlob(5);
cekArrayList.add(new Cek(id, kode, nama, harga, jumlah, gambar));
}while (cursor.moveToNext());
fragment_input_data.sqlHelper.close();
}
adapterListCek.notifyDataSetChanged();
listView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
return false;
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), fragment_input_data.class));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
class ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private Context mContext;
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentListTitle = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm, Context mContext) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentListTitle.size();
//return 2;
}
#NonNull
#Override
public CharSequence getPageTitle(int position) {
return fragmentListTitle.get(position);
}
public void addFragment (Fragment fragment, String string){
fragmentList.add(fragment);
fragmentListTitle.add(string);
}
}
i expect when i insert some data, fragment will automatically update it's view.
call a function as: just send the new instance of present fragment that you want to recreate
replaceFragment(new YourPresentFragment());
the function can be as below:
private void replaceFragment(Fragment fragment) {
String fragmentTag = fragment.getClass().getName();
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.fragments, fragment, fragmentTag);
ft.addToBackStack("fragments");
ft.commit();
}
this should do the job
Hello need help with a class trying to figure out how to create a first and last button in a fragment that will jump to the first item in a ViewPager and the last item in a ViewPager I'm a bit lost with how to implement. Here is the fragment.
public class CrimeFragment extends Fragment {
private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
private static final int REQUEST_DATE = 0;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
private Spinner mSpinner;
private Button mFirstButton;
private Button mLastButton;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date =
(Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(
CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(
CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mSpinner = (Spinner) v.findViewById(R.id.crime_severity);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.severity_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
mCrime.setSeverity((String) mSpinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return v;
}
}
Here is the Activity with the ViewPager.
public class CrimePagerActivity extends FragmentActivity{
private static final String EXTRA_CRIME_ID = "com.martin.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.activity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
For the First button Im pretty sure I just need to set item to 0? For last button I need to set item to size - 1 just not sure how to do that.
In your CrimePagerActivity, write two method's to jump to the ViewPager first page and last page.
CrimePagerActivity.java:
public void jumpToFirstPage() {
mViewPager.setCurrentItem(0);
}
public void jumpToLastPage() {
mViewPager.setCurrentItem(mCrimes.size() - 1);
}
Call those method's from mFirstButton and mLastButton click listener method:
CrimeFragment.java:
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToFirstPage();
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToLastPage();
}
});
Hope this will work perfectly.
Ok this was a answer that I was given by the teacher incase anyone is interested.
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(0);
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(CrimeLab.get(getActivity()).getCrimes().size()-1);
}
});
Create two button and on click set
viewPager.setCurrentItem(0); // for top
and
viewPager.setCurrentItem(mCrimes.size()); // for last