Passing Objects Between Intents (intent.putExtra), with Realm Objects - java

I have realm objects with Primary keys here's an example:
#RealmClass
public class Person extends RealmObject(){
#PrimaryKey
Int personID;
String name;
Int age;
}
The Person onjects are viewed in a recycler view, where the viewholder has an OnClick method. The OnClick method is fully functional, in the sense that screens change and everything inside it executes. However the Data from the specific Person object selected does not pass through.
Here is the code inside the OnClick method:
Intent intent = new Intent(this, PersonStats.class);
intent.putExtra("I don't know what to put here!");
startActivity(intent);
Where PersonStats is the class that will show all the stats of the Person object selected from the recycler view. I've been messing around with the intent.putExtra function but I can't get it to work. How would I go about this?
Edit: I'm asking for how to get the specific Realm Object that I selected from the recycler view so I can pass it through putExtra. As RecyclerView postion != PrimaryKey.

Related

Trying to explain a Java method in Android Studio with Intent

I'm trying to do a written report on some code and I found one on youtube. However I don't understand what is going on exactly. I understand that it get's the ID of a certain object which then opens in a new Java class but if someone could breakdown what is happening it would be greatly appreciated.
private void setUpOnclickListener()
{
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l)
{
Supplier selectSupplier = (Supplier) (listView.getItemAtPosition(position));
Intent showDetail = new Intent(getApplicationContext(), DetailActivity.class);
showDetail.putExtra("id",selectSupplier.getId());
startActivity(showDetail);
}
});
}
at first read some doc, what IS an Activity, then read how to start new one, and why Intent is needed for this
in short: this Intent is carrying information what dev want to start/open (will start new "window" - DetailActivity) and what will be passed to this component (some id)
The code gets the supplier that is clicked on in the listview in order to gain their supplier id. That ID is then given to the DetailActivity page using an intent, whereby it will be used to display the details that relate to the specific supplier. On the DetailActivity page, the intent and its extra information, namely the supplier id, will be retrieved, and then can be used to display the details for the specific supplier that was clicked on on the previous page.

How to handle/inflate more then one recycleview activity from an adapter class

It's quite hard to put My doubt in words but ill try, Hi there I am creating simple book app where user can learn different languages like java,c,c++, and I got and question mark here. my question is how can I control/Inflate more than one RecycleView activity from an adapter class or should I make different RecycleViewand and adapter system for every single language.
i.e I just want an app having multiple buttons with different languages where user can click on the button and learn programming concept listed there he can come back and click another button in order to learn another language as well
"I hope you got my point"
You must use different data
Also you can use different layout for any item
in your model.class (model of data for recyclerView you can define a variable for Type of data
ex :
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type= Type;
}
i use from this setter and getter
so in your addapter class insert below method
#Override
public int getItemViewType(int position) {
return ;
}
with this method you can pass any value you want and get it as int i in myViewHohder onCreateViewHolder method
public myViewHohder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return ;
}
and you can with a (if) Condition to decide for layout of item

Android - Design trouble - Should I use setTag to hold information for OnClick event?

I'm doing a small project as part of the Android course.
The app is supposed to retrieve the most popular movies using some site's API and then display them in a grid view (using posters as thumbnails).
When a specific movie is clicked a new activity will be started providing details.
I've gotten this far:
Obtained a list of most popular movies poster image URL's using the website's API.
Implemented an adapter extending ArrayAdapter which accepts ArrayList as the data source and loads the image from URL into ImageView item.
Populated the GridView using the adapter.
Setup listeners on Gridview using this code:
s:
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
//do stuff according to position/view
}
The info I need to pass onto the movie details activity when a movie is clicked can be obtained in step 1 (I just extracted the poster URLS from the json).
To be able to even provide information when a view is clicked I need to (at the very minimum) also extract the movie's ID and store it.
So as it seems my options are:
Store the IDs in the adapter. Then when a click occurs use getItem(position) to obtain the ID and send it with the intent. The next activity will then have to query the server for the movie details.
This means creating a class:
static class MovieItem {
int Id;
string posterUrl;
}
And converting the adapter to use ArrayList<MovieItem>.
Same as option 1 but instead use setTag to store the Id of the movie.
Same as option 1 but instead obtain all the required information (title, rating, plot, etc..) and store it to MovieItem. Query not required in the next activity.
Same as option 3 but instead use setTag (MovieItem). Query not required in the next activity.
I'm new to app development and I'm trying to get things done the right way, Would appreciate some help.
EDIT:
Also wanted to add, if I had stored additional movie information in the adapter would that not have been appropriate because the information isn't relevant to that class?
Thanks for your troubles! :)
When you first request the list of Movie info, you could store the details for each movie in something like a HashMap<String, HashMap<String, String>>, where the String is the movie id, and the Map is a set of Key/Value pairs for details information. Then, when a click comes through on your onClick, you would use the position to determine which movie poster was clicked. You would then retrieve the details HashMap for the selected movie, put it into a Bundle, pass it to the Intent of your new Activity, then retrieve it on the other side. So the code would look something like this:
When you first retrieve your list of movies, you would do something like this:
//You would put each set of movie data into a HashMap like this...
HashMap<String, HashMap<String, String>> movies = new HashMap<>();
HashMap<String, String> details = new HashMap<>();
details.put("dateReleased", "7.12.2015");
details.put("rating", "PG-13");
details.put("title", "Cool Awesome Movie");
movies.put("12345", details);
//Then when an onClick comes in, you would get the set of
//details for the movie that was selected (based on position)
HashMap<String, String> selectedDetails = movies.get("12345");
//Put the retrieved HashMap of details into a Bundle
Bundle bundle = new Bundle();
bundle.putSerializable("movieDetails", selectedDetails);
//Send the bundle over to the new Activity with the intent
Intent intent = new Intent(this, YourDetailsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
Then when the new Activity starts, you would retrieve the details from the Bundle in your onCreate():
//Then in onCreate() of the new Activity...
Bundle bundle = getIntent().getExtras();
HashMap<String, String> movieDetails = (HashMap<String, String>) bundle.getSerializable("movieDetails");
String dateReleased = movieDetails.get("dateReleased");
String rating = movieDetails.get("rating");
String title = movieDetails.get("title");

Android remove and add to ArrayList in between activities

I'm making my first android app and here's where i'm stuck.
I have an activity A which requires 4 players to be picked.
I'm passing to the activity PickPlayer 1,2,3,4 according to which player i want to fill.
ImageButton addp1 = (ImageButton)findViewById(R.id.player1);
addp1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(getApplicationContext(), PickPlayer.class);
i.putExtra("playersList", playersList);
startActivityForResult(i, 1);
}
});
On the PickPlayer activity i have a list which is populated and each item receives a listener.
final ArrayList<Player> playersList = (ArrayList<Player>)getIntent().getSerializableExtra("playersList");
lv.setAdapter(new PlayerItemAdapter(this, android.R.layout.simple_list_item_1, playersList));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
player = playersList.get(position);
playersList.remove(position);
Intent intentMessage = new Intent();
intentMessage.putExtra("player", player);
intentMessage.putExtra("playersList", playersList);
setResult(RESULT_OK, intentMessage);
finish();
}
});`
The above works fine by creating the playersList on activity A and passing it through from one to another each time and removing the player from the playerList on click.
Problem is if a player is chosen by mistake he needs to be put back into the list again once replaced by someone else.
Any suggestions on implementing this ?
One way i thought of is to pass from activity A to PickPlayer the player ( if one is assigned already at his position ) and readding him to the playerList again but i'm sure there's a better way for it.
I'm new to android so i have no idea about resources and best practises.
( example passing an object through activities or an id and run a db query).
Thanks
IMO, you'll achieve best results with a singleton class (or methods on Application instance - here a good stackoverflow question about it).
Your array would be an internal member of the singleton and have an boolean attribute to indicate if a player is already picked or not. Some methods using this attribute can be implemented like:
List<Player> getPickedPlayers()
List<Player> getNotPickedPlayers()
void setPlayerPicked(Player player)
void setPlayerNotPicked(Player player)
and so on...
Hope it helps!
When you send object through an Intent's bundle (i.putExtra("playersList", playersList);), it is marshalled and then unmarshalled on the other side (the new activity). This mean you have 2 instances of ArrayList and its content (one in each activity). If you wish to share data between activity A and activity B, I suggest you store it on an Application instance or by using a singleton.
If your data is coming from a database, you can pass the id through the intent, and get the list of players and the special player with a database query.
Not sure if this is the best way to accomplish this but i'm going to share with you.
I move the arrayList with the players back and forth in between the activities.
Once the player is sent back it's removed from it and kept in an object player1,player2,player3 etc etc.
So if the user clicks the button that has already a player assigned to it i simply add that player again into the list and pass the arrayList as i would do if it was empty.

Trouble with findViewById, explained diagramatically

Hello everyone.
I've posted a basic diagram of my Android project above. It's pretty sad but that's what 5 minutes in paint get you.
Anyway, I'll walk you through it. I have xml with a series of imageViews which have onClickListeners in my board.Java class. If one of the imageViews are clicked on, an instance of pawn.java is instantiated, I pass the context to the instantiated pawn object, then call its possibleMoves() method.
At the end of this method I generate a list of int's which happen to be the id's of the imageViews. the final portion of possibleMoves() is the following:
for (String s : chunks) {
String possibleSquare = "s" + s.substring(2, 4);
Toast.makeText(boardContext, possibleSquare, Toast.LENGTH_SHORT).show();
int id = boardContext.getResources().getIdentifier(possibleSquare, "id", boardContext.getPackageName());
System.out.println(id);
ImageView backgroundImg = (ImageView) findViewById(id);
backgroundImg.setBackgroundColor(Color.rgb(255, 255, 255));
}
return list;
The issue I'm having is that AndroidStudio says my findViewById(id) cannot be resolved. I've tried putting the context boardContext (the context I pass to my instantiated pawn object) in front of the findViewById, and I've tried using findViewById(R.id.id).
Suggestions?
findViewById(int id) are functions for View objects - here.. so you can not call it on nothing or any object. When you have reference to an Activity and you call findViewById(int id) it pulls the activity's contentView and calls it on it..
so your to your solution, Inflate the View containing your ImageView or get reference to your activity or if your context that you are passing is an Activity as context then you can cast your activity to the context and call your prefered method

Categories