Generalized Android Activity - android

I am new to Android programming. My question is that i have a list (ListView) of 8 restaurant headings. Upon clicking of any of these, a new page (activity) would start containing the menu and details of the restaurant. I understand that implementing 8 activities would be wasteful so probably i will have a general restaurant detail activity.
Now i am figuring out how to display this information out in an efficient way. I have so far implemented this which helps me to send a message across to the other activity according to the restaurant selected. But how can i send big chunks of information:
----MainActivity.java------
String [] restaurants = {"abc","def"....};
int POSITION_ACT;
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
POSITION_ACT=position;
customActivity(view);
}
});
public void customActivity(View view) {
Intent intent = new Intent(this, RestaurantDetails.class);
intent.putExtra(MESSAGE, "You clicked this restaurant: " + restaurants[POSITION_ACT]);
startActivity(intent);
}
--generalrestaurant.java----
Intent intent = getIntent();
String msg = intent.getStringExtra(foodActivity.MESSAGE);
TextView tt1 = (TextView) findViewById(R.id.tt1);
tt1.setText(msg);

You shouldn't be passing lots of information. Your model information should be in instances of a Restaurant class. Then you can keep all those instances in an ArrayList in a singleton. Write a getter for the singleton that returns a Restaurant instance and then call it from the RestaurantDetails activity using the extra you sent (maybe you want to make this a UUID). Finally, when the activity dies, you should save the Restaurant data from the singleton to a raw XML file or something and read it back in when the app starts up again.

You can create a POJO for your restaurant information and write data like Name, Location, Per head cost, rating etc to it. Then your POJO must implement Serializable or Parcelable. In your intent you can pass your POJO using intent.putExtra(String, Serializable) or intent.putExtra(String, Parcelable). In your second activity you can get the object and display your data in your Activity. Have a look at the below links :
http://developer.android.com/reference/java/io/Serializable.html
http://developer.android.com/reference/android/os/Parcelable.html

Related

Pass object or objects id to new activity

If I have a list of certain items (let's say fruits) in one activity. Here the items are completely loaded from a ROOM database.
Clicking on a Fruit should take you to the FruitDetailPage. Ofcourse I have to pass the Fruit to the new activity with an Intent.
But what would be better to do?
Pass the complete fruit object
Pass the fruit_id and reload the fruit object from the database in the new activity
Pass object will be better, because the bundle has a size limit, therefore, as the fields of the object increase, you can catch errors. You will also need to keep less space in memory.And most importantly, you do not have to write extra code and inherit your object from Parcelabe.
In your list activity:
int fruitId = 5;
Intent i = new Intent(this/*activity*/, FruitDetailPage.class);
i.putExtra("fruit_id", fruitId);
startActivity(i);
In your FruitDetailPage activity:
void onCreate(Bundle bundle) {
super.onCreate(bundle);
int fruitId = getIntent().getIntExtra("fruit_id", -1);
}

Sending data in through multiple screens

In my app , at a particular screen there is Arraylist which is a source of recycler view . There are many buttons on that screen which takes you to next screen , next screen may be a single plain activity or activity with view pager and tablayout and that fragment may contain buttons which takes you to next screen .In some screen i can edit the Song class field too . My problem is that i am confused whether the send the list to next screen and further next fragment or next screens through intent or should i make that static and access it anywhere . Again and again i have to parcel wrap and then unwrap then send it to fragment then wrap for the fragment then unwarp it then send it to adpater attached to fragment , this is long process and i am afraid that anyone can change that list in any screen and secondly this whole process is cumbersome every time sending intent and receiving intent .
Passing the Values from Intent have chances of data loss so do not pass the multiple Values with the Intent. So it will be better to access the values from a Static class if the values are not changing. If sometimes values are changing then pass these with Intent.
You can also go with the SharedPreferences, it will be more feasible in your case.
You can shift to flux architecture. Redux store kind of state management.
Who ever needs data queries to store. And data changes automatically dispatched to listeners.
SharedPreferences are NOT made to pass data between Activities/Fragments. They are here to store data that need to persist when the app is closed.
An option could be to use some kind of "cache" class that will store your data. So let's say you display the list of whatever data you want on the first screen, then the user selects one of the items to see the details/modify it. So you give the position of this data (in the array stored in the cache) to your next fragment and this next fragment asks the cache to give to it the data, based on the position it has received.
Example
Cache class
public class Cache{
List<Object> data;
// ... Implementation
public List<Object> getData(){
return this.data;
}
public setData(List<Object> data){
this.data = data;
}
public Object getObject(int position){
return data.get(position);
}
}
List Activity
public class ListDataActivity extends ListActivity{
public void onCreate(...){
// get the data
...
// Set the data to the cache
Cache.getInstance().setData(data);
// Display the list
...
}
public void onItemClicked(...){
Intent intent =....
intent.put(ITEM_POSITION, pos);
startActivity(intent);
}
}
Details Activity
public class DetailsActivity extends Activity{
public void onCreate(...){
//...
// get data from the cache
int pos = getIntent.getInt(ITEM_POSITION);
Object obj = Cache.getInstance().getObject(pos);
// Display the details
...
}
}

pass listview values from one activity to another activity

I have one list view and there are different values within it such as name, qty,unit,disc,price. I want to pass these values to next activity. I set 5 text boxes in new activity. this new activity is for update the values. how to pass values and display the same in new activity.???
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), Update.class);
myIntent.putExtra("ItemName", "value");
startActivity(myIntent);
}
});
You can use following ways for sharing data in android:
Intent and put extra data in the Bundle
SharePreferences in the Application class
SQLite database
Static variable
You can pass the data via Intent Extras eg :-
Intent intent = new Intent(this,calledActivity.class);
intent.putExtra("Caller",THIS_ACTIVITY);
startActivity(intent);
In this example Caller is the Key and THIS_ACTIVITY contains the value to be passed. This is then retrieved in the called activity like :-
String caller = getIntent().getStringExtra("Caller");
You can pass an entire object through Intents, as long as they implement the Parcelable / Serializable class.
public class Myclass implements Parcelable {}
Implementing these classes will ensure that your Object can be serialized.
Then you will be able to attach it to your Intent, and later retrieve it by calling getParcelableExtra or other methods.

How to restart activity with data of previous or next position of a ListView

I'm building a book reader app and currently having some issues on how to move to next or previous chapter.
The fragment that is in charge of showing a list of chapter (basically a ListView). I capture the item with onItemClick:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity().getApplicationContext(),ReaderActivity.class);
intent.putExtra("name",adapter.getItem(i).getName());
intent.putExtra("url",adapter.getItem(i).getUrl());
startActivity(intent);
}
});
It will start the ReaderActivity and display the content of the book. Now the ReaderActivity has 2 buttons for moving to next/previous chapter. How can I get the data (the name and url) from the ListView?
At the moment I'm thinking of two methods:
Calling finish() on ReaderActivity and override the onDestroy() method to call a method to get the next/previous data in the fragment that holds the ListView.
Passing the whole ArrayList of chapters to ReaderActivity so it can retrieve the item it wants (probably not a good solution since there are too many chapters).
Is there a better way?
There are way to many ways to get the best one.
Some of them:
Use your Application.java to share in-memory data (data stores) from any place. Example:
public final Application extends android.app.Application {
private List<Chapter> chapters;
public void setChapters(List<Chapter> chapters) {
this.chapters = chapters != null ? chapters : Collections.<Chapter>epmtyList();
}
public List<Chapter> get Chapters() {
return chapters;
}
}
// from any place which has context (or is context)
List<Chapter> chapters = ((Application) getContext().getApplicationContext()).getChapters();
Make your list a static member with a public static getter and then reference is from your ReaderActivity
public final ApplicationActivity extends Activity {
private static List<Chapter> chapters;
....
public static List<Chapter> getChapters() {
return chapters;
}
Store the list in shared preferences so any activity can reference it
Include the list of chapters in your intent extras and pass it to your ReaderActivity
I think your ReaderActivity needs to deal with the whole book rather a single chapter. Which means approach (4) is most likely a good candidate.
I would put the list data in the Application class (or another singleton), and then the ReaderActivity would be able to query it for the next chapter. Actually then it could just get the details of the next chapter and update its contents accordingly, without needing to create a new activity at all.

Android and parse

i made a listview with all the posts in the list.
what i want is when i click the child in the list i want another activity to be opened showing that specific post and the related comments
the question is how to know which item is clicked and how to show that particular post ParseObject in next activity
as they do in messaging app in which you click the message from the listview and subsequent messages are shown in the next activity
i might be very thankful to you if you solve this for me!!
Please Try this code:
Please implement your object class with Serializable
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
try
{
Log.v("position",position); // hear is your list item position
MyClass obj = new MyClass(); // Class must be implements with Serializable
Intent showintent = new Intent(context,<activity class to open>);
showcontactintent.putExtra("obj",obj);
startActivity(showintent);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
Use: Relational Data
Objects can have relationships with other objects. To model this behavior, any ParseObject can be used as a value in other ParseObjects. Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency.
For example, each Comment in a blogging app might correspond to one Post. To create a new Post with a single Comment, you could write:
// Create the post
ParseObject myPost = new ParseObject("Post");
myPost.put("title", "I'm Hungry");
myPost.put("content", "Where should we go for lunch?");
// Create the comment
ParseObject myComment = new ParseObject("Comment");
myComment.put("content", "Let's do Sushirrito.");
// Add a relation between the Post and Comment
myComment.put("parent", myPost);
// This will save both myPost and myComment
myComment.saveInBackground();
You can also link objects using just their objectIds like so:
// Add a relation between the Post with objectId "1zEcyElZ80" and the comment
myComment.put("parent", ParseObject.createWithoutData("Post", "1zEcyElZ80"));
By default, when fetching an object, related ParseObjects are not fetched. These objects' values cannot be retrieved until they have been fetched like so:
fetchedComment.getParseObject("post")
.fetchIfNeededInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject post, ParseException e) {
String title = post.getString("title");
// Do something with your new title variable
}
});
You can also model a many-to-many relation using the ParseRelation object. This works similar to List, except that you don't need to download all the ParseObjects in a relation at once. This allows ParseRelation to scale to many more objects than the List approach. For example, a User may have many Posts that they might like. In this case, you can store the set of Posts that a User likes using getRelation. In order to add a post to the list, the code would look something like:
ParseUser user = ParseUser.getCurrentUser();
ParseRelation<ParseObject> relation = user.getRelation("likes");
relation.add(post);
user.saveInBackground();
You can remove a post from the ParseRelation with something like:
relation.remove(post);
For more read: https://parse.com/docs/android/guide#objects-relational-data
^why did I copy all the words here instead of just providing the link? Because parse links are broken sometimes and doesn't direct you to the section you need (instead it just sends you to https://parse.com/docs/android/guide and because the doc is so large, you won't be able to find it.

Categories

Resources