Reputation: 137
I have an array which contains three items, for example:
title_list = new String[] { title1, title2, title3 };
These values are coming from SharedPreferences
. I would like to check so that if any of these values are empty they should be removed from the array.
For example, if the value of title1
is coming from another activity and is null
, then title1
should be removed and the array will be String[] { title2, title3 }
.
Here is my code:
package com.example.e_services;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class FavList extends Activity {
// Declare Variables
ListView list;
FavListViewAdapter adapter;
String[] rank;
String[] link;
String[] population;
String title1, title2;
String link1, link2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main2);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
title1 = prefs.getString("title1", ""); //no id: default value
title2 = prefs.getString("title2", ""); //no id: default value
link1 = prefs.getString("link1", ""); //no id: default value
link2 = prefs.getString("link2", ""); //no id: default value
if (title1.length() == 0){
rank[0] = null;
}
// Generate sample data into string arrays
rank = new String[] { title1, title2, "title3" };
link = new String[] { link1, link2 };
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
adapter = new FavListViewAdapter(this, rank);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Capture ListView item click
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(FavList.this, WebsiteView.class);
// Pass all data rank
i.putExtra("Link", link);
i.putExtra("position", position);
//Toast.makeText(getBaseContext(), "link "+link1,Toast.LENGTH_SHORT).show();
startActivity(i);
}
});
}
}
I tried to use
if (title1.length() == 0 ){
title_list[0] = null;
}
but it did not work.
Upvotes: 1
Views: 5216
Reputation: 1503964
You can't remove an element from an existing array - once you have created an array, its length is fixed. You can replace elements, but you can't add or remove them.
Options:
Change the value of the variable to refer to a new list, e.g.
title_list = new String[] { title_list[1], title_list[2] };
Use a List<String>
instead, using something like an ArrayList<String>
as the implementation
Upvotes: 3