How to set image as wall paper in viewpager app? - java

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;

Related

App is crashed after adding switch case in gridview

I got the problem when I tried to add switch case in custom page adapter. I can toast if one item of gridview is clicked. But when I tried to add new activity with onClick, app is crashed. I want to show new activity if gridview item is clicked. I've searched and studied regarding this problem, but I can't find solution.I think my problem is related to switch case. I am learning android. Please help me.
CustomAdapter.java
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] osNameList, int[] osImages) {
// TODO Auto-generated constructor stub
result=osNameList;
context=mainActivity;
imageId=osImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView os_text;
ImageView os_img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.sample_gridlayout, null);
holder.os_text =(TextView) rowView.findViewById(R.id.os_texts);
holder.os_img =(ImageView) rowView.findViewById(R.id.os_images);
holder.os_text.setText(result[position]);
holder.os_img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
switch(position){
case 0:
Intent a = new Intent(v.getContext(), FirstActivity.class);
v.getContext().startActivity(a);
break;
case 1:
Intent b = new Intent(v.getContext(), DefaultActivity.class);
v.getContext().startActivity(b);
break;
}
} });
return rowView;
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
public class MainActivity extends Activity {
GridView gridview;
public static String[] osNameList = {
"Android",
"iOS",
"Linux",
};
public static int[] osImages = {
R.drawable.alpha,
R.drawable.beta,
R.drawable.cupcake,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.customgrid);
gridview.setAdapter(new CustomAdapter(this, osNameList, osImages));
}
}
This is not the way to set OnItemClick Listener. If you want to set click on whole item you should use OnItemClickListener. Remove the OnClickListener from getView() and use OnItemClickListener as follows.
GridView gridview = (GridView) findViewById(R.id.customgrid);
gridview.setAdapter(new CustomAdapter(this, osNameList, osImages));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent a = new Intent(v.getContext(), FirstActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(v.getContext(), DefaultActivity.class);
startActivity(b);
break;
default:
break;
}
} });
NOTE:- There is no need of switch inside OnClickListener which is inside getView() because its only going to call for one position at a time.

.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details

I am new to Android. I started a new Project and implemented a Intro Navigation and App Drawer Screens. When I published "APK", intro sliders are working fine and "Side Bar Menu" app drawer is not working and app crashes,.
Gradle console has a warning message:
Note:
E:\AndroidApps\GoTogether\app\src\main\java\com\softvision\gotogether\app\WelcomeActivity.java
uses or overrides a deprecated API. Note: Recompile with
-Xlint:deprecation for details.
How to Recompile with -Xlint:deprecation in Android Studio?
Here's my code:
package com.softvision.gotogether.app;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Created by Shreekumar S [shreekumar.s#softvision.com] on 20-11-2017.
*/
public class WelcomeActivity extends AppCompatActivity {
private PreferenceManager _preferences;
private ViewPager _viewPager;
private LinearLayout _linearDotsLayout;
private Button _btnSkip, _btnNext;
private int[] _slideLayouts;
private TextView[] _textViewDots;
private WelcomeViewPagerAdapter _welcomeViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
_preferences = new PreferenceManager(this);
if (!_preferences.IsFirstTimeLaunch()) {
LaunchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.activity_welcome);
// get controls of Welcome screen
_viewPager = (ViewPager)findViewById(R.id.welcomeViewPager);
_linearDotsLayout = (LinearLayout) findViewById(R.id.welcomeLinearLayout);
_btnSkip = (Button) findViewById(R.id.btnSkip);
_btnNext = (Button) findViewById(R.id.btnNext);
// layouts of all welcome sliders
// add few more layouts if you want
_slideLayouts = new int[]{
R.layout.intro_slide_1,
R.layout.intro_slide_2,
R.layout.intro_slide_3,
R.layout.intro_slide_4};
// adding bottom dots
AddBottomDots(0);
// making notification bar transparent
ChangeStatusBarColor();
_welcomeViewPagerAdapter = new WelcomeViewPagerAdapter();
_viewPager.setAdapter(_welcomeViewPagerAdapter);
_viewPager.addOnPageChangeListener(onPageChangeListener);
// On Skip button Click
_btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LaunchHomeScreen();
}
});
// On Next button Click
_btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = GetItem(+1);
if (current < _slideLayouts.length) {
// move to next screen
_viewPager.setCurrentItem(current);
} else {
LaunchHomeScreen();
}
}
});
}
private void LaunchHomeScreen() {
_preferences.SetFirstTimeLaunch(false);
// Move from Welcome Activity to Main Activity
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
private void AddBottomDots(int currentPage) {
_textViewDots = new TextView[_slideLayouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
_linearDotsLayout.removeAllViews();
for (int i = 0; i < _textViewDots.length; i++) {
_textViewDots[i] = new TextView(this);
_textViewDots[i].setText(Html.fromHtml("•"));
_textViewDots[i].setTextSize(35);
_textViewDots[i].setTextColor(colorsInactive[currentPage]);
_linearDotsLayout.addView(_textViewDots[i]);
}
if (_textViewDots.length > 0)
_textViewDots[currentPage].setTextColor(colorsActive[currentPage]);
}
// Making notification bar transparent
private void ChangeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
private int GetItem(int i) {
return _viewPager.getCurrentItem() + i;
}
// View pager adapter
public class WelcomeViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public WelcomeViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(_slideLayouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return _slideLayouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
// ViewPager change listener
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
AddBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == _slideLayouts.length - 1) {
// last page. make button text to GOT IT
_btnNext.setText(getString(R.string.start));
_btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
_btnNext.setText(getString(R.string.next));
_btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
}
Html.fromHtml("•") //It is deprecated.
Refrance: https://developer.android.com/reference/android/text/Html#fromHtml(java.lang.String)
Solution:
HtmlCompat.fromHtml("•", HtmlCompat.FROM_HTML_MODE_LEGACY);

Is it possible to share the image located in drawable folder on social platform in viewpager ? (One user says he is not sure, How about you )

I have created viewpager app that is suppose to display images located in the drawable folder. I read android official guide and changed my code ,but it is not working for me. Any help will be appreciated....The user should be able to share the image located in drawable folder ..they like on various platforms according to the app downloaded in their phones.. My question is it possible ?. If yes, please..please.. provide some code..
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.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#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 = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
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();
}
}
imageadapter.java
import java.io.IOException;
import android.app.WallpaperManager;
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 final 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, final 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]);
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();
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
I am new to android programming so..please provide some explanation along with the code..if possible..thanks..
The user should be able to share the image they like on various
platforms according to the app downloaded in their phones
Yes, of course it is possible.
You have to use Intents to do that. I am not sure if one can send the images from the drawable folder, never tried that. However, if you want to let people share the images from the gallery or something:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri uri = Uri.parse(pathToImage);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent),"Share Via...")
What this is doing is that it is representing the intention of your application that it wants to send an image.

Button and menus stop working after orientation change

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.

Getting checkout button to navigate to checkout page

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);

Categories