I am using Timertask for scrolling images with viewpager. I need to show all images after that it is automatically move to category wise (no click operation).
public class GalleryActviity extends AppCompatActivity {
Timer timer;
LinearLayout images_lay;
ArrayList<String> arraylist = new ArrayList<String>();
List<String> tempimages = new ArrayList<String>();
ViewPager mPager ;
private static int currentPage = 0
List<String> dealimages = new ArrayList<>();
ArrayList<DetailImage> detail_images = new ArrayList<DetailImage>();
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
images_lay =(LinearLayout)findViewById(R.id.images_lay);
mPager = (ViewPager) findViewById(R.id.pager);
Intent in = getIntent();
Log.v("Tag_resid",""+in.getStringExtra("restid"));
String restid = in.getStringExtra("restid");
restaurntrestid(restid);
}
private void restaurntrestid(String restid) {
ServiceClient serviceClient = ServiceUtil.getServiceClient();
serviceClient.restaurntrestid(restid, restidcallback);
}
Callback<JsonObject> restidcallback = new Callback<JsonObject>() {
#Override
public void success(final JsonObject cusinerestaurantsinfo, Response response) {
imagesDeatail(cusinerestaurantsinfo);
}
#Override
public void failure(RetrofitError error) {
}
};
private void imagesDeatail(JsonObject cusinerestaurantsinfo) {
try {
JsonArray restaurant_imagesarray = cusinerestaurantsinfo.get("restaurant_images")
.getAsJsonArray();
for (int i = 0; i < restaurant_imagesarray.size(); i++) {
String url = restaurant_imagesarray.get(i).getAsJsonObject().get("url").getAsString();
String type = restaurant_imagesarray.get(i).getAsJsonObject().get("type").getAsString();
if(!arraylist.contains(type)){
arraylist.add(type);
// type means category like food, menu, logo...etc(dynamic data)
}
dealimages.add(url);
DetailImage detail = new DetailImage();
detail.setType(type);
detail.setUrl(url);
detail_images.add(detail);
}
mPager.setAdapter(new DealAdapter(GalleryActviity.this, dealimages));
imageRotator(1);
imageshow();
} catch (Exception e) {
e.printStackTrace();
}
}
public void imageRotator(int seconds) {
currentPage = 0;
timer = new Timer();
timer.scheduleAtFixedRate(new ImageRotateTask(), 0, seconds * 3000);
}
class ImageRotateTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (currentPage == dealimages.size() ) {
timer.cancel();
//Something here
}
else {
mPager.setCurrentItem(currentPage++, true);
}
}
});
}
}
private void imageshow(){
for(int i = 0; i < arraylist.size(); i++) {
final Button txtview = new Button(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
layoutParams.setMargins(0, 0, 0, 0);
if(i == 0){
txtview.setText("All");
txtview.setBackgroundColor(getResources().getColor(R.color.navigationBarwhite));
txtview.setTextColor(getResources().getColor(R.color.colorPrimary));
}
else {
txtview.setText(arraylist.get(i));
txtview.setBackgroundColor(getResources().getColor(R.color.navigationBarwhite));
txtview.setTextColor(getResources().getColor(R.color.navigationBarColor));
}
txtview.setLayoutParams(layoutParams);
txtview.setTextSize(12);
txtview.setAllCaps(false);
txtview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!txtview.getText().toString().equalsIgnoreCase("All")){
//image_display(txtview.getText().toString().trim());
txtview.setBackgroundColor(getResources().getColor(R.color.navigationBarwhite));
txtview.setTextColor(getResources().getColor(R.color.colorPrimary));
}
else if(txtview.getText().toString().equalsIgnoreCase("All")){
imageRotator(1);
mPager.setAdapter(new DealAdapter(GalleryActviity.this, dealimages));
}
}
});
images_lay.addView(txtview);
}
}
}
Here i am showing all the images in "ALL" section. how to show the remain images of every catgory. I added my screenshot which will show the images . "ALL" means every category type image will showing in this section.
Here i can showing all images in "ALL" Section, now how to move to automatically show the images based on category.
Related
I am having a Viewpager where i am loading data of different categories. I want to show a custom dialog popup whenever user stays on a particular category for 5 seconds or more asking the user if he/she wants to share the content. For that i have used a custom dialog and am hiding/showing based on the condition.
But the problem is, that if i want to open the dialog if the user stays on Viewpager item at position let's say 3, the dialog is opening for the Viewpager item at position 4.
I am not sure why it's referencing the wrong Viewpager item.
I am including the code of Adapter class for the reference.
ArticleAdapter.java
public class ArticleAdapter extends PagerAdapter {
public List<Articles> articlesListChild;
private LayoutInflater inflater;
Context context;
View rootView;
View customArticleShareDialog, customImageShareDialog;
public int counter = 0;
int contentType = 0;
int userId;
public ArticleAdapter(Context context, List<Articles> articlesListChild, int userId) {
super();
this.context = context;
this.userId = userId;
this.articlesListChild = articlesListChild;
}
#Override
public int getCount() {
return articlesListChild.size();
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 5*1000, 5*1000);
}
private void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
switch (contentType) {
case 1:
showShareDialog("articles");
break;
case 2:
showShareDialog("images");
break;
default :
// Do Nothing
}
}
};
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = LayoutInflater.from(container.getContext());
View viewLayout = inflater.inflate(R.layout.article_single_item, null, false);
final ImageView contentIv, imageContentIv;
final TextView sharingTextTv;
final LinearLayout articleShareBtn, articlesLayout, imagesLayout, customArticleShareDialog, customImageShareDialog;
contentIv = viewLayout.findViewById(R.id.content_iv);
articleShareBtn = viewLayout.findViewById(R.id.article_share_btn);
articlesLayout = viewLayout.findViewById(R.id.articles_layout);
imagesLayout = viewLayout.findViewById(R.id.images_layout);
imageContentIv = viewLayout.findViewById(R.id.image_content_iv);
sharingTextTv = viewLayout.findViewById(R.id.sharing_text_tv);
customArticleShareDialog = viewLayout.findViewById(R.id.articles_share_popup);
customImageShareDialog = viewLayout.findViewById(R.id.images_share_popup);
rootView = viewLayout.findViewById(R.id.post_main_cv);
viewLayout.setTag(rootView);
articleShareBtn.setTag(rootView);
// Images
if (articlesListChild.get(position).getArticleCatId() == 1) {
articlesLayout.setVisibility(GONE);
imagesLayout.setVisibility(View.VISIBLE);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(imageContentIv);
imageContentIv.setScaleType(ImageView.ScaleType.FIT_XY);
sharingTextTv.setText("Found this image interesting? Share it with your friends.");
counter = 0;
startTimer();
// Articles
} else if (articlesListChild.get(position).getArticleCatId() == 2){
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
articlesLayout.setVisibility(View.VISIBLE);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(contentIv);
contentIv.setScaleType(ImageView.ScaleType.FIT_XY);
sharingTextTv.setText("Found this article interesting? Share it with your friends.");
counter = 0;
startTimer();
}
container.addView(viewLayout, 0);
return viewLayout;
}
public void showShareDialog(String categoryType) {
if (categoryType.equalsIgnoreCase("articles")) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
customArticleShareDialog.setVisibility(View.VISIBLE);
}
});
} else if (categoryType.equalsIgnoreCase("images")) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
customImageShareDialog.setVisibility(View.VISIBLE);
}
});
}
}
}
ArticleActivity.java
public class ArticleActivity extends AppCompatActivity {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.drawer_layout)
DrawerLayout drawer;
#BindView(R.id.articles_view_pager)
ViewPager articlesViewPager;
#BindView(R.id.constraint_head_layout)
CoordinatorLayout constraintHeadLayout;
private ArticleAdapter articleAdapter;
private List<List<Articles>> articlesList = null;
private List<Articles> articlesListChild = new ArrayList<>();
private List<Articles> articlesListChildNew = new ArrayList<>();
SessionManager session;
Utils utils;
final static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
int userIdLoggedIn;
LsArticlesSharedPreference lsArticlesSharedPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
toolbar.setTitle("");
toolbar.bringToFront();
session = new SessionManager(getApplicationContext());
if (session.isLoggedIn()) {
HashMap<String, String> user = session.getUserDetails();
String userId = user.get(SessionManager.KEY_ID);
userIdLoggedIn = Integer.valueOf(userId);
} else {
userIdLoggedIn = 1000;
}
utils = new Utils(getApplicationContext());
String storedTime = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("lastUsedDate", "");
System.out.println("lastUsedDate : " + storedTime);
if (utils.isNetworkAvailable()) {
insertData();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.colorWhite));
drawer.addDrawerListener(toggle);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesListChild, userIdLoggedIn);
toggle.syncState();
clickListeners();
toolbar.setVisibility(View.GONE);
} else {
Intent noInternetIntent = new Intent(getApplicationContext(), NoInternetActivity.class);
startActivity(noInternetIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finishAffinity();
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
articleAdapter.notifyDataSetChanged();
insertData();
Toast.makeText(this, "Refreshed", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("ClickableViewAccessibility")
public void clickListeners() {
}
private void insertData() {
Intent intent = new Intent(getBaseContext(), OverlayService.class);
startService(intent);
final SweetAlertDialog pDialog = new SweetAlertDialog(ArticleActivity.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.colorPrimary));
pDialog.setTitleText("Loading");
pDialog.setCancelable(false);
pDialog.show();
Api.getClient().getHomeScreenContents(userIdLoggedIn, new Callback<ArticlesResponse>() {
#Override
public void success(ArticlesResponse articlesResponse, Response response) {
articlesList = articlesResponse.getHomeScreenData();
if (!articlesList.isEmpty()) {
for (int i = 0; i < articlesList.size(); i++) {
articlesListChildNew = articlesList.get(i);
articlesListChild.addAll(articlesListChildNew);
}
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
pDialog.dismiss();
} else {
List<Articles> savedArticles = lsArticlesSharedPreference.getFavorites(getApplicationContext());
if (!savedArticles.isEmpty()) {
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, savedArticles, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
pDialog.dismiss();
} else {
Api.getClient().getAllArticles(new Callback<AllArticlesResponse>() {
#Override
public void success(AllArticlesResponse allArticlesResponse, Response response) {
articlesListChild = allArticlesResponse.getArticles();
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
};
#Override
public void failure(RetrofitError error) {
Log.e("articlesData", error.toString());
}
});
pDialog.dismiss();
}
}
}
#Override
public void failure(RetrofitError error) {
pDialog.dismiss();
Toast.makeText(ArticleActivity.this, "There was some error fetching the data.", Toast.LENGTH_SHORT).show();
}
});
}
}
Issue reason:
You face this issue because the viewpager preload fragments in background. It means that when you see 3rd fragment, the viewpager is instantiating 4th. Due to this workflow your timer for 3rd screen is cancelled and timer for 4th screen is started. Check out this link to understand what is going on.
Solution:
I would do next:
Then set page change listener for your adapter. How to do it
In this listener you can get current page and start timer for this page (and cancel timer for previously visible page).
You don't need to call startTimer() method when you instantiate item in instantiateItem() method.
i am making a slider walkthrough which is introduced in the app for the first item when the user clicks the app....and it is gone when the user again open it.
like this: https://www.youtube.com/watch?v=va2IRW_e7_w
the problem is that i am regaining it again and again whenever i opent the app, its a small mistake and i can't find it.
Main2Activity:
public class Main2Activity extends AppCompatActivity {
Button next, skip;
private ViewPagerAdapter adapter;
private ViewPager viewPager;
private SliderWalkthrough sliderWalkthrough;
private int[] layouts;
private TextView[] dots;
private LinearLayout dotsLayout;
ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addButtonDots(position);
if (position == layouts.length - 1) {
next.setText("GET STARTED");
skip.setVisibility(View.GONE);
} else {
next.setText("NEXT");
skip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sliderWalkthrough = new SliderWalkthrough(this);
if (!sliderWalkthrough.Check()) {
sliderWalkthrough.setFirst(false);
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
finish();
}
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_main2);
viewPager = (ViewPager) findViewById(R.id.id_WalkThroughViewPager);
dotsLayout = (LinearLayout) findViewById(R.id.layout_dots);
layouts = new int[]{R.layout.slider_walkthrough_screen1, R.layout.slider_walkthrough_screen2, R.layout.slider_walkthrough_screen3};
addButtonDots(0);
adapter = new ViewPagerAdapter();
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(listener);
}
private void addButtonDots(int position) {
dots = new TextView[layouts.length];
int[] colorActive = getResources().getIntArray(R.array.active_dot);
int[] colorInactive = getResources().getIntArray(R.array.inactive_dot);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setTextSize(30);
dots[i].setTextColor(colorInactive[position]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0) {
dots[position].setTextColor(colorActive[position]);
}
}
}
SliderWalkthrough:
public class SliderWalkthrough {
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
public SliderWalkthrough(Context context) {
this.context = context;
sharedPreferences=context.getSharedPreferences("first",0);
editor=sharedPreferences.edit();
}
public void setFirst(Boolean firstTime){
editor.putBoolean("check",firstTime);
editor.commit();
}
public boolean Check()
{
return sharedPreferences.getBoolean("check",true);
}
}
You need to change the preference value to false once your walk-through is finished otherwise if (!sliderWalkthrough.Check()) { will never be executed and walk-through will be shown everytime
#Override
public void onPageSelected(int position) {
addButtonDots(position);
if (position == layouts.length - 1) {
next.setText("GET STARTED");
skip.setVisibility(View.GONE);
sliderWalkthrough.setFirst(false);
//^^^^^^ add this case
}
else {
next.setText("NEXT");
skip.setVisibility(View.VISIBLE);
}
}
Note : remove sliderWalkthrough.setFirst(false); , no longer required
if (!sliderWalkthrough.Check()) {
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
finish();
}
I am fetching data from json with Volley and populating RecyclerView with the parsed data but I ran into a bit of problem:
The call to get the items is in onCreate method, so the call is repeated each time the activity is recreated both from configuration changes and otherwise; hence the data is reloaded. So I found this answer that uses parcelables
and this article on Codepath (still on parcelables). After I have followed the instructions explicitly (or so I feel), there seems to be no change: the call to get data is repeated each time the activity is recreated.
FruitItems
public class FruitItems implements Parcelable {
private String fruit_title;
private String fruit_description;
private String fruit_image;
public String getFruit_title() {
return fruit_title;
}
public void setFruit_title(String fruit_title) {
this.fruit_title = fruit_title;
}
public String getFruit_description() {
return fruit_description;
}
public void setFruit_description(String fruit_description) {
this.fruit_description = fruit_description;
}
public String getFruit_image() {
return fruit_image;
}
public void setFruit_image(String fruit_image) {
this.fruit_image = fruit_image;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.fruit_title);
dest.writeString(this.fruit_description);
dest.writeString(this.fruit_image);
}
public FruitItems() {
}
protected FruitItems(Parcel in) {
this.fruit_title = in.readString();
this.fruit_description = in.readString();
this.fruit_image = in.readString();
}
public static final Parcelable.Creator<FruitItems> CREATOR = new Parcelable.Creator<FruitItems>() {
#Override
public FruitItems createFromParcel(Parcel source) {
return new FruitItems(source);
}
#Override
public FruitItems[] newArray(int size) {
return new FruitItems[size];
}
};
}
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private final String KEY_POST_ITEMS = "fruititems";
//List of fruits
private List<FruitItems> mFruitItemsList;
//Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.fruit_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_POST_ITEMS)) {
mFruitItemsList = savedInstanceState.getParcelableArrayList(KEY_POST_ITEMS);
} else {
//Initializing the fruitlist
mFruitItemsList = new ArrayList<>();
if (NetworkCheck.isAvailableAndConnected(this)) {
getData();
} else {
final Context mContext;
mContext = this;
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.alert_titl);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
alertDialogBuilder.setMessage(R.string.alert_mess);
alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
adapter = new FruitAdapter(mFruitItemsList, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList(KEY_POST_ITEMS, ArrayList<? extends Parcelable>))mFruitItemsList);
super.onSaveInstanceState(savedInstanceState);
}
//Getting json data
private void getData(){
Log.d(TAG, "getData called");
//Show progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_fruit));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigFruit.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//parsing json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
FruitItems fruitItem = new FruitItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
fruitItem.setFruit_title(jsonObject.getString(ConfigFruit.TAG_POST_TITLE));
fruitItem.setFruit_description(jsonObject.getString(ConfigFruit.TAG_POST_DESCRIPTION));
//Parsing image
JSONObject fruitImage = jsonObject.getJSONObject("thumbnail");
fruitItem.setFruit_image(fruitImage.getString("url"));
} catch (JSONException w) {
w.printStackTrace()
}
mFruitItemsList.add(fruitItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
}
I may not be a pro but I know that I have goofed somewhere in the codes above, else it should have worked.
Now, my question is where did I goof and how do I plug this mistake?
EDIT
I have edited the codes above to reflect the answer that I accepted. It works fine but there is still a problem.
I start Activity B from MainActivity. If I press the back-button in Activity B the data is saved but when I press the up-button, the getData is called again and the data is re-fetched.
Please, is there anyway around this?
You don't seem to have an onSaveInstanceState in your mainactivity. You need something like
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(KEY_POST_ITEMS,mFruitItemsList) ;
}
In order to retain your data for the activity that is about to be destructed and the one that is being created, you need to override the onSaveInstance callback
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList(KEY_POST_ITEMS, (ArrayList)mFruitItemsList);
super.onSaveInstanceState(savedInstanceState);
}
NOTE: always remember to call the superclass.
I am making a slot machine app and using kankan's wheel for the same. I want to modify the library such that when the rotation stops the item it will point shoud be the one that I set . I have done this but there is a glitch that shows that we have changed the actual image to the one that we want . How to achieve this?
Update:
I have researched a lot on this and if I am right , android scroll is based on duration and distance not items . From kankan's wheel library I can get current item .Now , I am trying to stop the animation as well as scroll , as soon as a certain duration has been reached and the item is the one that I want (through index) . But this is not working .Please help!!
GameActivity
public class GameActivity extends Activity {
float mDeviceDensity;
String mUuid, mTitle, mContent, mReward;
ImageButton play;
SlotMachineAdapter slotAdapter;
private List<HashMap<String, Object>> slotImages = new ArrayList<HashMap<String, Object>>();
ArrayList<String> imagesWinId = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filler_up_game);
DisplayMetrics display = getResources().getDisplayMetrics();
mDeviceDensity = display.density;
slotAdapter = new SlotMachineAdapter(this);
getPassedData();
setSoundPlayer(R.raw.clicks,true);
initWheel(R.id.slot_1, false, 0);
initWheel(R.id.slot_2, false, 1);
initWheel(R.id.slot_3, true, 2);
play = (ImageButton) findViewById(R.id.btn_mix);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shuffle(R.id.slot_1, 5000);
shuffle(R.id.slot_2, 7000);
shuffle(R.id.slot_3, 9000);
}
});
}
protected ImageLoader imageLoader;
ArrayList<SlotItem> arrListSlotItems;
private void getPassedData() {
try {
mUuid = getIntent().getStringExtra(getString(R.string.FILLER_UP_UUID));
imageLoader = ImageLoader.getInstance();
Uuid slotImagesExtra = (Uuid) (getIntent()
.getSerializableExtra(getString(R.string.FILLER_UP_IMAGES)));
arrListSlotItems = slotImagesExtra.getArrSlotItemArray();
for (int i = 0; i < arrListSlotItems.size(); i++)
downloadSlotImages(arrListSlotItems.get(i).getSlotId(), arrListSlotItems.get(i).getImageUrl());
} catch (Exception e) {
e.printStackTrace();
}
}
// Wheel scrolled flag
private boolean wheelScrolled = false;
// Wheel scrolled listener
OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
setStatus(wheel.getId(), getWheel(wheel.getId()).getWinningIndex());
}
};
// Wheel changed listener
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
/**
* Updates status
*/
private void updateStatus() {
myThread();
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
GameActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
showAlertDialogWithSingleButton(GameActivity.this, mTitle, mContent, success);
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
android.content.DialogInterface.OnClickListener success = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mContent != null && mContent.contains("again"))
startHomeActivity();
else
startNewsActivity();
}
};
private void startHomeActivity() {
}
private void startNewsActivity() {
}
android.content.DialogInterface.OnClickListener fail = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
};
public void showAlertDialogWithSingleButton(final Activity ctx, final String title, final String message,
DialogInterface.OnClickListener onClickListener) {
// show dialog
}
private void initWheel(int id, boolean monitorScroll, int itemIndex) {
Random randomGenerator = new Random();
int index = randomGenerator.nextInt(arrListSlotItems.size());
WheelView wheel = getWheel(id);
wheel.setViewAdapter(slotAdapter);
wheel.setCurrentItem((index ));
wheel.setVisibleItems(1);
wheel.setWinningIndex(itemIndex);
wheel.addChangingListener(changedListener);
wheel.addScrollingListener(scrolledListener);
wheel.setCyclic(true);
wheel.setEnabled(false);
}
private WheelView getWheel(int id) {
return (WheelView) findViewById(id);
}
private void setStatus(int id, int item) {
int index = 0;
for (int i = 0; i < arrListSlotItems.size(); i++) {
SlotItem d = arrListSlotItems.get(i);
if (d.getSlotId() != 0 && d.getSlotId() == Integer.parseInt(imagesWinId.get(item)))
index = arrListSlotItems.indexOf(d);
}
getWheel(id).setCurrentItem(index, true);
if (id == R.id.slot_3) {
if(player.isPlaying())
{
stopBackgroundAudio();
}
updateStatus();
}
}
private void shuffle(int id, int duration) {
WheelView wheel = getWheel(id);
wheel.scroll(450 + (int) (Math.random() * 50), duration);
}
private class SlotMachineAdapter extends AbstractWheelAdapter {
final int IMAGE_WIDTH = getImageWidth(mDeviceDensity);
final int IMAGE_HEIGHT = getImageHeight(mDeviceDensity);
private Context context;
/**
* Constructor
*/
public SlotMachineAdapter(Context context) {
this.context = context;
}
/**
* Loads image from resources
*/
private Bitmap loadImage(Bitmap bitmap) {
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
return scaled;
}
#Override
public int getItemsCount() {
return slotImages.size();
}
// Layout params for image view
final LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setPadding(0, 5, 0, 5);
img.setLayoutParams(params);
#SuppressWarnings("unchecked")
SoftReference<Bitmap> bitmapRef = (SoftReference<Bitmap>) slotImages.get(index).get("image");
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(bitmap);
}
img.setImageBitmap(bitmap);
return img;
}
}
private int getImageWidth(float density) {
}
private int getImageHeight(float density) {
}
private void downloadSlotImages(final int id, String slotObj) {
//downloading slot images from server
}
}
This is the code. Through this code, when slot stops I want it to scroll some more untill it reaches the image position that I receaved from server. I can do this .But this is providing a lil glitch . Is there any way to stop scrolling when the image is reached as soon as certain duration is reached.
P.S. If you need anymore detail I can provide you.
P.P.S. Screenshots wont give you any detailed insight about the issue.
After days of searching I finally did it.All I had to do was set interpolater as LinearInterpolater and While setting setCurrentItem set animation as true.
I've got a strange problem, a Dialog being created and called for "show()" but not being visible in my activity...
The thing is it goes through the call "show", I've seen it in the debugger, but nothing...
here is the code:
protected void initializeSpinners() {
spnPlayLists = (Spinner) findViewById(R.id.spnLists);
spnProviders = (Spinner) findViewById(R.id.spnProvider);
spnProviders.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> _spinner, View _parent,
int _pos, long _id) {
if (_spinner == spnProviders) {
String[] playListsId = core.getAllPlayListsFrom(_pos);
int items = playListsId.length;
**showProgressDialog(items);**
String[] playListsNames = new String[items];
String[] playListsThumbs = new String[items];
playLists = new PlayList[items];
for (int i = 0; i < items; i++) {
String id = playListsId[i];
PlayList playList = core.getPlayList(id, true);
playLists[i] = playList;
playListsNames[i] = playList.title;
playListsThumbs[i] = playList.thumb;
handle.sendEmptyMessage(i);
}
loadPlayLists(playListsNames, playListsThumbs);
myPd_bar.dismiss();
}
}
#Override
public void onNothingSelected(AdapterView<?> _arg0) {
}
});
ProvidersArrayAdapter providersAdapter = new ProvidersArrayAdapter(this);
spnProviders.setAdapter(providersAdapter);
}
and the function called up:
private void showProgressDialog(int _items) {
handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
myPd_bar.setProgress(msg.what + 1);
}
};
myPd_bar = new ProgressDialog(Intro.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle("Please Wait..");
myPd_bar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myPd_bar.setProgress(0);
myPd_bar.setMax(_items);
**myPd_bar.show();**
}
what am I doing bad...?
It is possible that your dialog is getting dismissed before it appears. Basically your loop is not going long enough for the view to appear.
Have you tried to comment out the dismiss line and see if it appear then?
Finally I realized. I was holding the activity thread in the spinner so it won't show anything until it finishes!
here is my solution, using an asyntask (properly, I was using them badly on the playlist load, and blocking)
protected void setupDialog() {
handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what < 0){
loadPlayLists(playListsNames, playListsThumbs);
myPd_bar.dismiss();
} else {
myPd_bar.setProgress(msg.what + 1);
}
}
};
myPd_bar = new ProgressDialog(Intro.this);
myPd_bar.setMessage(WAIT_MESSAGE);
myPd_bar.setTitle(WAIT_TITLE);
myPd_bar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myPd_bar.setProgress(0);
}
protected void initializeSpinners() {
spnPlayLists = (Spinner) findViewById(R.id.spnLists);
spnProviders = (Spinner) findViewById(R.id.spnProvider);
spnProviders.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> _spinner, View _parent,
int _pos, long _id) {
if (_spinner == spnProviders) {
String[] playListsId = core.getAllPlayListsFrom(_pos);
int items = playListsId.length;
myPd_bar.setMax(items);
myPd_bar.show();
new AsyncTask<String[], Integer, Long>(){
#Override
protected Long doInBackground(String[]... _playListsId) {
int items = _playListsId[0].length;
playListsNames = new String[items];
playListsThumbs = new String[items];
playLists = new PlayList[items];
for (int i = 0; i < items; i++) {
String id = _playListsId[0][i];
PlayList playList = core.getPlayList(id, true);
playLists[i] = playList;
playListsNames[i] = playList.title;
playListsThumbs[i] = playList.thumb;
publishProgress(i);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... _progress) {
handle.sendEmptyMessage(_progress[0]);
}
#Override
protected void onPostExecute(Long _result) {
handle.sendEmptyMessage(-1);
}
}.execute(playListsId);
}
}
#Override
public void onNothingSelected(AdapterView<?> _arg0) {
}
});
ProvidersArrayAdapter providersAdapter = new ProvidersArrayAdapter(this);
spnProviders.setAdapter(providersAdapter);
}