I am getting this error when doing intent. I don't know why it is coming. I need to go to the fragment to activity. I need to go to the next activity with the api in this application. I have tried many times and I am not getting the answer.**Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'**I have given the image below How to do fragment to activity intent i am new android devloper
package com.kannada.newspaper.india.utils;
import static com.kannada.newspaper.india.Constant.EXTRA_OBJC;
import static com.kannada.newspaper.india.Constant.getApiUrl;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.kannada.newspaper.india.AppConfig;
import com.kannada.newspaper.india.Constant;
import com.kannada.newspaper.india.MainActivity;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.ActivityCategoryDetail;
import com.kannada.newspaper.india.adapters.GalleryAdapter;
import com.kannada.newspaper.india.model.Category;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private Call<CallbackHome> callbackCall = null;
SharedPref sharedPref;
private View root_view;
public static final String EXTRA_OBJC = "key.EXTRA_OBJC";
private GalleryAdapter adapterCategory;
private GridView gridView;
private List<Category> mensWears;
private GalleryAdapter adapter;
private Category category;
public FragmentCategory() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
requestAction();
category = (Category) getActivity().getIntent().getSerializableExtra(Constant.EXTRA_OBJC);
// Inflate the layout for this fragment
root_view = inflater.inflate(R.layout.fragment_phones,container,false);
((TextView) root_view.findViewById(R.id.txt_title_category)).setText(getResources().getString(R.string.home_title_category));
return root_view;
}
private void requestAction() {
new Handler().postDelayed(this::requestHomeData, Constant.DELAY_TIME);
}
private void requestHomeData() {
this.callbackCall = RestAdapter.createAPI(getApiUrl).getHome(AppConfig.REST_API_KEY);
this.callbackCall.enqueue(new Callback<CallbackHome>() {
public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
CallbackHome responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
return;
}
displayData(responseHome);
}
public void onFailure(Call<CallbackHome> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
}
}
});
}
private void displayData(CallbackHome responseHome) {
displayCategory(responseHome.category);
}
private void displayCategory(List<Category> list) {
GridView gridView = (GridView) root_view.findViewById(R.id.gridHolder);
adapterCategory = new GalleryAdapter(getActivity(), list);
gridView.setAdapter(adapterCategory);
GalleryAdapter.setOnItemClickListener((v, obj, position) -> {
Intent intent = new Intent(getActivity(), ActivityCategoryDetail.class);
intent.putExtra(EXTRA_OBJC, obj);
startActivity(intent);
});
LinearLayout lyt_category = root_view.findViewById(R.id.lyt_category);
if (list.size() > 0) {
// lyt_category.setVisibility(View.VISIBLE);
} else {
// lyt_category.setVisibility(View.GONE);
}
}
}
GalleryAdapter adapter
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
public static void setOnItemClickListener(Object o) {
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
TextView prdId = view.findViewById(R.id.category_name);
ImageView imageView = view.findViewById(R.id.category_image);
// prdId.setText(prdId.toString());
Picasso.get()
.load(getApiUrl + "/upload/category/" + mensWears.get(i).category_image())
.placeholder(R.drawable.ic_thumbnail)
.into(imageView);
prdId.setText(mensWears.get(i).getItemName());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
You cannot put Object type in putExtra , it has to be either serailized, string, double and other primitive type.
You can do like this:
Category category = (Category)adapter.getItemAtPosition(pos);
or this should also work:
Category category = (Category) obj
then,
intent.putExtra(EXTRA_OBJC,category)
Note: Your Category class should implement parcelable or serilizable to be passed as an intent.
public class Category implements Serializable {
..........}
I am making a flash card app with SwipeCard
This is my FlashCardActivity:
import android.os.Bundle;
import android.text.style.TtsSpan;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.gson.Gson;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.adapter.CardListAdapter;
import org.koreanlab.fabloading.basickit.BasicCompatActivity;
import org.koreanlab.fabloading.basickit.remote.RemoteService;
import org.koreanlab.fabloading.basickit.remote.ServiceGenerator;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FlashCardActivity extends BasicCompatActivity {
private String TAG = getClass().getSimpleName();
private ArrayList<CardItem> cardList;
private ArrayAdapter<String> cardAdapter;
private CardListAdapter cardListAdapter;
private int i;
CardItem newCard;
#BindView(R.id.frame)
SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashcard);
ButterKnife.bind(this);
cardList = new ArrayList<>();
Log.d(TAG, "cardList created");
// get Two Words;
cardList.add(getCardItem());
cardList.add(getCardItem());
Log.d(TAG, "added Card");
cardListAdapter = new CardListAdapter(this, R.layout.card_item, cardList);
Log.d(TAG, "adapter created: " + (cardListAdapter == null ? "cardAdapter is NULL" : "cardAdapter is not NULL"));
flingContainer.setAdapter(cardListAdapter);
Log.d(TAG, "adapter set: " + (flingContainer == null ? "flingContainer is NULL" : "flingContainer is not NULL"));
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
cardList.remove(0);
cardListAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
makeToast(FlashCardActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(FlashCardActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
Log.d(TAG, "onAdapterAboutToEmpty: "+itemsInAdapter);
cardList.add(getCardItem());
cardListAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(FlashCardActivity.this, "Clicked!");
}
});
}
#OnClick(R.id.right)
public void right() {
/**
* Trigger the right event manually.
*/
flingContainer.getTopCardListener().selectRight();
}
#OnClick(R.id.left)
public void left() {
flingContainer.getTopCardListener().selectLeft();
}
public CardItem getCardItem() {
// No problem here.
return newCard;
}
}
Notice that, getCardItem() just get one card. First of all, it calls two cards and the cardList has two cards when activity has created. And after that I'd like to get just one card after swipe. getCardItem() has no problem. I can see that I receives the data from my Server.
This is my custom CardListAdapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import java.util.List;
public class CardListAdapter extends ArrayAdapter {
private final String TAG = this.getClass().getSimpleName();
private Context context;
private int cardResId;
private int frontResId;
private int backResId;
private List<CardItem> cardList;
private LayoutInflater mInflater;
//this, R.layout.card_item, R.id.card_front, R.id.card_back, cardList
public CardListAdapter(Context context, int cardResId, ArrayList<CardItem> cardList) {
super(context, cardResId);
this.context = context;
this.cardResId = cardResId;
this.cardList = cardList;
mInflater = LayoutInflater.from(context);
}
public void setItem(CardItem newItem) {
Log.d(TAG, "setItem");
for (int i = 0; i < cardList.size(); i++) {
CardItem item = cardList.get(i);
if (item.seq == newItem.seq) {
cardList.set(i, newItem);
break;
}
}
}
#Override
public int getCount() {
Log.d(TAG, "getVIew");
return 0;
}
public int getPosition(CardItem item) {
Log.d(TAG, "getPosition = "+item);
return cardList.indexOf(item);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(cardResId, parent,false);
holder = new ViewHolder();
Log.d(TAG, "getView");
holder.frontTV = convertView.findViewById(R.id.card_front);
holder.backTV = convertView.findViewById(R.id.card_back);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.frontTV.setText((String)getItem(position));
holder.backTV.setText((String)getItem(position));
return convertView;
}
static class ViewHolder
{
TextView frontTV, backTV;
}
}
I checked many blogs and other Q&A, but I haven't figured it out how to solve this problem. That activity keeps going back after receiving 'one word' data from the Server and It doesn't show any error messages.
I have been taking this Android tutorial at CodeLearn and have faced a problem. I have searched all through the Internet and I can't seem to find any answer for this.
Here's the code for the TweetListActivity:
package com.arvisapps.aryansh.encryptit;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class TweetListActivity extends ListActivity
{
private String[] stringArray;
private ArrayAdapter tweetItemArrayAdapter;
private List<Tweet> tweets;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweet_list);
tweets = new ArrayList<Tweet>();
for(int i = 0; i < 5 ; i++)
{
Tweet tweet = new Tweet();
tweet.setTitle("Header #" + i);
Log.d("Fuck Me", "Title captured " + tweet.getTitle());
tweet.setBody("Body text #" + i);
tweets.add(tweet);
}
tweetItemArrayAdapter = new TweetAdapter(this, tweets);
setListAdapter(tweetItemArrayAdapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
Intent intent = new Intent(this, TweetDetailActivity.class);
startActivity(intent);
}
}
Here's the code for TweetAdapter:
package com.arvisapps.aryansh.encryptit;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class TweetAdapter extends ArrayAdapter<Tweet> {
String headerSet;
private LayoutInflater inflater;
public TweetAdapter(Activity activity, List<Tweet> tweets) {
super(activity, R.layout.row_tweet, tweets);
inflater = activity.getWindow().getLayoutInflater();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.row_tweet, parent, false);
Tweet tweet = new Tweet();
headerSet = tweet.getTitle();
Log.d("Text Captured", "Text Captured "+headerSet);
((TextView)convertView.findViewById(R.id.tweetTitle)).setText(headerSet);
return convertView;
}
}
Here's an additional POJO:
package com.arvisapps.aryansh.encryptit;
public class Tweet
{
private String id;
private String title;
private String body;
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return this.title;
}
public void setBody(String body)
{
this.body = body;
}
public String getBody()
{
return this.body;
}
public void setId(String id)
{
this.id = id;
}
public String getId()
{
return this.id;
}
}
The problem is that when I check the logcat for TweetListActivity it shows the right text, i.e, the text I need as an output but in TweetAdapter upon checking the Logcat the same text is nullified, i.e, it is displayed as null in the logcat. I want that the text in TweetAdapter to be what it is in the TweetListActivity.
One of my app activity is called DayGallery activity (infinite images gallery) ,
when i open the gallery, it show first image randomly , and not start with first image i specified in DayGallery activity code .
what am trying to achieve is:
FIRST: start with first image specified in DayGallery activity code as below :
when open Day1 gallery ,first image to appear is:
R.drawable.day_one_1
and when open Day2 gallery ,first image to appear is:
R.drawable.day_two_1
and like that for all Days gallery, also keep infinite scrolling in both sides.
SECOND : if am in gallery stopped on image named day_one_7 for example then press back to go to previous activity and return again to gallery , i want to see the same image i saw before i left gallery ,
but if i exit the app then open the gallery again , it must reset to show the first image i specified in DayGallery activity code , explained as bellow image .
actually i searched google for that purpose but i cant get any helpful thing about it ,
any help will be highly appreciated .
DayGallery.java:
#SuppressWarnings("deprecation")
public class DayGallery extends Activity {
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// Set the layout to use
setContentView(R.layout.main);
if (customTitleSupported) {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);
tv = (TextView) findViewById(R.id.title_tv1);
tv.setTypeface(FontFactory.getBFantezy(getBaseContext()));
}
InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne);
galleryOne.setAdapter(initializeImages());
galleryOne.setSelection(galleryOne.getCount()/2);
}
private InfiniteGalleryAdapter initializeImages() {
InfiniteGalleryAdapter galleryAdapter = null;
String day = getIntent().getStringExtra("dayname");
if(day.equalsIgnoreCase("Day1")){
int[] tempimages = { R.drawable.day_one_1, R.drawable.day_one_2,R.drawable.day_one_3,
R.drawable.day_one_4, R.drawable.day_one_5,R.drawable.day_one_6,R.drawable.day_one_7,
R.drawable.day_one_8, R.drawable.day_one_9,R.drawable.day_one_10,R.drawable.day_one_11,
R.drawable.day_one_12
};
String[] name = { "00:35","00:35","00:35","1:07","2:00","2:01","2:09",
"2:12","2:15","6:13","6:13","6:13"
};
tv.setText("Day one pictures");
galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);
}
else if(day.equalsIgnoreCase("Day2")){
int[] tempimages = { R.drawable.day_two_1, R.drawable.day_two_2,R.drawable.day_two_3,
R.drawable.day_two_4, R.drawable.day_two_5,R.drawable.day_two_6,R.drawable.day_two_7,
R.drawable.day_two_8, R.drawable.day_two_9,R.drawable.day_two_10,R.drawable.day_two_11,
R.drawable.day_two_12
};
String[] name = { "12:04","12:04", "12:04","12:05","12:06", "12:07",
"12:07","12:07","12:08","12:10","12:10","12:10"
};
tv.setText("Day two pictures");
galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);
}
// AND THE SAME FOR REST OF DAYS TILL Day10//
return galleryAdapter;
}
}
class InfiniteGalleryAdapter extends BaseAdapter {
private Context mContext;
private int[] images;
private String[] name;
public InfiniteGalleryAdapter(Context c, int[] imageIds,String[] names) {
this.mContext = c;
images = imageIds;
name=names;
inflater = (LayoutInflater)mContext.getSystemService ( Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return Integer.MAX_VALUE;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
private LayoutInflater inflater=null;
public class ViewHolder{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = getImageView();
int itemPos = (position % images.length);
try { i.setImageResource(images[itemPos]); ((BitmapDrawable) i.getDrawable()).setAntiAlias(true);
}
catch (OutOfMemoryError e) { Log.e("InfiniteGalleryAdapter", "Out of memory creating imageview. Using empty view.", e);
}
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.gallery_items, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textView1);
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else holder=(ViewHolder)vi.getTag();
holder.text.setText(name[itemPos]);
final int stub_id=images[itemPos];
holder.image.setImageResource(stub_id);
return vi;
}
private ImageView getImageView() {
ImageView i = new ImageView(mContext);
return i;
}
}
#SuppressWarnings("deprecation")
class InfiniteGallery extends Gallery {
public InfiniteGallery(Context context) {
super(context);
init();
}
public InfiniteGallery(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public InfiniteGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
// These are just to make it look pretty
setSpacing(25);
setHorizontalFadingEdgeEnabled(false);
}
}
UPDATE:
I add this line of code :
galleryOne.setSelection(0);
after this line :
galleryOne.setSelection(galleryOne.getCount()/2);
in my code it result in showing the first image as specified it in DayGallery activity , but it result to one way infinite scrolling to left side only but not in both side ,
How we can get two way infinite scrolling of my gallery images with showing the first image as specified it in DayGallery activity ?
really appreciate any help , thanks.
I can tell you the logic to write infinite viewpager which uses fragments. This viewpager can scroll in both direction infinitely. Also it can be launched from any particular fragment. My requiremnet was:
I had an ebook and user can click on any menu(chapters) and it should launch that and then it should be possible to scroll both ways. I guess your are trying to achieve same thing with gallery:
Check the code:
InfinitePagerAdapter.java:
package com.example.multiplepages;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
/**
* A PagerAdapter that wraps around another PagerAdapter to handle paging
* wrap-around.
*
*/
public class InfinitePagerAdapter extends PagerAdapter {
private static final String TAG = "InfinitePagerAdapter";
private static final boolean DEBUG = true;
private PagerAdapter adapter;
public InfinitePagerAdapter(PagerAdapter adapter) {
this.adapter = adapter;
}
#Override
public int getCount() {
// warning: scrolling to very high values (1,000,000+) results in
// strange drawing behaviour
return Integer.MAX_VALUE;
}
/**
* #return the {#link #getCount()} result of the wrapped adapter
*/
public int getRealCount() {
return adapter.getCount();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
debug("getRealCount: " + getRealCount());
int virtualPosition = position % getRealCount();
debug("instantiateItem: real position: " + position);
debug("instantiateItem: virtual position: " + virtualPosition);
// only expose virtual position to the inner adapter
return adapter.instantiateItem(container, virtualPosition);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
int virtualPosition = position % getRealCount();
debug("destroyItem: real position: " + position);
debug("destroyItem: virtual position: " + virtualPosition);
// only expose virtual position to the inner adapter
adapter.destroyItem(container, virtualPosition, object);
}
/*
* Delegate rest of methods directly to the inner adapter.
*/
#Override
public void finishUpdate(ViewGroup container) {
adapter.finishUpdate(container);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return adapter.isViewFromObject(view, object);
}
#Override
public void restoreState(Parcelable bundle, ClassLoader classLoader) {
adapter.restoreState(bundle, classLoader);
}
#Override
public Parcelable saveState() {
return adapter.saveState();
}
#Override
public void startUpdate(ViewGroup container) {
adapter.startUpdate(container);
}
/*
* End delegation
*/
private void debug(String message) {
if (DEBUG) {
Log.d(TAG, message);
}
}
}
InfiniteViewPager.java:
package com.example.multiplepages;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
/**
* A {#link ViewPager} that allows pseudo-infinite paging with a wrap-around
* effect. Should be used with an {#link InfinitePagerAdapter}.
*
*/
public class InfiniteViewPager extends ViewPager {
int mPageOffset = 0;
public InfiniteViewPager(Context context) {
super(context);
}
public InfiniteViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setAdapter(PagerAdapter adapter) {
super.setAdapter(adapter);
// offset first element so that we can scroll to the left
setCurrentItem(0);
}
public void setpageOffset(int pageOffset) {
mPageOffset = pageOffset;
}
#Override
public void setCurrentItem(int item) {
// offset the current item to ensure there is space to scroll
item = getOffsetAmount() + (item % getAdapter().getCount());
item = item + mPageOffset;
super.setCurrentItem(item);
}
private int getOffsetAmount() {
if (getAdapter() instanceof InfinitePagerAdapter) {
InfinitePagerAdapter infAdapter = (InfinitePagerAdapter) getAdapter();
// allow for 100 back cycles from the beginning
// should be enough to create an illusion of infinity
// warning: scrolling to very high values (1,000,000+) results in
// strange drawing behaviour
return infAdapter.getRealCount() * 100;
} else {
return 0;
}
}
}
MultiplePageScroll.java : This is MainActivity
package com.example.multiplepages;
import java.util.ArrayList;
import java.util.List;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class MultiplePageScroll extends FragmentActivity {
private int listSize = 0;
public int listPos = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_multiple_page_scroll);
Bundle bundle = getIntent().getExtras();
listSize = bundle.getInt("listSize");
listPos = bundle.getInt("itemPosition");
PagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public int getCount() {
return listSize;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putInt("identifier", position);
fragment.setArguments(args);
return fragment;
}
};
// wrap pager to provide infinite paging with wrap-around
PagerAdapter wrappedAdapter = new InfinitePagerAdapter(adapter);
// actually an InfiniteViewPager
InfiniteViewPager viewPager = (InfiniteViewPager) findViewById(R.id.pager);
viewPager.setpageOffset(listPos);
viewPager.setAdapter(wrappedAdapter);
}
}
PageFragment.java:
package com.example.multiplepages;
import java.io.IOException;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
//import android.webkit.WebSettings;
import android.widget.Toast;
public class PageFragment extends Fragment {
String path="s_english/contents";
AssetManager assMan = null;
int pageIndex;
String pagePath = null;
String[] pageList = null;
private int listPosition;
public static PageFragment newInstance(int index) {
PageFragment pageFragment = new PageFragment();
Bundle bundle = new Bundle();
bundle.putInt("index", index);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
listPosition = args.getInt("identifier");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
WebView mWebView = (WebView) view.findViewById(R.id.webview);
mWebView.addJavascriptInterface(new JavaScriptInterface(getActivity()), "NativeFunc");
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.getSettings().setBuiltInZoomControls(true);
assMan = getActivity().getAssets();
try {
pageList = assMan.list(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pageIndex = listPosition;
pagePath=pageList[pageIndex];
mWebView.loadUrl("file:///android_asset/s_english/contents/" + pagePath);
//mWebView.loadUrl("http://192.168.0.33:8080/orginalsource/contents/" + pagePath);
//MultiplePageScroll.mSpinner.setVisibility(View.GONE);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("dummy", true);
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
}
}
activity_multiple_page_scroll.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.multiplepages.InfiniteViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
You can use sharedPrefernce to save the launchedpage and use that. By modifying this code a little you can achieve what you want.
I want to create a ArrayAdapter for one spinner. So each element contain one string (which will be displayed in the spinner/list) and one value (e.g. an ID). How I can easily store a second value beside each string without implementing a new Adapter class?
Sincerely
xZise
You may create a class with two fields: one for text and another for ID. And implement toString method as returning the value of the text field. Here is an example:
package org.me.adaptertest;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ListActivity {
public static class Element {
private String mText;
private long mId;
public Element(String text, long id) {
mText = text;
mId = id;
}
public long getId() {
return mId;
}
public void setId(long id) {
mId = id;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
#Override
public String toString() {
return mText;
}
}
private List<Element> mItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mItems = new ArrayList<MainActivity.Element>();
mItems.add(new Element("Element 1", 1));
mItems.add(new Element("Element 2", 2));
mItems.add(new Element("Element 3", 3));
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
android.R.id.text1, mItems));
getListView().setOnItemClickListener(new ListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,
"ID is " + mItems.get(position).getId(),
Toast.LENGTH_SHORT).show();
}
});
}
}
You could use a hashmap to map an ID to each string.