Lots of Activity used (How to reduce it ? ) - android

This is my first question in stack overflow .
I am creating one project with spinner , When dropdown list is clicked it displays 25 states , If we click any one state it takes us to new activity with LISTVIEW of hotels in that city , If we click any hotel it shows the details .
For this I am creating 2to3 activity , IF my project is small its ok , but i am adding 25 States and each states consists of 10-15 Hotels . It takes too much of time to create it ..
I use New --> Other --> Android --> Android Activity ,
My question is :- Can I create activity with contents (Image , ImageButton & details) using Java code ?

Do not create so many activities for each city and then for each hotel.
You can create only one activity to show city hotels just by passing that city name in EXTRAS in "intent" and show hotels of that city only in new activity.
To send name of city in intent use
Intent intent = new Intent(MAIN_ACTIVITY.this, HOTELS_ACTIVITY.class);
intent.putExtra("city", city_name);
startActivity(intent);
After that in new activity use
String passedCity = getIntent().getExtras().getString("city");
Now you have city name and you can retrieve hotels name of that city accordingly.
In this way you don't have to create so many activities.
Similarly you can use this to show hotel details by passing just its name and retrieving it in next activity.
Good Luck

You should be reusing activities rather than building from scratch each time.
Your data model could possibly look like this:
public class State
{
private String name;
private ArrayList<Hotel> hotels;
public State(String name, ArrayList<Hotel> hotels)
{
this.name = name;
this.hotels = hotels;
}
public ArrayList<Hotel> getHotels()
{
return this.hotels;
}
public String getName()
{
return this.name;
}
}
public class Hotel
{
private String name;
// Add in your other variables here
// Examples: Location, Id, Address
public Hotel(String name)
{
this.name = name;
}
}
Build your data however you please, but you should use objects similar to these to pass through to your 2/3 activities and build the user interface dynamically.

Related

Generalized Android Activity

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

How do I store multiple values in an array in Android?

For this example I have an array:
String[] books = new String[x];
I would like to store the id and title in each location:
books[0]=>id:0, title:"book title1"
books[0]=>id:1, title:"book title2"
books[0]=>id:2, title:"book title3"
books[0]=>id:3, title:"book title4"
I want to store the id since it may change. I'm getting the id and title from a database. Getting the info isn't the issue. I want to store it this way so in my other functions this returns to I can use something like:
btn.setText(regions[i].title)
Any suggestion on how to handle this would be great.
Do one thing, first create a bean class like BookBean.
Under this declare two variables ID and Title. and declare getters and setters (If u are using eclipse u can easily do this by (Source -> generate getters and setters.. option)
and then declare a ArrayList to store BookBean vale as of follow.
ArrayList<BookBean> bookArrayList=new ArrayList<BookBean>();
for(int i=0;i<=urSize;i++)
{
// create a object for BookBean
BookBean book =new BookBean();
book.setID("what ever");
book.setTitle("what ever");
bookArrayList.ass(book)
}
It is better to use Arraylist with custom class.
see this
class Book
{
String id,title;
/* Cunstructor to store data */
public Book(String id,String title)
{
this.id = id;
this.title = title;
}
}
//declare arraylist
ArrayList<Book> bookList = new ArrayList<Book>();
bookList.add("1","book1");
bookList.add("2","book2");
bookList.add("3","book3");
bookList.add("4","book4");
btn.setText(bookList.get(i).title)
I think you have several options
Use a HashMap where you can use your id as key and value title
Define a class and keep id and title as attributes , define get and set methods.
Keep the objects of the class in a ArrayList

Android Listview : Display Item details onItemClic

I have been working on a e-commerce application for a while, and now I have a ListView that displays a list of products - Each products = 1 ImageView and some TextViews-.
I set an onItemClick listener on that ListView, the event that I want to occur when I click on one of that listView products is, Start the i new Activity, 'ProductDetails' that displays more informations on the product I have clicked on.
I have already asked this question somewhere else, but I didn't get a clear answer,
They said that I have to create a new 'list\details' project, but this can't happen now, as I've working on that project for like 20 days, and can't start all over again.
You can't send a TextView or an ImageView from Activity to Activity. what you can send instead is it's contents. so for example if you want to pass the information from the TextView you will need to pass the source String that is displayed there (Or extract the String from the TextView) you do that by passing a Bundle from the calling Activity to the invoked one or simply by putting it as an Extra:
intent.putExtra("string name", value);
and in the following Activity you get this data:
Intent intent = getIntent();
bundle = intent.getExtras();
bundle.getString("string name");
Then in the following Activity create a TextView with the passed String.
Same way is handled with the ImageView by passing the it's path.
Sorry I have posted an answer but was only a link to another site so it was deleted :-(
Here I come again with what could be the solution:
In your first activity, you need to use intent.putExtra(...) and retrieve the datas in your second activity with intent.getExtra(...).
Example activity 1:
i.putExtra("title01", yourDataCollection.get(position).get(KEY_TITLE01));
Activity 2 :
this.title01 = i.getStringExtra("title01");
There is a full project here : http://www.codeproject.com/Articles/507651/Customized-Android-ListView-with-Image-and-Text
Android uses intent to allow Activitys to interact. If you want to show a details of product, probably you have a Class that describe that product and with the information it holds you fill up your ListView. If you let the class Product implements Serializable you can use Intent.putExtra(String name, Serializable obj), to pass the Product description between Activitys. In ProductDetailsActivity you can use:
getIntent(). getSerializableExtra (String name)
to retrive the serializable you put inside the Intent you created to start ProductDetailsActivity
If you pass your model class around many times using Intent, perhaps it could implement the Parcelable interface for convenience. For example:
class ProductData implements Parcelable {
protected String name;
protected String someOtherData;
public static final Parcelable.Creator<ProductData> CREATOR = new Parcelable.Creator<ProductData>() {
#Override
public ProductData createFromParcel(Parcel source) {
return new ProductData(source);
}
#Override
public ProductData[] newArray(int size) {
return new ProductData[size];
}
};
public ProductData(){
}
public ProductData(Parcel source){
readFromParcel(source);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(someOtherData);
}
public void readFromParcel(Parcel source){
name = source.readString();
someOtherData = source.readString();
}
// Here goes the rest of your model code
}
Then you can easily pass the object to another Activity using an Intent:
intent.putExtra("product", productData);
and later get the data using
ProductData productData = intent.getParcelableExtra("product");

Dynamically name objects based on EditText input?

I am creating a finance Android app that will open up and ask the user to add an account. (This will always be static on the page.) On the Main activity, it will have an EditText box next to a Button ("Add Account"). When the Button is pressed, I want a new Object created and it will then be stored into an ArrayList. The List of accounts (as they are added) will then be looped below (with corresponding dynamic buttons to edit the account). This is my practice/unfinished code. It is very raw at this point!
String accountName = (Whatever is in EditText Box)
ArrayList<Accounts> accountList = new ArrayList<Accounts>();
int accountListSize = accountList.size();
(Button on Click) {
Account{accountName} = new Account(); // Not sure how to dynamically name
accountList.add({accountName}) // Not sure how to dynamically name
}
// iterate through finance loop
for(int i = 0; i < accountList .size(); i++)
{
// do stuff - Create Dynamicly Edit and Clear Buttons for each account
}
One of the big issues I am trying to overcome is how to name an Object Dynamically?
Am I over-thinking this process overall and making it harder than it should be? I am going to create a class to handle the account specifics. I eventually have to keep the data stored--so maybe should I scrap the Object orientated style and use SQLite? Shared-preferences?
Any code samples would be great, but I am mostly hoping to find the recommend method I should take.
I would recommend to create an Account object that takes the name in the constructor. For example:
public class Account {
private String name;
public Account( String name ) {
this.name = name;
}
// ... other account related methods here...
public String getName() {
return name;
}
}
Then in your code above:
List<Account> accountList = new ArrayList<Account>();
(Button on Click) {
Account anAccount = new Account( accountName ); // accountName taken from text box.
accountList.add( anAccount );
}
Then to loop through the account list:
for( Account account : accountList ) {
String name = account.getName();
// .. do whatever you need to for each account...
}
Once you have this list of Account objects, you can do anything you need to do with them, such as storing in SQLite DB for later, etc...
Hope this helps...

How can i improve my app

I have an app which present some beaches to the users.there is a list view with the name of every beach and when the user press on a name it opens a new activity with a photo and some text.i have created a .java class for every beach( same copy-paste code ) and a common .xml file. is there any better way to do it?for example to have all the beaches and their text in a db?
why don't you just instance the same class but with different parameters in the constructor?
Something like this:
public class Beach{
protected String name;
protected String pathImage;
public Beach(String name, String pathImage){
this.name = name;
this.pathImage = pathImage;
}
}
//Somewhere else in your application...
Beach beach1 = new Beach("Cancun","/images/cancun.png");
Beach beach2 = new Beach("Miami","/images/miami.png");
I would store the beach information in a SQLlite database, then just create a single Beach view that knows how to display the information from the database. A problem with this is that you might want to build a simple tool to allow you to manage the information in the database so you don't have to do it through queries on the command line.
You could ofcourse create a (abstract) superclass Beach.java and let other beaches extend that class. That way, you've got less redundant code.
public abstract class Beach{
protected String name;
public Beach(String name){
this.name = name;
}
public abstract String getOtherInfo();
}
public class FirstBeach extends Beach{
public FirstBeach(){
super("FirstBeach");
}
public String getOtherInfo(){
return "someInfo";
}
}

Categories

Resources