Reputation: 342
I'm trying to make a listview maked with clicks on a button that includes favorites. This listview items are created with 1 image, title and subtitle.
My problem is this: It seems that when saving the values of the number of items that will be, it always take the value as 1, even though every time you click on the button (in the state to add) this variable is incremented and stored in a sharedpreferences.
Pasting important parts of the code:
List1 (fragment of activity Viewp)
public class List1 extends Fragment {
public String seleccion;
private Context context2;
private Activity act2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context2 = getActivity().getApplicationContext();
act2 = this.getActivity();
View visor = inflater.inflate(R.layout.activity_principal, container, false);
ListView lista = (ListView) visor.findViewById(R.id.listadirectivos);
ArrayList<Directivo> arraydir = new ArrayList<Directivo>();
Directivo directivo;
// Forma 1: Introduzco los datos por orden alfab�tico
/*directivo = new Directivo(getResources().getDrawable(R.drawable.abccountry), "ABC ", "Country");
arraydir.add(directivo);
directivo = new Directivo(getResources().getDrawable(R.drawable.abcjazz), "ABC ", "Jazz");
arraydir.add(directivo);*/
directivo = new Directivo(getResources().getDrawable(R.drawable.arrowclassicrock), "Arrow Classic Rock", "Rock");
arraydir.add(directivo);
directivo = new Directivo(getResources().getDrawable(R.drawable.canalfiesta), "Canal Fiesta", "Radio Party");
arraydir.add(directivo);
directivo = new Directivo(getResources().getDrawable(R.drawable.cadenadial), "Cadena Dial", "Radio General");
arraydir.add(directivo);
//........
// Creo el adapter personalizado
AdapterDirectivos adapter = new AdapterDirectivos(act2, arraydir);
// Lo aplico
lista.setAdapter(adapter);
lista.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
//Link con la radio: en general los que no van son MMS
String opcionSeleccionada =
((Directivo)a.getAdapter().getItem(position)).getNombre();
/*if (opcionSeleccionada == "ABC ") { //no va
seleccion = "mms://a952.l11289754951.c112897.g.lm.akamaistream.net/D/952/112897/v0001/reflector:54951";
}
else if (opcionSeleccionada == "ABC ") { //no va
seleccion = "mms://a134.l11289752133.c112897.g.lm.akamaistream.net/D/134/112897/v0001/reflector:52133";
}*/
if (opcionSeleccionada == "Arrow Classic Rock") { //va
seleccion = "http://91.221.151.155";
}
else if (opcionSeleccionada == "Canal Fiesta") { //va
seleccion = "http://195.55.74.207/rtva/canalfiestaradio_master.mp3?GKID=3bfcb56203a811e4a80500163e914f69";
}
else if (opcionSeleccionada == "Cadena Dial") { //va
seleccion = "http://194.169.201.177:8085/liveDial.mp3";
}
//............
Intent i = new Intent(context2, Radio.class);
i.putExtra("seleccion", seleccion);
i.putExtra("opcionSeleccionada", opcionSeleccionada);
startActivity(i);
}
});
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) visor.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
return visor;
}
}
//"opcionSeleccionada" is the name of the title of one of the items of the ListView (used to the creation of the listview after that) and "selecction" is not important here
Radio (activity)
public class Radio extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private int j=0;
private int i=0;
private String TAG = getClass().getSimpleName();
private MediaPlayer mp = null;
private boolean dejaractivado=false;
private Button play;
private ToggleButton favs;
private Button stop;
private TextView textView;
boolean prevencion = false;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.TextView1);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
favs = (ToggleButton) findViewById(R.id.favs);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
favs.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(favs.isChecked()) {
addfavs();
}
else {
delfavs();
}
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
stop();
}
});
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
private void play() {
Bundle bundle=getIntent().getExtras();
prevencion = true;
textView.setText("Conectando con la radio......");
Uri myUri = Uri.parse(bundle.getString("seleccion"));
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
@Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
textView.setText("");
/* String aux = (String) MediaStore.Audio.Media.ARTIST;
textView.setText("Estas escuchando: "+aux);
textView.setText("");*/
j=1;
}
private void addfavs() {
i++;
//Toast toast = Toast.makeText(getApplicationContext(), "Bien, metido", Toast.LENGTH_SHORT);
//toast.show();
Bundle bundle=getIntent().getExtras();
String str = bundle.getString("opcionSeleccionada"); // str = Nombre Radio
//String str2= wmbPreference.getString("opcionSeleccionada",str);
SharedPreferences shared = getSharedPreferences("guardar", 0);
SharedPreferences.Editor editor = shared.edit();
editor.putString("opcionSeleccionada"+i, str);
editor.remove("Status_size");
editor.putInt("Status_size", i);
editor.commit();// commit is important here.
}
private void delfavs() {
//it is a prototype:
SharedPreferences shared = getSharedPreferences("guardar", 0);
SharedPreferences.Editor editor = shared.edit();
editor.remove("opcionSeleccionada"+i);
editor.commit();// commit is important here.
//String channel = (shared.getString("opcionSeleccionada", ""));
//Toast toast = Toast.makeText(getApplicationContext(), channel, Toast.LENGTH_SHORT);
//toast.show();
//Toast toast = Toast.makeText(getApplicationContext(), "Mal, sacado", Toast.LENGTH_SHORT);
//toast.show();
}
private void stop() {
if(j==1) {
textView.setText("");
mp.stop();
}
}
public void onDestroy() {
textView.setText("");
super.onDestroy();
stop();
}
@Override
public void onStop() {
textView.setText("");
super.onStop();
if(dejaractivado==false) { }
else {
stop();
}
}
public void onCompletion(MediaPlayer mp) {
stop();
}
("i" is the value of the favourite items, and "opcionSeleccionadai" is the string name title of each item)
Viewp (activity)
public class Viewp extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private Context context = this;
String[] channel = new String[100];
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager);
// Initilization
/*context.getSharedPreferences("guardar", 0);
SharedPreferences shared = getSharedPreferences("guardar", 0);
i = shared.getInt("Status_size", 0);
for(int s=1;s<=i;s++) {
channel[s] = (shared.getString("opcionSeleccionada"+s, ""));
}*/
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
actionBar.addTab(actionBar.newTab().setText(getResources().getString(R.string.emisoras))
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(getResources().getString(R.string.estilo))
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(getResources().getString(R.string.favoritos))
.setTabListener(this));
/* for (int w=0; w<tabs.length-1; w++) {
actionBar.addTab(actionBar.newTab().setText(tabs[w])
.setTabListener(this));
}*/
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onResume(){
super.onResume();
context.getSharedPreferences("guardar", 0);
SharedPreferences shared = getSharedPreferences("guardar", 0);
i = shared.getInt("Status_size", 0); //i siempre da 1
for(int j=0; j<i; j++) {
channel[j] = shared.getString("opcionSeleccionada"+j, "");
}
}
}
here, I load the values saved in the other class
List3 (fragment of Viewp)
public class List3 extends Fragment {
public String seleccion;
private Context context;
private Activity act;
private String[] myValue;
private int y=0;
private boolean primeravez=true;
//private TextView estilo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_principal3, container, false);
context = getActivity().getApplicationContext();
act = this.getActivity();
Directivo directivo;
ArrayList<Directivo> arraydir2 = new ArrayList<Directivo>();
AdapterDirectivos2 adapter2 = new AdapterDirectivos2(act, arraydir2);
Viewp viewp = (Viewp)getActivity();
myValue = new String[viewp.channel.length];
for (int k=0; k<myValue.length; k++) {
myValue[k]=viewp.channel[k];
}
for(int i=0; i<myValue.length;i++) {
if(myValue[i]!=null) {
if (myValue[i].equals("Esencia Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.esenciaradio), "Esencia Radio", "Radio General");
else if (myValue[i].equals("I love FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.ilovefm), "I Love FM", "Radio General");
else if (myValue[i].equals("Los 40 Principales"))
adapter2.addItem(getResources().getDrawable(R.drawable.los40principales), "Los 40 Principales", "Radio General");
else if (myValue[i].equals("RAC 105"))
adapter2.addItem(getResources().getDrawable(R.drawable.rac105), "RAC 105", "Radio General");
else if (myValue[i].equals("Sky FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.skyfm), "Sky FM", "Radio General");
else if (myValue[i].equals("Styl FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.stylfm), "Styl FM", "Radio General");
else if (myValue[i].equals("Cocktelera Blues"))
adapter2.addItem(getResources().getDrawable(R.drawable.cocktelerablues), "Cocktelera Blues", "General Blues");
else if (myValue[i].equals("Q fm"))
adapter2.addItem(getResources().getDrawable(R.drawable.qfm), "Q fm", "Jazz/Soul/Blues/Funky");
else if (myValue[i].equals("Radio Clásica RNE"))
adapter2.addItem(getResources().getDrawable(R.drawable.radioclasicarne), "Radio Clásica RNE", "Música Clásica");
else if (myValue[i].equals("Koffee FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.koffeeradio), "Koffee FM", "Chill out");
else if (myValue[i].equals("Ibiza Global Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.ibizaglobalradio), "Ibiza Global Radio", "House/Dance/Electrónica");
else if (myValue[i].equals("Maxima FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.maximafm), "Maxima FM", "Dance/Música Electrónica");
else if (myValue[i].equals("Cadena Latino"))
adapter2.addItem(getResources().getDrawable(R.drawable.cadenalatino), "Cadena Latino", "Latino/Flamenco");
else if (myValue[i].equals("Chanquete FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.chanquetefm), "Chanquete FM", "Flamenco");
else if (myValue[i].equals("Flamenco Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.flamencoradio), "Flamenco Radio", "Flamenco");
else if (myValue[i].equals("HotMix Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.hotmixradiofunky), "HotMix Radio Funky", "Funky Mix");
else if (myValue[i].equals("Sublime FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.sublimefm), "Sublime FM", "Jazz/Soul/Funk/Lounge");
else if (myValue[i].equals("Mix Radio House"))
adapter2.addItem(getResources().getDrawable(R.drawable.mixradiohouse), "Mix Radio House", "House");
else if (myValue[i].equals("Jazz Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.jazzradio), "Jazz Radio", "Jazz");
else if (myValue[i].equals("SmoothJazz Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.smoothjazz), "SmoothJazz Radio", "Smooth Jazz");
else if (myValue[i].equals("Canal Fiesta"))
adapter2.addItem(getResources().getDrawable(R.drawable.canalfiesta), "Canal Fiesta", "Pop");
else if (myValue[i].equals("Sky FM "))
adapter2.addItem(getResources().getDrawable(R.drawable.skyfmreggae), "Sky FM ", "Reggae");
else if (myValue[i].equals("Arrow Classic Rock"))
adapter2.addItem(getResources().getDrawable(R.drawable.arrowclassicrock), "Arrow Classic Rock", "Rock");
else if (myValue[i].equals("HotMix Radio Rock"))
adapter2.addItem(getResources().getDrawable(R.drawable.hotmixradiorock), "HotMix Radio Rock", "Rock");
else if (myValue[i].equals("Rock FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.rockfm), "Rock FM", "Rock");
else if (myValue[i].equals("Rock FM Classic"))
adapter2.addItem(getResources().getDrawable(R.drawable.rockfmbelgie), "Rock FM Classic", "Classic Rock");
else if (myValue[i].equals("Virgin Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.virginradio), "Virgin Radio", "Rock/Hard-Rock");
else if (myValue[i].equals("Trance FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.trancefm), "Trance FM", "Trance");
else if (myValue[i].equals("M80 Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.m80radio), "M80 Radio", "Best of 70s/80s/90s");
}
}
But, the Vector of strings myValue[], like channel[], it seems that only have 1 position and the other values of they are null. Because of this, I thought that in one moment of all the process the "i or Status_size" value is redeclared or something rare happens.
Upvotes: 0
Views: 367
Reputation: 2456
First I am going to assume that channel[] is really private String channel[]
You should really post all related code including all initializations declarations of all arrays because at this point i do not know the size of your channel array.
i = shared.getInt("Status_size", 0); //i siempre da 1
channel[i] = (shared.getString("opcionSeleccionada"+i, ""));
In the code above you are stated that you are loading all of the values from the the previous activity. But this code only loads 1 value. It loads the string at key "opcionSeleccionada"+i
into the position i
of the channel array. So if this is the only place where you are filling the channel array then it will only ever have 1 value in it.
To fix this you need a loop like you did in the fragment to fill the array with the proper values from the shared preference map
for(int j=0; j < i; j++) {
channel[j] = shared.getString("opcionSeleccionada"+j, "");
}
inside addFavs() do this
private void addfavs() {
SharedPreferences shared = getSharedPreferences("guardar", 0);
int i = shared.getInt("Status_size", 0);
i++;
//Toast toast = Toast.makeText(getApplicationContext(), "Bien, metido", Toast.LENGTH_SHORT);
//toast.show();
Bundle bundle=getIntent().getExtras();
String str = bundle.getString("opcionSeleccionada"); // str = Nombre Radio
//String str2= wmbPreference.getString("opcionSeleccionada",str);
SharedPreferences.Editor editor = shared.edit();
editor.putString("opcionSeleccionada"+i, str);
//you do not need to remove a value from shared preferences. If you use the same key then it gets overridden
//editor.remove("Status_size");
editor.putInt("Status_size", i);
editor.commit();// commit is important here.
}
You can remove i
as a member variable and make sure you set it the same way in deleteFavs method
Upvotes: 1
Reputation:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("MYLABEL", "myStringToSave").commit();
Upvotes: 0