Update layout after writing SharedPreferences? - java

My first thread here - sorry if the text formatting is bad.
I use Android Studio 3.1.3 API27 and work on an app for Smartphone.
The app currently consists of 1 activity (split in 3 fragments), a second activity and 5 xml files.
By using a ViewPager, I'm able to swipe through the 3 fragments.
The 2nd fragment (middle fragment) contains 2 buttons that each open the 2nd activity, which contains many color buttons.
When clicking on the color buttons, I can change the background colors of the 1st fragment.
After choosing a color, the 2nd activity gets closed and I'm back in activity 1 -> fragment2.
It works, but the PROBLEM is that I always have to swipe to the 3rd fragment,
then back to the 2nd and then to the 1st.
If I don't do this, the colors of fragment 1 will remain the old ones.
Now I'm looking for a way to update the layout of fragment 1 as soon as I press a color button of activity 2.
I already tried this:
when writing the SharedPreferences (Activity2), I use editor.apply() instead of editor.commit()
when reading the SharedPreferences (Activity1 -> Fragment1), I use Context.MODE_MULTI_PROCESS instead of Context.MODE_PRIVATE
using viewpage.setOffscreenPageLimit(0); in the MainActivity inside of my public void SetUpViewPager(ViewPager viewpage) method.
Nothing helped, though.
This is how it looks like:
MainActivity.java (Activity 1):
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
ViewPager vp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager vp = findViewById(R.id.vp);
SetUpViewPager(vp);
}
public void SetUpViewPager(ViewPager viewpage)
{
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.AddPageFragment(new Page_1(), "Page 1");
Adapter.AddPageFragment(new Page_2(), "Page 2");
Adapter.AddPageFragment(new Page_3(), "Page 3");
viewpage.setOffscreenPageLimit(0);
viewpage.setAdapter(Adapter);
}
public class MyViewPagerAdapter extends FragmentPagerAdapter
{
private List<Fragment> MyFragment = new ArrayList<>();
private List<String> MyPageTitle = new ArrayList<>();
public MyViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
public void AddPageFragment(Fragment Frag, String Title)
{
MyFragment.add(Frag);
MyPageTitle.add(Title);
}
#Override
public Fragment getItem(int i)
{
return MyFragment.get(i);
}
#Nullable
#Override
public CharSequence getPageTitle(int position)
{
return MyPageTitle.get(position);
}
#Override
public int getCount()
{
return 3;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Page_1.java (Activity 1 -> Fragment 1):
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;
public class Page_1 extends Fragment
{
int backgroundColorLeft, backgroundColorRight, textColorLeft, textColorRight; // Variables for SharedPreferences
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageOne = inflater.inflate(R.layout.page1, container, false); // Link view to layout?
return PageOne;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
SharedPreferences prefs = getActivity().getSharedPreferences("bgColor", Context.MODE_MULTI_PROCESS); // Load saved shared file
backgroundColorLeft = prefs.getInt("backgroundColorLeft", backgroundColorLeft); // Load saved background color for left layout
textColorLeft = prefs.getInt("textColorLeft", textColorLeft); // Load saved text color for left layout
backgroundColorRight = prefs.getInt("backgroundColorRight", backgroundColorRight); // Load saved background color for right layout
textColorRight = prefs.getInt("textColorRight", textColorRight); // Load saved text color for right layout
RelativeLayout relLayoutLeft = getActivity().findViewById(R.id.rel_layout_left); // Link variable to ID of left layout
relLayoutLeft.setBackgroundColor(backgroundColorLeft); // Change background color of left layout
TextView tvLeft = getActivity().findViewById(R.id.tv_left); // Link variable to ID
tvLeft.setTextColor(textColorLeft); // Change text color of left layout
RelativeLayout relLayoutRight = getActivity().findViewById(R.id.rel_layout_right); // Link variable to ID of right layout
relLayoutRight.setBackgroundColor(backgroundColorRight); // Change background color of right layout
TextView tvRight = getActivity().findViewById(R.id.tv_right); // Link variable to ID
tvRight.setTextColor(textColorRight); // Change text color of right layout
super.onActivityCreated(savedInstanceState);
}
}
Page_2.java (Activity 1 -> Fragment 2):
package com.example.konstantin.clipcodes_swiping;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import static android.content.Context.MODE_PRIVATE;
public class Page_2 extends Fragment
{
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageTwo = inflater.inflate(R.layout.page2, container, false);
Button buttonLeft = PageTwo.findViewById(R.id.button_left); // Link variable to ID of left button
buttonLeft.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int pos = 1; // Set position to left
setPosition(pos); // Load setColor method and send 2 color values
}
});
Button buttonRight = PageTwo.findViewById(R.id.button_right); // Link variable to ID of right button
buttonRight.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int pos = 2; // Set position to right
setPosition(pos); // Load setColor method and send 2 color values
}
});
return PageTwo;
}
public void setPosition (int pos) // Start second activity to choose colors
{
Intent intentPos = new Intent(getActivity(), Page_4_Colors.class); // Create intent for current Activity and target activity
SharedPreferences prefs = getActivity().getSharedPreferences("bgColor", Context.MODE_MULTI_PROCESS); // Create new SharedPreferences instance
SharedPreferences.Editor editor = prefs.edit(); // Assign variable to editor function
editor.putInt("position", pos); // Write selected position (int) inside of editor
editor.apply(); // Save values, close process
getActivity().startActivity(intentPos); // Start second activity
}
}
Page_3.java (Activity 1 -> Fragment 3):
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Page_3 extends Fragment
{
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageThree = inflater.inflate(R.layout.page3, container, false);
return PageThree;
}
}
Page_4_Colors.java (Activity 2):
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class Page_4_Colors extends Activity
{
int pos;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.page4_colors);
SharedPreferences prefs = getSharedPreferences("bgColor", MODE_MULTI_PROCESS); // Load saved shared file
pos = prefs.getInt("position", pos); // Load saved position (int)
Log.wtf("Position", String.valueOf(pos)); // Show pos value in Log
Button buttonWhite = findViewById(R.id.button_white);
buttonWhite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.white), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonYellow = findViewById(R.id.button_yellow);
buttonYellow.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.yellow), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonOrange = findViewById(R.id.button_orange);
buttonOrange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.orange), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonRed = findViewById(R.id.button_red);
buttonRed.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.red), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonGreen = findViewById(R.id.button_green);
buttonGreen.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.green), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonBlue = findViewById(R.id.button_blue);
buttonBlue.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.blue), getResources().getColor(R.color.white)); // Load setColor method and send 2 color values
}
});
}
public void setColor (int backgroundColor, int textColor) // Write color values into SharedPreferences
{
SharedPreferences prefs = getSharedPreferences("bgColor", MODE_MULTI_PROCESS); // Create new SharedPreferences instance
SharedPreferences.Editor editor = prefs.edit(); // Assign variable to editor function
if (pos == 1)
{
editor.putInt("backgroundColorLeft", backgroundColor); // Write background color (int) inside of editor
editor.putInt("textColorLeft", textColor); // Write text color (int) inside of editor
}
if (pos == 2)
{
editor.putInt("backgroundColorRight", backgroundColor); // Write background color (int) inside of editor
editor.putInt("textColorRight", textColor); // Write text color (int) inside of editor
}
editor.apply(); // Save values, close process
this.finish(); // Close this activity
}
}
Thanks for any help!

use EventBus
unregister and register EventBus in Page_1 onStop() and onStart()
EventBus.getDefault().unregister(this)
EventBus.getDefault().register(this)
and use this for post the value
EventBus.getDefault().post(new MessageEvent("Change Color"));
and this function will handle the MessageEvent
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
//change the color here
//add this function in Page_1
}
when you update the value of color. put in MessageEvent documentation

You can update the UI (or at least the color related part) for each fragment in the onResume() method, thus, when you return from the second activity, it will refresh.

When a Fragment is made visible (i.e., the selected page in your ViewPager), its setUserVisibleHint() method is called. You can override that method in your Fragment and use it to trigger a refresh.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//you can check if the color is changed then refresh the fragment if not then don't do anything
//here you should refresh your fragment , this will called every time you
//view this fragment in all cases even if you didn't move to the
//third tab
}
}
How To Refresh A Fragment
Fragment currentFragment = getFragmentManager().findFragmentByTag("YourFragmentTag");
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();

Related

Getting the button press on recycler view item which is created with method

I'm pretty new to Android Studio and Java overall so this might be simple question but I couldn't find any solutions or either couldn't use them to fix my issue.
So I have a RecyclerView which I can insert items from a list of pre-defined items with the function "addItems()" when I press to a button and display them.
Also those items have ImageButtons -which is just a transparent rectangle- to get individual clicks on them.
The purpose of these ImageButtons are to switch to a new activity which I defined in the "addItems()" method.
But the problem is, I can't catch -but they respond to the clicks- click on those items, and also I can't pass the activity class or the layout file.
To be exact, I want to use these buttons to switch to a new activity and display the info of that item there.
It's my first question here, so if I need to show any code, please tell me to.
NewsAdapter.java
package com.example.yiyecek2.Activities;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.yiyecek2.R;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder>
{
Context mContext;
List<NewsItem> mData;
public NewsAdapter(Context mContext, List<NewsItem> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View layout;
layout = LayoutInflater.from(mContext).inflate(R.layout.lyt_restoran,viewGroup,false);
return new NewsViewHolder(layout);
}
// Changed below ----------
#Override
public void onBindViewHolder(#NonNull NewsViewHolder newsViewHolder, int position) {
// Bind data here
newsViewHolder.tvSellerName.setText(mData.get(position).getSellerName());
newsViewHolder.tvSellerAddress.setText(mData.get(position).getSellerAddress());
newsViewHolder.ivSellerImage.setImageResource(mData.get(position).getSellerImage());
newsViewHolder.tvMinCost.setText(mData.get(position).getMinCost());
newsViewHolder.tvMinTime.setText(mData.get(position).getMinTime());
newsViewHolder.tvDeliveryCost.setText(mData.get(position).getDeliveryCost());
newsViewHolder.tvClassToGo.setText(mData.get(position).getClassToGo());
// Line below is the buttons attached to the items which I aim to use on switching Activities
newsViewHolder.ibGoSellerPage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(SiparisActivity.this, classDominos.class);
startActivity(intent); // startActivity is marked red
}
});
}
// Changed above ----------
#Override
public int getItemCount() {
return mData.size();
}
public class NewsViewHolder extends RecyclerView.ViewHolder{
TextView tvSellerName, tvSellerAddress, tvMinCost, tvMinTime, tvDeliveryCost, tvClassToGo;
ImageView ivSellerImage;
ImageButton ibGoSellerPage;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
tvSellerName = itemView.findViewById(R.id.tvFoodName);
tvSellerAddress = itemView.findViewById(R.id.tvFoodDescription);
ivSellerImage = itemView.findViewById(R.id.ivFoodImage);
tvMinCost = itemView.findViewById(R.id.tvFoodCost);
tvMinTime = itemView.findViewById(R.id.tvMinTime);
tvDeliveryCost = itemView.findViewById(R.id.tvDeliveryCost);
tvClassToGo = itemView.findViewById(R.id.tvClassToGo);
ibGoSellerPage = itemView.findViewById(R.id.ibGoSellerPage);
//int position = getAdapterPosition();
//Toast.makeText(mContext.getApplicationContext(), "Position is: "+position, Toast.LENGTH_SHORT).show();
}
}
}
SiparisActivity.java //this is where I list restaurant items with ImageButtons said above.
package com.example.yiyecek2.Activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.yiyecek2.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import recyclerview.CustomItemAnimator;
public class SiparisActivity extends AppCompatActivity {
Button btnListRestaurants;
RecyclerView NewsRecyclerView;
NewsAdapter newsAdapter;
List<NewsItem> mData;
ImageButton ibGoSellerPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_siparis);
// Hide the action bar
getSupportActionBar().hide();
NewsRecyclerView = findViewById(R.id.news_rv);
btnListRestaurants = (Button) findViewById(R.id.buttonListRestaurants);
NewsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
NewsRecyclerView.setHasFixedSize(true);
NewsRecyclerView.setItemAnimator(new CustomItemAnimator());
// Get clicks on the "List Restaurants"
btnListRestaurants.setOnClickListener(new View.OnClickListener() {
int restaurantCount = 0;
#Override
public void onClick(View view) {
Toast toast = Toast.makeText(getApplicationContext(), "Listing Restaurants", Toast.LENGTH_SHORT);
toast.show();
Timer timerToTransition;
timerToTransition = new Timer();
TimerTask task = new TimerTask() {
public void run() {
addItems();
restaurantCount++;
if (restaurantCount > 9)
{
System.out.println(restaurantCount);
timerToTransition.cancel(); // Stops the timer when theres 10 Restaurants listed
}
}
};
timerToTransition.scheduleAtFixedRate(task,0,300); // waits 300ms before creating a new Restaurant
}
});
if (ibGoSellerPage != null) // Check if Restaurant button exists
{
System.out.println("ON CLICK HERE");
ibGoSellerPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("ON CLICK HERE");
}
});
}
mData = new ArrayList<>();
// fill list news with pre defined data
// Adapter ini and setup
newsAdapter = new NewsAdapter(this,mData);
NewsRecyclerView.setAdapter(newsAdapter);
NewsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void addItems()
{
RecyclerView.State state = null;
int switchInt = 0; // To use in the switch
// Random integer list to assign switchInt a random value
int[] intList;
intList = new int[]{0,1,2,3,4,5,6,7};
// Pick a random int
Random rand = new Random();
int rndInt = rand.nextInt(5);
// Check if the array's index isn't empty(-1)
while (intList[rndInt] != -1)
{
switchInt = (int) intList[rndInt];
intList[rndInt] = -1;
}
//System.out.println(rndInt);
switch(switchInt) {
case 0:
mData.add(0,new NewsItem("Domino's Pizza","Sarıgöl, Ordu Cd. No:128, 34240 Gaziosmanpaşa/İstanbul",
R.drawable.dominos,"32 TL","30 dk.","0 TL","classDominos")); // I'm trying to catch that "classDominos" to use to switch Activity
break;
case 1:
mData.add(0,new NewsItem("Migros","Bağlarbaşı, Küçükköy Yolu Cd., 34245 Gaziosmanpaşa/İstanbul",
R.drawable.migroslogo,"32 TL","25 dk.","0 TL", "classDominos"));
break;
case 2:
mData.add(0,new NewsItem("KFC","Yeşilpınar Mah. Şehit Metinkaya Sok Vialand AVM No:11 Mağaza No:237, 34065 Eyüpsultan",
R.drawable.kfclogo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
case 3:
mData.add(0,new NewsItem("Popeyes","Yeşilpınar Mah. Şehit Metin Kaya Sok. No:11 K:3 Vialand AVM, 34065",
R.drawable.popeyeslogo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
case 4:
mData.add(0,new NewsItem("Mado","İslambey, Hz. Halid Blv. No:43 D:B, 34050 Eyüpsultan/İstanbul",
R.drawable.madologo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
default:
break;
}
System.out.println("Added item");
newsAdapter.notifyItemInserted(0);
NewsRecyclerView.getLayoutManager().smoothScrollToPosition(NewsRecyclerView, state, 0);
// Un-commenting the lines below crash the app when "Listing Restaurants" (Creating items)
//ibGoSellerPage = (ImageButton) findViewById(R.id.ibGoSellerPage);
/*ibGoSellerPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("ON CLICK HERE");
}
});
*/
}
}
I can see the individual buttons in the profiler but how to catch clicks on them? (You can see I'm holding the button on the right)
Profiler Screenshot
I think the problem with you is that the click event happen on the screen in another view
By making a transparent rectangle i think the click go to the parent view
Try to test that for ex:
<LinearLayout
android:id="#+id/layout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
handle the click on layout view if it work so you need to change the transparent rectangle button to a bold one or another approach
better to add some code from your side to help us understand the problem well

Fragments seem to be stacking on top of each other - causing problems, android

I've been pulling my hair out over this for the whole day, as I'm very new to fragments. Basically, I have a fragment in an app I have that keeps track of a player's currency. I want to reuse one fragment throughout the entire app, as it has references to a singleton class that stores the players currency and sets a TextView to display this currency.
The problem is that in every activity I initialize a new fragment when the activity starts, like so:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fmang2, new fragment1());
ft.commit();
this causes the fragments to stack, which is a problem because the fragments are constantly adding currency to the player's balance. So, if I have 3 created 3 activities, players will be receiving currency 3x as fast as they should be.
How do I fix this? I've tried creating fragments with XML too, but that doesn't help.
For reference, here is the code in my fragment:
package com.example.bunzclicker;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.example.bunzclicker.bunz.Bunz;
import java.math.BigDecimal;
import java.util.Timer;
import java.util.TimerTask;
public class fragment1 extends Fragment {
private TextView bunz_count;
private TextView money_count;
private Bunz bunz;
private Handler handler;
private HandlerThread mHandlerThread;
int delay = 1000;
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
bunz = Bunz.getInstance();
handler = new Handler();
view = inflater.inflate(R.layout.fragment1, container, false);
handler.postDelayed(new Runnable(){
public void run(){
update(view);
handler.postDelayed(this, delay);
}
}, delay);
return view;
}
public void update(View view){
bunz_count = (TextView) view.findViewById(R.id.final_bunz_count);
money_count = (TextView) view.findViewById(R.id.final_money_count);
//System.out.println(bunz.getBaker1());
BigDecimal number = ((BigDecimal.valueOf
(bunz.getBaker1()).multiply(BigDecimal.valueOf(.1))));
// ).add((BigDecimal.valueOf(bunz.getBaker2()).multiply(BigDecimal.valueOf(.2)))).
// add((BigDecimal.valueOf
// (bunz.getBaker3()).multiply(BigDecimal.valueOf(.4)))).
// add((BigDecimal.valueOf
// (bunz.getBaker4()).multiply(BigDecimal.valueOf(.8)))).
// add((BigDecimal.valueOf(bunz.getBaker5()).multiply(BigDecimal.valueOf(1)))).
// add((BigDecimal.valueOf(bunz.getBaker6()).multiply(BigDecimal.valueOf(2)))).
// add((BigDecimal.valueOf(bunz.getBaker7()).multiply(BigDecimal.valueOf(4)))).
// add((BigDecimal.valueOf(bunz.getBaker8()).multiply(BigDecimal.valueOf(5)))).
//add((BigDecimal.valueOf(bunz.getBaker9()).multiply(BigDecimal.valueOf(10))));
//System.out.println(number);
bunz.setBunz(bunz.getBunz().add((number)));
bunz_count.setText("Bunz: " + bunz.getBunz());
money_count.setText("Money: " + bunz.getMoney());
System.out.println("bunz" + bunz.getBunz());
}
}
Your Handler keeps posting update() even when the fragment has been put on pause, you should move the handler code to onResume() and use handler.removeCallbacksAndMessages(null) in onPause to prevent update() calls when the fragment is paused. You'll need to do something along the following lines,
#Override
public void onResume() {
super.onResume();
handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
update(view);
handler.postDelayed(this, delay);
}
}, delay);
}
#Override
public void onPause() {
handler.removeCallbacksAndMessages(null);
super.onPause();
}

Exchanging icons in listview items

I am trying to change icon image according to the item data . when pressing the icon, it should switch to other icon and change the item data. everything is going right but when i scroll up or down the new icon image change its place to some other items because i am using list view with adapter. how can i keep the new icons in the pressed items without mixing with other items.
package com.example.sairamkrishna.handymade;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class HandAdapter extends ArrayAdapter<HandClass> {
private int myColor;
public HandAdapter(Context context, ArrayList<HandClass> objects, int my_Color) {
super(context, 0, objects);
myColor = my_Color;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View myView = convertView;
final HandClass myData = getItem(position);
if (myView == null) {
myView = LayoutInflater.from(getContext()).inflate(
R.layout.label_item, parent, false);
}
ImageView aImage = (ImageView) myView.findViewById(R.id.itemImage);
aImage.setImageResource(myData.getClsImage());
TextView aName = (TextView) myView.findViewById(R.id.itemName);
aName.setText(myData.getClsName());
FrameLayout aColor = (FrameLayout) myView.findViewById(R.id.itemColor);
aColor.setBackgroundColor(myColor);
final ImageView aAddToBasket = (ImageView) myView.findViewById(R.id.itemAddToBasket);
aAddToBasket.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Boolean aClsToBasket = (Boolean) myData.getClsToBasket();
if (aClsToBasket) {
aAddToBasket.setImageResource(R.drawable.ic_add_circle);
myData.setClsToBasket(false);
Toast.makeText(getContext(), "Remove from basket"+ position, Toast.LENGTH_SHORT).show();
} else {
// if (!aClsToBasket) {
aAddToBasket.setImageResource(R.drawable.ic_remove_circle);
myData.setClsToBasket(true);
Toast.makeText(getContext(), "Add to basket"+ position, Toast.LENGTH_SHORT).show();
}
}
});
ImageView aAddToFavorite = (ImageView) myView.findViewById(R.id.itemAddToFavorite);
aAddToFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Favorite - List item was clicked at " + position, Toast.LENGTH_SHORT).show();
}
});
return myView;
}
}
A fundamental concept of ListView and RecyclerView is that you need to "update" the value (in this case, the image) for each portion of the row every time getView() or onBindViewHolder() is called.
For example, every time getView() is called, you're always updating the (text) value of TextView aName. That is, there is always a call to aName.setText().
Right now, the only time you call aAddToBasket.setImageResource() is inside an OnClickListener. Of course, it makes sense to do it here, but you must also update the image outside of the listener.
Add this code right after your ImageView aAddToBasket line:
if ((Boolean) myData.getClsToBasket()) {
aAddToBasket.setImageResource(R.drawable.ic_remove_circle);
} else {
aAddToBasket.setImageResource(R.drawable.ic_add_circle);
}
Add this line after icon change.
adapter.notifyDataSetChanged();

Save Text in textview after leaving activity

Is there a way for me to keep the entered text in the text view after leaving the activity?
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ClassDatabase extends AppCompatActivity {
TextView students;
TextView averages;
String studentNames;
String studentAvgs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_database);
students = findViewById(R.id.data);
averages = findViewById(R.id.avgs);
displays the intent;
displayIntent();
back to previous activity where u enter new text
BacktoAdd();
}
private void BacktoAdd(){
Button Back2Add = (Button) findViewById(R.id.backtoadd);
Back2Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ClassDatabase.this, Add.class));
}
});
}
adds new text to text view
private void displayIntent(){
studentNames = getIntent().getExtras().getString("class");
studentAvgs = getIntent().getExtras().getString("avg");
students.append(studentNames);
students.append(" \n");
averages.append(studentAvgs);
averages.append(" \n");
}
}
Currently it gets the text from the previous activity and appends the text to the textview but when I go back to the previous activity and repeat the actions the previous text wasn't saved
You can use SharedPreferences https://developer.android.com/training/data-storage/shared-preferences

Android Studio Coding [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My task is to convert an activity to a fragment.
I did some changes but it still doesn't work. I am missing something, but I can't figure it out. One problem I do see is that the public class QuoteFragment extends SingleFregmentActivity is underline...not sure what I forget to do. Help please!
When I wan converting the activity to a fragment what did I forget?
Code for the activity...
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.Intent;
/**
* Main activity for the application.
* Displays a series of quotes
*/
public class QuoteFragment extends SingleFragmentActivity{
/** Key for fact about author stored in Intent sent to AuthorFactActivity. */
public static final String EXTRA_AUTHOR_FACT =
"edu.andrews.cptr252.stephanien.quoteoftheday.author_fact";
private static final String KEY_QUOTE_INDEX = "quoteIndex";
/**ImageView used to display inspirational image*/
private ImageView mImageView;
private TextView mQuoteTextView;
private TextView mAuthorTextView;
private Button mNextButton;
/**Quotes used in app */
private Quote[] mQuoteList = new Quote[]{
new Quote(R.string.quote_text_0, R.string.quote_author_0,
R.string.author_fact_0, R.drawable.mountain_pic),
new Quote(R.string.quote_text_1, R.string.quote_author_1,
R.string.author_fact_1, R.drawable.lier),
new Quote(R.string.quote_text_2, R.string.quote_author_2,
R.string.author_fact_2, R.drawable.math),
new Quote(R.string.quote_text_3, R.string.quote_author_3,
R.string.author_fact_3, R.drawable.smiley),
new Quote(R.string.quote_text_4, R.string.quote_author_4,
R.string.author_fact_4, R.drawable.th),
};
/** Index of current quote in list */
private int mCurrentIndex = 0;
/** Launch activity to display author fact */
private void displayAuthorFact(){
//Create intent with name of class for second activity.
//This intent will be sent to the Activity Manager in the OS
//Which will launch the activity.
Intent i = new Intent(QuoteFragment.this, AuthorFactActivity.class);
//Add extra containing resource id for fact
i.putExtra(EXTRA_AUTHOR_FACT, mQuoteList[mCurrentIndex].getAuthorFact());
//Send the intent to the activity manager.
startActivity(i);
}
/**
* Remember the current quote when the activity is destroyed
* #param savedInstanceState Bundle used for saving identity of current quote
*/
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//Stored the index of the current quote in the bundle.
//Use our key to access the value later.
savedInstanceState.putInt(KEY_QUOTE_INDEX, mCurrentIndex);
}
/**
* Setup and inflate layout.
* #param savedInstanceState Previously saved Bundle
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.activity_fragment, container, false);
//mQuoteTextView.setText("This should generate an error. Do you see why?");
//Re-display the same quote we were on when activity destroyed
if(savedInstanceState != null){
mCurrentIndex = savedInstanceState.getInt(KEY_QUOTE_INDEX);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//Display that text for the quote
mQuoteTextView = (TextView) findViewById(R.id.quoteTextView);
int quote = mQuoteList[mCurrentIndex].getQuote();
mQuoteTextView.setText(quote);
mQuoteTextView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
displayAuthorFact();
}
});
//Display the author of the quote
mAuthorTextView = (TextView) findViewById(R.id.authorTextView);
int author = mQuoteList[mCurrentIndex].getAuthor();
mAuthorTextView.setText(author);
mAuthorTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayAuthorFact();
}
});
//Display image
mImageView = (ImageView) findViewById(R.id.imageView);
mImageView.setImageResource(R.drawable.mountain_pic);
//set up listener to handle next button presses
mNextButton = (Button) findViewById(R.id.nextButton);
mNextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// move to the next quote in the list
//if index reaches end array,
//reset index to zero (first quote)
mCurrentIndex++;
if(mCurrentIndex == mQuoteList.length){
mCurrentIndex = 0;
}
updateQuote();
}
});
return v;
}
/** Display the quote at the current index. */
private void updateQuote(){
int quote = mQuoteList[mCurrentIndex].getQuote();
int author = mQuoteList[mCurrentIndex].getAuthor();
int picture = mQuoteList[mCurrentIndex].getPicture();
mQuoteTextView.setText(quote);
mAuthorTextView.setText(author);
mImageView.setImageResource(picture);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quote, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Create QuoteFragment
Copy-paste code from QuoteActivity
Remove setContent(R.layout.activity_quote) and implement onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) method
Initialize views in onViewCreated (View view, Bundle savedInstanceState) method
Rename activity_quote.xml to fragment_quote.xml
Create xml file activity_quote.xml and add the QuoteFragment as a content:
<fragment android:name="com.example.android.fragments.QuoteFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
See details here: http://developer.android.com/training/basics/fragments/creating.html#AddInLayout
And remove all code from QuoteActivity except of:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quote);
}

Categories