I have an Android app which uses tabs and fragments for navigation. The app works fine when launched, but after I change the orientation the menu items and the widgets in the fragments stop working. The app works if I put
android:configChanges="orientation|screenSize"
in the manifest, but in the Android documentation it says that this should be a last resort, so I'm wondering if there is a better solution. Here's the code for the host activity and one of the fragments.
package com.mynews;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
//stopService(new Intent(this, FindArticlesService.class));
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar.newTab()
.setText("Articles")
.setTabListener(new TabListener<Articles>(this, "articles", Articles.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Websites")
.setTabListener(new TabListener<UserSites>(this, "websites", UserSites.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Add a website")
.setTabListener(new TabListener<AddSites>(this, "add a site", AddSites.class));
actionBar.addTab(tab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
////Intent intent = new Intent(this, FindArticlesService.class);
//this.startService(intent);
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
Fragment fragment;
final Activity activity;
final String tag;
final Class<T> mClass;
public TabListener(Activity a, String s, Class<T> c){
activity = a;
tag = s;
mClass = c;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment == null){
fragment = Fragment.instantiate(activity, mClass.getName());
ft.add(android.R.id.content, fragment, tag);
}else{
ft.attach(fragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment != null){
ft.detach(fragment);
}
activity.closeContextMenu();
}
}
}
My Fragment Class
package com.mynews;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddSites extends Fragment {
public AddSites(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_add_sites);
// Show the Up button in the action bar.
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.add);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
UserSitesFunc usf = new UserSitesFunc(); //create a new UserSitesFunc to hold
try{ //the list of sites
FileInputStream fis = getActivity().openFileInput("MySites.ser");//check if there's a file
ObjectInputStream ois = new ObjectInputStream(fis);//with a USF object
usf = (UserSitesFunc) ois.readObject(); //if there is, deserialize it and use it
ois.close();//instead of a brand new object
}catch(IOException e){ //catch various exceptions
e.printStackTrace();
}catch(Exception ep){
ep.printStackTrace();
}finally{
try{ //do this with either the new object or the deserialised one
EditText website = (EditText) getActivity().findViewById(R.id.editText1);//get the input
EditText keywords = (EditText) getActivity().findViewById(R.id.editText2);//from the user
String web = website.getText().toString(); //store it in strings
String key = keywords.getText().toString();
String[] kwords = key.split(", ");
ArrayList<String> newKeywords = new ArrayList<String>();
for(String s:kwords){
newKeywords.add(s);
}
Sites s = new Sites(web, newKeywords);//create a new site from the input
if(usf.siteList.contains(s)){
showContainedDialog();
return;
}
usf.addSite(s);//add it to the user's list of sites
FileOutputStream fs = getActivity().openFileOutput("MySites.ser", Context.MODE_PRIVATE);//save it
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(usf);
oos.close();
Toast.makeText(getActivity(), web + " added to Tracked Websites", Toast.LENGTH_LONG).show();
website.setText("");
keywords.setText("");
}catch(MalformedURLException mue){
showDialog();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.activity_add_sites, container, false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.add_sites, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
return true;
}
return super.onOptionsItemSelected(item);
}
public static class NotAWebsiteDialog extends DialogFragment {
public static NotAWebsiteDialog newInstance(){
NotAWebsiteDialog notAWebsite = new NotAWebsiteDialog();
Bundle args = new Bundle();
notAWebsite.setArguments(args);
return notAWebsite;
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// TODO Auto-generated method stub
return new AlertDialog.Builder(getActivity())
.setMessage("Please enter a vaild web address")
.create();
}
}
public void showDialog(){
DialogFragment dialog = NotAWebsiteDialog.newInstance();
dialog.show(getFragmentManager(), "Not A Website");
}
public static class AlreadyContainsWebsiteDialog extends DialogFragment {
public static AlreadyContainsWebsiteDialog newInstance(){
AlreadyContainsWebsiteDialog containsAWebsite = new AlreadyContainsWebsiteDialog();
Bundle args = new Bundle();
containsAWebsite.setArguments(args);
return containsAWebsite;
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// TODO Auto-generated method stub
return new AlertDialog.Builder(getActivity())
.setMessage("This website is already being tracked")
.create();
}
}
public void showContainedDialog(){
DialogFragment dialog = AlreadyContainsWebsiteDialog.newInstance();
dialog.show(getFragmentManager(), "Contains this Website");
}
}
Kudos for not taking the easy way... keep up your programming efforts!
Refer to my answer here regarding the use of Menus and their host Fragments.
Related
i am trying to show some buttons in actionbar but they just dont show up
i have successfully implemented the navigation drawer and viewpager using fragments
the implementes for showing menu inflator and action bar buttons has also been done but they just wont show up
in menu/main.xml i have added app:showAsAction="always" but still it wont show up
here is the
detailactivity.java
package com.test.app;
import java.lang.reflect.Field;
import android.app.ActionBar;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
//import android.support.v7.app.ActionBar;
import com.Blog.gkgyan.parser.RSSFeed;
//public class DetailActivity extends FragmentActivity implements OnItemClickListener{
public class DetailActivity extends FragmentActivity implements OnItemClickListener{
RSSFeed feed;
int pos;
private DescAdapter adapter;
private ViewPager pager;
private DrawerLayout drawerLayout;
private ListView listView;
private String[] planets;
private ActionBarDrawerToggle drawerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
//Drawer Layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout,R.drawable.ic_drawer,R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
//super.onDrawerClosed(drawerView);
Toast.makeText(DetailActivity.this, "Drawer closed", Toast.LENGTH_LONG).show();
}
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
//super.onDrawerOpened(drawerView);
Toast.makeText(DetailActivity.this, "Drawer opened", Toast.LENGTH_LONG).show();
}
};
drawerLayout.setDrawerListener(drawerListener);
//getSupportActionBar().setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);;
getActionBar().setDisplayHomeAsUpEnabled(true);
// try {
// ViewConfiguration config = ViewConfiguration.get(this);
// Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
// if (menuKeyField != null) {
// menuKeyField.setAccessible(true);
// menuKeyField.setBoolean(config, false);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) { e.printStackTrace(); }
}
listView = (ListView) findViewById(R.id.drawerlist);
planets = getResources().getStringArray(R.array.planets);
listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, planets ));
listView.setOnItemClickListener(this);
// Get the feed object and the position from the Intent
feed = (RSSFeed) getIntent().getExtras().get("feed");
pos = getIntent().getExtras().getInt("pos");
// Initialize the views
adapter = new DescAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
// Set Adapter to pager:
pager.setAdapter(adapter);
pager.setCurrentItem(pos);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
//return super.onCreateOptionsMenu(menu);
}
//#Override
//public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (drawerListener.onOptionsItemSelected(item)) {
return true;
}
Intent i = null;
switch (item.getItemId()) {
case R.id.action_rate:
String webpage = "http://developer.android.com/index.html";
i = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(i);
//return true;
break;
case R.id.action_share:
i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "Hello from Hansel and Petal!");
i.setType("text/plain");
startActivity(i);
//return true;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
drawerListener.syncState();
}
public class DescAdapter extends FragmentStatePagerAdapter {
public DescAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return feed.getItemCount();
}
#Override
public Fragment getItem(int position) {
DetailFragment frag = new DetailFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
bundle.putInt("pos", position);
frag.setArguments(bundle);
return frag;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
if (position == 0) {
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
}
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
`
and menu/main.xml
<menu 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"
tools:context="com.Blog.gkgyan.MainActivity" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never"/>
<item
android:id="#+id/action_share"
android:icon="#drawable/ic_action_share"
android:orderInCategory="101"
android:title="#string/action_share"
app:showAsAction="always" />
<item
android:id="#+id/action_rate"
android:icon="#drawable/ic_action_important"
android:orderInCategory="101"
android:title="#string/action_rate"
app:showAsAction="always"/>
</menu>
i wan to show the action_share and Action_rate butons in action bar on detailactivity.java tried every thing nothing works on this page
however it does work perfectly fine in main activity.java
here is the code
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Intent intent = null;
switch (item.getItemId()) {
case R.id.action_rate:
String webpage = "http://developer.android.com/index.html";
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent);
break;
case R.id.action_share:
intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello from Hansel and Petal!");
intent.setType("text/plain");
startActivity(intent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void latestActivity(View v){
//Intent intent = new Intent(this, SplashActivity.class);
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
is it a issue with fragment activity or navigation drawer any help would be great please mention where is should make changes in my code
Edited code after following this link ...Set wallpaper from ViewPager .I developed simple viewpager app along with the background music. However, I want to modify my app so that image chosen by user will give them option to set as wallpaper....I don't want to implement any buttons in my app. User should be able to just touch the image , which will give them option to set as wallpaper...
I am getting error at this code curruntPosition=arg0;. It says "Current position cannot be resolve to a variable". I don't know what it mean ...
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
//Here you can set the wallpaper
curruntPosition=arg0;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
oursong = null;
}
}
imageadapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
I just start with programming, so please give some explanations, or it will be great if you provide some codes .
First add this Permission to the Manifest
<uses-permission android:name="android.permission.SET_WALLPAPER">
Now for some code.
imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Explantion : This will set that the Image will be clickable , when the image is clicked it will set the phone Wallpaper with the selected drawable.
getApplicationContext()
is the Context from the Activity.
This changes will take place inside the Adapter.
Activity
add this variable
int currentPosition;
I have made an app recently and I added a count down timer one day and made a few changes here and there and now when I run the app on my (actual) Galaxy Note 3 it crashes as soon as I hit the Play button below are my LevelOne.java file and my MainActivity.Java file. By the way the logcat shows nothing as if it doesn't realize it crashed.
LevelOne.java
package com.parker.orangedot;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class LevelOne extends ActionBarActivity {
Button myButton;
LevelOne context;
CountDownTimer timer = new CountDownTimer(1500, 1500)
{
#Override
public void onFinish() {
Intent intent = new Intent(context, Scores.class);
startActivity(intent);
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_level_one);
//ass soon as this activity is created, I start my timer.
timer.start();
myButton = (Button) findViewById(R.id.button2);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
timer.cancel();
}});
}
#Override
public void onBackPressed() {
}
public void next(View view) {
// Do something in response to button
Intent intent = new Intent(this, LevelTwo.class);
startActivity(intent);
}
public void openScores(View view) {
// Do something in response to button
Intent intent = new Intent(this, Scores.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.level_one, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_level_one,
container, false);
return rootView;
}
}
}
MainActivity.java
package com.parker.orangedot;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void openScores(View view) {
// Do something in response to button
Intent intent = new Intent(this, Scores.class);
startActivity(intent);
}
public void play(View view) {
// Do something in response to button
Intent intent = new Intent(this, LevelOne.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
UPDATE:
When using the emulater for the Galaxy Nexus, pressing "play" does absolutely nothing.
I am working in Eclipse and struggling with a certain step in my assignment so any help would be appriciated because I actually dont know how to do it even though I realise how glaringly simple it probably is...
I have a shopping app and I have created my CheckoutActivity... now... it needs to start when the user clicks the checkout button in my CartActivity.
I need to add code in the ocCreate method of my CartActivity (which I will provide below) that specifies the listener for the Checkout button. then I need to define a button variable named btn inside the onCreate. I then need to assign the button element from the view using the id that you specified in my activity_cart.xml layout.
All I have so far is this... and I have no idea what to do...
btn.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
//I cant figure out how to get it to start the CheckoutActivity
}
});
Just in case you need to see the code I have so far... here is the code I have for my cartActivty
package uk.ac.uk.st265.shopper;
import java.text.DecimalFormat;
import java.util.List;
import java.util.ResourceBundle.Control;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class CartActivity extends Activity {
CartListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
TextView text = (TextView) findViewById(R.id.total_price); // its not in
// XML
DecimalFormat df = new DecimalFormat("#.00");
text.setText("£"
+ df.format(((ShopperApp) getApplication()).getCartTotal()));
adapter = new CartListAdapter(this);
ListView cartList = (ListView) findViewById(R.id.cart_list);
adapter.setItemList(((ShopperApp) getApplication()).cart);
cartList.setAdapter(adapter);
// Show the Up button in the action bar.
setupActionBar();
//work5ass2part6
//btn.setOnClickListener(new OnClickListener() {
//public void onClick(final View v) {
// I cant figure out how to get it to start the CheckoutActivity
//}
//});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cart, menu);
return true;
}
public class CartListAdapter extends BaseAdapter {
private final Context context;
private List<Product> itemList;
public CartListAdapter(Context c) {
context = c;
}
public void setItemList(List<Product> itemList) {
// this.itemList = itemList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View cell = convertView;
if (cell == null) {
// get layout from mobile xml
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
cell = inflater.inflate(R.layout.adapter_cart, parent, false);
}
Product p = itemList.get(position);
// set value into text view according to position
TextView textView = (TextView) cell
.findViewById(R.id.product_title);
textView.setText(p.getProductName());
textView = (TextView) cell.findViewById(R.id.product_info);
textView.setText("Price " + p.getPrice());
// set value into image view according to position
ImageView imgView = (ImageView) cell
.findViewById(R.id.product_image);
// clear the image
imgView.setImageDrawable(null);
// and load from the network
p.loadImage(imgView, 54, 54);
return cell;
}
public List<Product> getItemList() {
return itemList;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
case R.id.show_cart:
// Create the intent for the cart activity
Intent intent = new Intent(getApplicationContext(),
CartActivity.class);
startActivity(intent);
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here is the code I have so far on my CheckoutActivity:
package uk.ac.uk.st265.shopper;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class CheckoutActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.checkout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
// myIntent.putExtra("key", value); //if you want to pass parameter
CurrentActivity.this.startActivity(myIntent);
MainActivity
public class MainActivity extends FragmentActivity implements ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
public final static String EXTRA_MESSAGE = "com.example.deltaskype.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(
actionBar.getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
new String[] {
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}),
this);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
getActionBar().getSelectedNavigationIndex());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
return true;
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
DisplayMessageActivity
package com.example.deltaskype;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
Socket socket = null;
try {
socket = new Socket("X.X.X.X", 13134);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream out = null;
try {
out = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter output = new PrintWriter(out);
output.println("<request><auth><user>X</user><password>X</password></auth><action><name>makeCall</name><data><dialnum>"+message+"</dialnum></data></action></request>\n");
output.flush();
output.close();
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is used to call to a deskphone, but it executes the call multiple times,
A response of OK is given if the call is made for the first time, any ideas why it makes a call multiple times (i.e. pick up the call and put it down and it rings again!)