<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.chapter01.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sup doge" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
package com.example.chapter01; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical" tools:context="com.example.chapter02.FindBeerActivity" > <Spinner android:id="@+id/color" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_gravity="center" android:layout_margin="16dp" android:entries="@array/beer_colors" /> <Button android:id="@+id/find_beer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="16dp" android:text="@string/find_beer" android:onClick="onClickFindBeer" /> <TextView android:id="@+id/brands" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="16dp" android:text="@string/brands" /> </LinearLayout>
<resources> <string name="app_name">Beer Adviser</string> <string name="find_beer">Find Beer!</string> <string name="brands">No beers selected</string> <string-array name="beer_colors"> <item>light</item> <item>amber</item> <item>brown</item> <item>dark</item> </string-array> </resources>
package com.example.chapter02; import java.util.ArrayList; import java.util.List; /** * Created by davidg on 28/04/2017. */ public class BeerExpert { List<String> getBrands(String color) { List<String> brands = new ArrayList<>(); if (color.equals("amber")) { brands.add("Jack Amber"); brands.add("Red Moose"); } else { brands.add("Jail Pale Ale"); brands.add("Gout Stout"); } return brands; } }
package com.example.chapter02; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Spinner; import android.widget.TextView; import java.util.List; public class FindBeerActivity extends Activity { private BeerExpert expert = new BeerExpert(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_find_beer); } //Call when the button gets clicked public void onClickFindBeer(View view) { //Get a reference to the TextView TextView brands = (TextView) findViewById(R.id.brands); //Get a reference to the Spinner Spinner color = (Spinner) findViewById(R.id.color); //Get the selected item in the Spinner String beerType = String.valueOf(color.getSelectedItem()); //Get recommendations from the BeerExpert class List<String> brandsList = expert.getBrands(beerType); StringBuilder brandsFormatted = new StringBuilder(); for (String brand : brandsList) { brandsFormatted.append(brand).append('\n'); } //Display the beers brands.setText(brandsFormatted); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical" tools:context=".CreateMessageActivity" > <EditText android:id="@+id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:hint="@string/hint" android:ems="10" /> <Button android:id="@+id/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:onClick="onSendMessage" android:text="@string/send" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical" tools:context=".ReceiveMessageActivity" > <TextView android:id="@+id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
<resources> <string name="app_name">My Messenger</string> <string name="send">Send Message</string> <string name="hint">Enter a message</string> <string name="chooser">Send message via...</string> </resources>
package com.example.chapter03; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class CreateMessageActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_message); } //Call onSendMessage() when the button is clicked public void onSendMessage(View view) { EditText messageView = (EditText)findViewById(R.id.message); String messageText = messageView.getText().toString(); Intent intent = new Intent(this, ReceiveMessageActivity.class); // intent.setType("text/plain"); // intent.putExtra(Intent.EXTRA_TEXT, messageText); // String chooserTitle = getString(R.string.chooser); // Intent chosenIntent = Intent.createChooser(intent, chooserTitle); // startActivity(chosenIntent); intent.putExtra(ReceiveMessageActivity.EXTRA_MESSAGE, messageText); startActivity(intent); } }
package com.example.chapter03; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class ReceiveMessageActivity extends Activity { public static final String EXTRA_MESSAGE = "message"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_receive_message); Intent intent = getIntent(); String messageText = intent.getStringExtra(EXTRA_MESSAGE); TextView messageView = (TextView)findViewById(R.id.message); messageView.setText(messageText); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="30dp" tools:context=".MainActivity" > <TextView android:id="@+id/time_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textAppearance="@android:style/TextAppearance.Large" android:textSize="56sp" /> <Button android:id="@+id/start_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" android:onClick="onClickStart" android:text="@string/start" /> <Button android:id="@+id/stop_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="8dp" android:onClick="onClickStop" android:text="@string/stop" /> <Button android:id="@+id/reset_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="8dp" android:onClick="onClickReset" android:text="@string/reset" /> </LinearLayout>
<resources> <string name="app_name">Chapter04</string> <string name="start">Start</string> <string name="stop">Stop</string> <string name="reset">Reset</string> </resources>
package com.example.chapter04; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.TextView; import java.util.Locale; public class MainActivity extends AppCompatActivity { private int seconds = 0; private boolean running; private boolean wasRunning; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { seconds = savedInstanceState.getInt("seconds"); running = savedInstanceState.getBoolean("running"); wasRunning = savedInstanceState.getBoolean("wasRunning"); } runTimer(); }//this gets called before the activity gets destroyed @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putInt("seconds", seconds); savedInstanceState.putBoolean("running", running); savedInstanceState.putBoolean("wasRunning", wasRunning); } //the timer should resume running. @Override protected void onResume() { super.onResume(); if (wasRunning) { running = true; Log.d("onResume:","onResume is called"); } } @Override protected void onPause() { super.onPause(); wasRunning = running; running = false; Log.d("onPause:","onPause is called"); } //Start the stopwatch running when the Start button is clicked. public void onClickStart(View view) { running = true; } //Stop the stopwatch running when the Stop button is clicked. public void onClickStop(View view) { running = false; } //Reset the stopwatch when the Reset button is clicked. public void onClickReset(View view) { running = false; seconds = 0; } //Sets the number of seconds on the timer. private void runTimer() { final TextView timeView = (TextView)findViewById(R.id.time_view); final Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { int hours = seconds/3600; int minutes = (seconds%3600)/60; int secs = seconds%60; String time = String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, secs); timeView.setText(time); //running default is false if (running) { seconds++; } handler.postDelayed(this, 1000); } }); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical" tools:context=".MainActivity" > <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/to" /> <EditText android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="top" android:hint="@string/message" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end" android:text="@string/send" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".MainActivity" > <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="centerCrop" android:src="@drawable/duck" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_gravity="bottom|end" android:gravity="end" android:padding="16dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:text="It's a duck!" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:text="(not a real one)" /> </LinearLayout> </FrameLayout>
<resources> <string name="app_name">Chapter05</string> <string name="to">To</string> <string name="message">Message</string> <string name="send">Send</string> </resources>
package com.example.chapter05; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //setContentView(R.layout.duck_layout); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".DrinkCategoryActivity" > <ListView android:id="@+id/list_drinks" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.hfad.starbuzz.DrinkActivity" > <ImageView android:id="@+id/photo" android:layout_width="190dp" android:layout_height="190dp" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".TopLevelActivity" > <ImageView android:layout_width="200dp" android:layout_height="100dp" android:src="@drawable/starbuzz_logo" android:contentDescription="@string/starbuzz_logo" /> <ListView android:id="@+id/list_options" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/options" /> </LinearLayout>
<resources> <string name="app_name">Chapter07</string> <string name="starbuzz_logo">Starbuzz logo</string> <string-array name="options"> <item>Drinks</item> <item>Food</item> <item>Stores</item> </string-array> </resources>
package com.example.chapter07; /** * Created by davidg on 30/04/2017. */ public class Drink { private String name; private String description; private int imageResourceId; //drinks is an array of Drinks public static final Drink[] drinks = { new Drink("Latte", "A couple of espresso shots with steamed milk", R.drawable.latte), new Drink("Cappuccino", "Espresso, hot milk, and a steamed milk foam", R.drawable.cappuccino), new Drink("Filter", "Highest quality beans roasted and brewed fresh", R.drawable.filter) }; //Each Drink has a name, description, and an image resource private Drink(String name, String description, int imageResourceId) { this.name = name; this.description = description; this.imageResourceId = imageResourceId; } public String getDescription() { return description; } public String getName() { return name; } public int getImageResourceId() { return imageResourceId; } public String toString() { return this.name; } }
package com.example.chapter07; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.os.Bundle; public class DrinkActivity extends AppCompatActivity { public static final String EXTRA_DRINKID = "drinkId"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink); //Get the drink from the intent int drinkId = (Integer)getIntent().getExtras().get(EXTRA_DRINKID); Drink drink = Drink.drinks[drinkId]; //Populate the drink name TextView name = (TextView)findViewById(R.id.name); name.setText(drink.getName()); //Populate the drink description TextView description = (TextView)findViewById(R.id.description); description.setText(drink.getDescription()); //Populate the drink image ImageView photo = (ImageView)findViewById(R.id.photo); photo.setImageResource(drink.getImageResourceId()); photo.setContentDescription(drink.getName()); } }
package com.example.chapter07; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.os.Bundle; public class DrinkCategoryActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink_category); ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>( this, android.R.layout.simple_list_item_1, Drink.drinks); ListView listDrinks = (ListView) findViewById(R.id.list_drinks); listDrinks.setAdapter(listAdapter); //Create the listener AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> listDrinks, View itemView, int position, long id) { //Pass the drink the user clicks on to DrinkActivity Intent intent = new Intent(DrinkCategoryActivity.this, DrinkActivity.class); intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) id); startActivity(intent); } }; //Assign the listener to the list view listDrinks.setOnItemClickListener(itemClickListener); } }
package com.example.chapter07; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; public class TopLevelActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_top_level); //Create an OnItemClickListener AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> listView, View itemView, int position, long id) { if (position == 0) { Intent intent = new Intent(TopLevelActivity.this, DrinkCategoryActivity.class); startActivity(intent); } } }; //Add the listener to the list view ListView listView = (ListView) findViewById(R.id.list_options); listView.setOnItemClickListener(itemClickListener); } }
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.ActionBar" > <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_scrollFlags="scroll|enterAlways" /> <com.google.android.material.tabs.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.appbar.AppBarLayout> <androidx.viewpager.widget.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?> <androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".TopFragment" > <!--We’re using a FrameLayout because we want to position the text on top of the image--> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/info_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="centerCrop" android:src="@drawable/restaurant" android:contentDescription="@string/restaurant_image" /> <!--We’re using a LinearLayout to contain the text. We’re giving it a white background, and the margins will add space around the edges--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:padding="16dp" android:background="#FFFFFF" android:orientation="vertical" > <TextView android:textSize="32sp" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/company_name" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/home_text" /> </LinearLayout> </FrameLayout> </androidx.core.widget.NestedScrollView>
<resources> <string name="app_name">Bits and Pizzas</string> <string name="create_order">Create Order</string> <string name="create_order_title">Create Order</string> <string name="action_share">Share</string> <string name="title_top">Top fragment</string> <string-array name="pizzas"> <item>Diavolo</item> <item>Funghi</item> </string-array> <string-array name="pasta"> <item>Spaghetti Bolognese</item> <item>Lasagne</item> </string-array> <string-array name="stores"> <item>Cambridge</item> <item>Sebastopol</item> </string-array> <string name="home_tab">Home</string> <string name="pizza_tab">Pizzas</string> <string name="pasta_tab">Pasta</string> <string name="store_tab">Stores</string> <string name="company_name">Bits and Pizzas</string> <string name="restaurant_image">Restaurant image</string> <string name="home_text">Since we opened our doors in 2017, Bits and Pizzas has built its reputation as one of America’s best Italian-Digital restaurants. Some people believe eating out is about being with your friends and family. We believe that good food is best enjoyed while staring at your phone.</string> <string name="order_name_hint">Please enter your name</string> <string name="order_details_hint">Please enter your order</string> <!-- TODO: Remove or change this placeholder text --> <string name="hello_blank_fragment">Hello blank fragment</string> </resources>
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
package com.example.chapter12; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.ShareActionProvider; import androidx.appcompat.widget.Toolbar; import androidx.core.view.MenuItemCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; public class MainActivity extends AppCompatActivity { private ShareActionProvider shareActionProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Attach the SectionsPagerAdapter to the ViewPager SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); ViewPager pager = (ViewPager) findViewById(R.id.pager); //Attach the FragmentPagerAdapter to the ViewPager. pager.setAdapter(pagerAdapter); //Attach the ViewPager to the TabLayout TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); //This links the ViewPager to the TabLayout. tabLayout.setupWithViewPager(pager); } /* @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the app bar. getMenuInflater().inflate(R.menu.menu_main, menu); MenuItem menuItem = menu.findItem(R.id.action_share); shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem); setShareActionIntent("Want to join me for pizza?"); return super.onCreateOptionsMenu(menu); }*/ private void setShareActionIntent(String text) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, text); shareActionProvider.setShareIntent(intent); } // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { //case R.id.action_create_order: // Intent intent = new Intent(this, OrderActivity.class); // startActivity(intent); // return true; // default: // return super.onOptionsItemSelected(item); // } // } //The FragmentPagerAdapter passes information to the ViewPager. private class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override //Say how many pages the ViewPager should contain. public int getCount() { return 4; } @Override //Specify which fragment should appear on each page. public Fragment getItem(int position) { switch (position) { case 0: return new TopFragment(); case 1: return new PizzaFragment(); case 2: return new PastaFragment(); case 3: return new StoresFragment(); } return null; } //This method adds the text to the tabs. @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Home"; case 1: return getResources().getText(R.string.pizza_tab); case 2: return getResources().getText(R.string.pasta_tab); case 3: return getResources().getText(R.string.store_tab); } return null; } } }
package com.example.chapter12; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import androidx.fragment.app.ListFragment; /** * A simple {@link Fragment} subclass. */ public class PastaFragment extends ListFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ArrayAdapter<String> adapter = new ArrayAdapter<>( inflater.getContext(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.pasta)); setListAdapter(adapter); return super.onCreateView(inflater, container, savedInstanceState); } }
package com.example.chapter12; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import androidx.fragment.app.ListFragment; /** * A simple {@link Fragment} subclass. */ public class PizzaFragment extends ListFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ArrayAdapter<String> adapter = new ArrayAdapter<>( inflater.getContext(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.pizzas)); setListAdapter(adapter); return super.onCreateView(inflater, container, savedInstanceState); } }
package com.example.chapter12; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import androidx.fragment.app.ListFragment; /** * A simple {@link Fragment} subclass. */ public class StoresFragment extends ListFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ArrayAdapter<String> adapter = new ArrayAdapter<>( inflater.getContext(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.stores)); setListAdapter(adapter); return super.onCreateView(inflater, container, savedInstanceState); } }
package com.example.chapter12; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link TopFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link TopFragment#newInstance} factory method to * create an instance of this fragment. */ public class TopFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_top, container, false); } }
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="purple_200">#FFBB86FC</color> <color name="purple_500">#FF6200EE</color> <color name="purple_700">#FF3700B3</color> <color name="teal_200">#FF03DAC5</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> </resources>
<resources> <string name="app_name">Chapter14</string> <string name="user_name">spot@catchat.com</string> <string name="nav_inbox">Mesagez</string> <string name="nav_drafts">Draftz</string> <string name="nav_sent">Sent mesagez</string> <string name="nav_trash">In da trash</string> <string name="nav_support">Support</string> <string name="nav_help">Halp</string> <string name="nav_feedback">Giv us feedback</string> <string name="nav_open_drawer">Open navigation drawer</string> <string name="nav_close_drawer">Close navigation drawer</string> <!-- TODO: Remove or change this placeholder text --> <string name="hello_blank_fragment">Hello blank fragment</string> <string name="title_activity_help">HelpActivity</string> <!-- Strings used for fragments for navigation --> <string name="first_fragment_label">First Fragment</string> <string name="second_fragment_label">Second Fragment</string> <string name="next">Next</string> <string name="previous">Previous</string> <string name="hello_first_fragment">Hello first fragment</string> <string name="hello_second_fragment">Hello second fragment. Arg: %1$s</string> <string name="title_activity_feedback">FeedbackActivity</string> </resources>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".FeedbackActivity" > <include layout="@layout/toolbar_main" android:id="@+id/toolbar" /> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Feedback" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".HelpActivity" > <include layout="@layout/toolbar_main" android:id="@+id/toolbar" /> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Help" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <!-- The layout's root element is a DrawerLayout --> <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" > <!-- This is for the drawer’s main content. --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- The activity’s main content is composed of a Toolbar, and a FrameLayout in which we’ll display fragments. --> <include layout="@layout/toolbar_main" android:id="@+id/toolbar" /> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> <!-- The NavigationView defines the drawer’s appearance and much of its behavior. We’re giving it an ID, as we’ll need to refer to it in our activity code --> <!-- We’re using the layout we created earlier as the drawer’s header, and the menu resource file for the list of options --> <com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:headerLayout="@layout/nav_header" app:menu="@menu/menu_nav"/> </androidx.drawerlayout.widget.DrawerLayout>
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".DraftsFragment"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_blank_fragment" /> </FrameLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".InboxFragment" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Inbox" /> </LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".SentItemsFragment" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Sent items" /> </LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".TrashFragment" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="Trash" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="180dp" android:theme="@style/ThemeOverlay.AppCompat.Dark" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="centerCrop" android:src="@drawable/kitten_small" /> <!-- This LinearLayout will appear on top of the ImageView. We're using it to display text at the bottom of the image.--> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" android:gravity="bottom|start" android:layout_margin="16dp"> <!-- This is a built-in style that makes the text look slightly bolder. It comes from the AppCompat Support Library --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/user_name" /> </LinearLayout> </FrameLayout>
<?xml version="1.0" encoding="utf-8"?> <androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<?xml version="1.0" encoding="utf-8"?> <!--Add this group and the four items it contains to your menu resource file so they'll appear in the navigation drawer --> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <!-- This means that a single item in the group will be highlighted (the option the user selects) --> <group android:checkableBehavior="single"> <!-- the first group contains message, draft, sent, and trash --> <!-- Checked = True, highlights the item in the navigation drawer by default --> <!-- This is a built-in drawable you can use to display an email icon --> <item android:id="@+id/nav_inbox" android:icon="@android:drawable/sym_action_email" android:title="@string/nav_inbox" android:checked="true" /> <item android:id="@+id/nav_drafts" android:icon="@android:drawable/ic_menu_edit" android:title="@string/nav_drafts" /> <item android:id="@+id/nav_sent" android:icon="@android:drawable/ic_menu_send" android:title="@string/nav_sent" /> <item android:id="@+id/nav_trash" android:icon="@android:drawable/ic_menu_delete" android:title="@string/nav_trash" /> </group> <item android:title="@string/nav_support"> <menu> <!-- the second group contains help and feedback --> <item android:id="@+id/nav_help" android:icon="@android:drawable/ic_menu_help" android:title="@string/nav_help" /> <item android:id="@+id/nav_feedback" android:icon="@android:drawable/sym_action_email" android:title="@string/nav_feedback" /> </menu> </item> </menu>
package com.example.chapter14; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class DraftsFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_drafts, container, false); } }
package com.example.chapter14; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Bundle; public class FeedbackActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback); //5. Set the toolbar as the activity's app bar, page 313 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } }
package com.example.chapter14; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Bundle; public class HelpActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } }
package com.example.chapter14; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class InboxFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_inbox, container, false); } }
package com.example.chapter14; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import com.google.android.material.navigation.NavigationView; //Implementing this interface means the activity can listen for clicks public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private DrawerLayout drawer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); //setSupportActionBar(toolbar); // Add a drawer toggle with the burger icon DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.nav_open_drawer, R.string.nav_close_drawer); drawer.addDrawerListener(toggle); toggle.syncState(); //Register the activity with the navigation view as a listener. NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); Fragment fragment = new InboxFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); //We are replacing the content_frame from the activity_main.xml to the default fragment (i.e., inbox). ft.add(R.id.content_frame, fragment); ft.commit(); } //This method gets called when the user clicks on one of the items in the drawer @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); Fragment fragment = null; Intent intent = null; switch(id) { case R.id.nav_drafts: fragment = new DraftsFragment(); break; case R.id.nav_sent: fragment = new SentItemsFragment(); break; case R.id.nav_trash: fragment = new TrashFragment(); break; case R.id.nav_help: intent = new Intent(this, HelpActivity.class); break; case R.id.nav_feedback: intent = new Intent(this, FeedbackActivity.class); break; default: fragment = new InboxFragment(); } if (fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); //We are replacing the content_frame from the activity_main.xml to the clicked fragment ft.replace(R.id.content_frame, fragment); ft.commit(); } else { startActivity(intent); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } //This gets called when the Back button gets pressed @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); //If the drawer is currently open, close it. if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { //Otherwise, call up to the superclass onBackPressed() method super.onBackPressed(); } } }
package com.example.chapter14; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SentItemsFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_sent_items, container, false); } }
package com.example.chapter14; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class TrashFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_trash, container, false); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/list_drinks" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/photo" android:layout_width="190dp" android:layout_height="190dp" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:layout_width="200dp" android:layout_height="100dp" android:src="@drawable/starbuzz_logo" android:contentDescription="@string/starbuzz_logo" /> <ListView android:id="@+id/list_options" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/options" /> </LinearLayout>
<resources> <string name="app_name">Chapter15</string> <string name="starbuzz_logo">Starbuzz logo</string> <string-array name="options"> <item>Drinks</item> <item>Food</item> <item>Stores</item> </string-array> </resources>
package com.example.chapter15; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; public class drink_category extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink_category); ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>( this, android.R.layout.simple_list_item_1, Drink.drinks); ListView listDrinks = (ListView) findViewById(R.id.list_drinks); listDrinks.setAdapter(listAdapter); //Create the listener AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> listDrinks, View itemView, int position, long id) { //Pass the drink the user clicks on to DrinkActivity Intent intent = new Intent(drink_category.this, DrinkActivity.class); intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) id); startActivity(intent); } }; //Assign the listener to the list view listDrinks.setOnItemClickListener(itemClickListener); } }
package com.example.chapter15; /** * Created by davidg on 30/04/2017. */ public class Drink { private String name; private String description; private int imageResourceId; //drinks is an array of Drinks public static final com.example.chapter15.Drink[] drinks = { new com.example.chapter15.Drink("Latte", "A couple of espresso shots with steamed milk", R.drawable.latte), new com.example.chapter15.Drink("Cappuccino", "Espresso, hot milk, and a steamed milk foam", R.drawable.cappuccino), new com.example.chapter15.Drink("Filter", "Highest quality beans roasted and brewed fresh", R.drawable.filter) }; //Each Drink has a name, description, and an image resource private Drink(String name, String description, int imageResourceId) { this.name = name; this.description = description; this.imageResourceId = imageResourceId; } public String getDescription() { return description; } public String getName() { return name; } public int getImageResourceId() { return imageResourceId; } public String toString() { return this.name; } }
package com.example.chapter15; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; public class DrinkActivity extends AppCompatActivity { public static final String EXTRA_DRINKID = "drinkId"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink); //Get the drink from the intent int drinkId = (Integer)getIntent().getExtras().get(EXTRA_DRINKID); Drink drink = Drink.drinks[drinkId]; //Populate the drink name TextView name = (TextView)findViewById(R.id.name); name.setText(drink.getName()); //Populate the drink description TextView description = (TextView)findViewById(R.id.description); description.setText(drink.getDescription()); //Populate the drink image ImageView photo = (ImageView)findViewById(R.id.photo); photo.setImageResource(drink.getImageResourceId()); photo.setContentDescription(drink.getName()); } }
package com.example.chapter15; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Create an OnItemClickListener AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> listView, View itemView, int position, long id) { if (position == 0) { Intent intent = new Intent(MainActivity.this, drink_category.class); startActivity(intent); } } }; //Add the listener to the list view ListView listView = (ListView) findViewById(R.id.list_options); listView.setOnItemClickListener(itemClickListener); } }
package com.example.chapter15; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class StarbuzzDatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "starbuzz"; // the name of our database private static final int DB_VERSION = 2; // the version of the database StarbuzzDatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { updateMyDatabase(db, 0, DB_VERSION); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { updateMyDatabase(db, oldVersion, newVersion); } private static void insertDrink(SQLiteDatabase db, String name, String description, int resourceId) { ContentValues drinkValues = new ContentValues(); drinkValues.put("NAME", name); drinkValues.put("DESCRIPTION", description); drinkValues.put("IMAGE_RESOURCE_ID", resourceId); //DrinkValues ("NAME": Latte, "DESCRIPTION": Espresso, "IMAGE_RESOURCE_ID": 53556) db.insert("DRINK", null, drinkValues); } private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 1) { //Just to create our table in the database db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "NAME TEXT, " + "DESCRIPTION TEXT, " + "IMAGE_RESOURCE_ID INTEGER);"); // insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte); insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam", R.drawable.cappuccino); insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter); } if (oldVersion < 2) { db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC;"); } } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/list_drinks" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/photo" android:layout_width="190dp" android:layout_height="190dp" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/favorite" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/favorite" android:onClick="onFavoriteClicked" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:layout_width="200dp" android:layout_height="100dp" android:src="@drawable/starbuzz_logo" android:contentDescription="@string/starbuzz_logo" /> <ListView android:id="@+id/list_options" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/options" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="@string/favorites" /> <ListView android:id="@+id/list_favorites" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
<resources> <string name="app_name">Chapter15</string> <string name="starbuzz_logo">Starbuzz logo</string> <string name="favorite">Favorite</string> <string name="favorites">Your favorite drinks:</string> <string-array name="options"> <item>Drinks</item> <item>Food</item> <item>Stores</item> </string-array> </resources>
package com.example.chapter15; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; public class drink_category extends Activity { private SQLiteDatabase db; private Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink_category); SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this); ListView listDrinks = (ListView) findViewById(R.id.list_drinks); try { db = starbuzzDatabaseHelper.getReadableDatabase(); cursor = db.query("DRINK", new String[]{"_id", "NAME"}, null, null, null, null, null); SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"NAME"}, new int[]{android.R.id.text1}, 0); listDrinks.setAdapter(listAdapter); } catch(SQLiteException e) { Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT); toast.show(); } //Create the listener AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> listDrinks, View itemView, int position, long id) { //Pass the drink the user clicks on to DrinkActivity Intent intent = new Intent(drink_category.this, DrinkActivity.class); intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) id); startActivity(intent); } }; //Assign the listener to the list view listDrinks.setOnItemClickListener(itemClickListener); } @Override public void onDestroy(){ super.onDestroy(); cursor.close(); db.close(); } }
package com.example.chapter15; /** * Created by davidg on 30/04/2017. */ public class Drink { private String name; private String description; private int imageResourceId; //drinks is an array of Drinks public static final com.example.chapter15.Drink[] drinks = { new com.example.chapter15.Drink("Latte", "A couple of espresso shots with steamed milk", R.drawable.latte), new com.example.chapter15.Drink("Cappuccino", "Espresso, hot milk, and a steamed milk foam", R.drawable.cappuccino), new com.example.chapter15.Drink("Filter", "Highest quality beans roasted and brewed fresh", R.drawable.filter) }; //Each Drink has a name, description, and an image resource private Drink(String name, String description, int imageResourceId) { this.name = name; this.description = description; this.imageResourceId = imageResourceId; } public String getDescription() { return description; } public String getName() { return name; } public int getImageResourceId() { return imageResourceId; } public String toString() { return this.name; } }
package com.example.chapter15; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class DrinkActivity extends Activity { public static final String EXTRA_DRINKID = "drinkId"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink); //Get the drink from the intent int drinkId = (Integer)getIntent().getExtras().get(EXTRA_DRINKID); //Create a cursor SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this); try { SQLiteDatabase db = starbuzzDatabaseHelper.getReadableDatabase(); Cursor cursor = db.query ("DRINK", new String[] {"NAME", "DESCRIPTION", "IMAGE_RESOURCE_ID", "FAVORITE"}, "_id = ?", new String[] {Integer.toString(drinkId)}, null, null,null); //Move to the first record in the Cursor if (cursor.moveToFirst()) { //Get the drink details from the cursor String nameText = cursor.getString(0); String descriptionText = cursor.getString(1); int photoId = cursor.getInt(2); boolean isFavorite = (cursor.getInt(3) == 1); //Populate the drink name TextView name = (TextView)findViewById(R.id.name); name.setText(nameText); //Populate the drink description TextView description = (TextView)findViewById(R.id.description); description.setText(descriptionText); //Populate the drink image ImageView photo = (ImageView)findViewById(R.id.photo); photo.setImageResource(photoId); photo.setContentDescription(nameText); //Populate the favorite checkbox CheckBox favorite = (CheckBox)findViewById(R.id.favorite); favorite.setChecked(isFavorite); } } catch(SQLiteException e) { Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT); toast.show(); } } //Update the database when the checkbox is clicked public void onFavoriteClicked(View view){ int drinkId = (Integer) getIntent().getExtras().get(EXTRA_DRINKID); new UpdateDrinkTask().execute(drinkId); } //Inner class to update the drink. private class UpdateDrinkTask extends AsyncTask<Integer, Void, Boolean> { private ContentValues drinkValues; protected void onPreExecute() { CheckBox favorite = (CheckBox) findViewById(R.id.favorite); drinkValues = new ContentValues(); drinkValues.put("FAVORITE", favorite.isChecked()); } protected Boolean doInBackground(Integer... drinks) { int drinkId = drinks[0]; SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(DrinkActivity.this); try { SQLiteDatabase db = starbuzzDatabaseHelper.getWritableDatabase(); db.update("DRINK", drinkValues, "_id = ?", new String[]{Integer.toString(drinkId)}); db.close(); return true; } catch (SQLiteException e) { return false; } } protected void onPostExecute(Boolean success) { if (!success) { Toast toast = Toast.makeText(DrinkActivity.this, "Database unavailable", Toast.LENGTH_SHORT); toast.show(); } } } }
package com.example.chapter15; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.widget.CursorAdapter; import android.widget.SimpleCursorAdapter; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private SQLiteDatabase db; private Cursor favoritesCursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupOptionsListView(); setupFavoritesListView(); } private void setupOptionsListView() { //Create an OnItemClickListener AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> listView, View itemView, int position, long id) { if (position == 0) { Intent intent = new Intent(MainActivity.this, drink_category.class); startActivity(intent); } } }; //Add the listener to the list view ListView listView = (ListView) findViewById(R.id.list_options); listView.setOnItemClickListener(itemClickListener); } private void setupFavoritesListView() { //Populate the list_favorites ListView from a cursor ListView listFavorites = (ListView) findViewById(R.id.list_favorites); try{ SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this); db = starbuzzDatabaseHelper.getReadableDatabase(); favoritesCursor = db.query("DRINK", new String[] { "_id", "NAME"}, "FAVORITE = 1", null, null, null, null); CursorAdapter favoriteAdapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_list_item_1, favoritesCursor, new String[]{"NAME"}, new int[]{android.R.id.text1}, 0); listFavorites.setAdapter(favoriteAdapter); } catch(SQLiteException e) { Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT); toast.show(); } //Navigate to DrinkActivity if a drink is clicked listFavorites.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> listView, View v, int position, long id) { Intent intent = new Intent(MainActivity.this, DrinkActivity.class); intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) id); startActivity(intent); } }); } @Override public void onRestart() { super.onRestart(); Cursor newCursor = db.query("DRINK", new String[] { "_id", "NAME"}, "FAVORITE = 1", null, null, null, null); ListView listFavorites = (ListView) findViewById(R.id.list_favorites); CursorAdapter adapter = (CursorAdapter) listFavorites.getAdapter(); adapter.changeCursor(newCursor); favoritesCursor = newCursor; } //Close the cursor and database in the onDestroy() method @Override public void onDestroy(){ super.onDestroy(); favoritesCursor.close(); db.close(); } }
package com.example.chapter15; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class StarbuzzDatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "starbuzz"; // the name of our database private static final int DB_VERSION = 2; // the version of the database StarbuzzDatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { updateMyDatabase(db, 0, DB_VERSION); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { updateMyDatabase(db, oldVersion, newVersion); } private static void insertDrink(SQLiteDatabase db, String name, String description, int resourceId) { ContentValues drinkValues = new ContentValues(); drinkValues.put("NAME", name); drinkValues.put("DESCRIPTION", description); drinkValues.put("IMAGE_RESOURCE_ID", resourceId); //DrinkValues ("NAME": Latte, "DESCRIPTION": Espresso, "IMAGE_RESOURCE_ID": 53556) db.insert("DRINK", null, drinkValues); } private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 1) { //Just to create our table in the database db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "NAME TEXT, " + "DESCRIPTION TEXT, " + "IMAGE_RESOURCE_ID INTEGER);"); // insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte); insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam", R.drawable.cappuccino); insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter); } if (oldVersion < 2) { db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC;"); } } }