我有一个包含三个项目的数组,例如:
title_list = new String[] { title1, title2, title3 };
这些值来自SharedPreferences
。我想检查一下,如果这些值中的任何一个为空,则应从阵列中删除它们。
例如,如果title1
的值来自其他活动并且为null
,那么应删除title1
并且数组将为String[] { title2, title3 }
。
这是我的代码:
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);
}
});
}
}
我尝试使用
if (title1.length() == 0 ){
title_list[0] = null;
}
但它不起作用。
答案 0 :(得分:3)
您无法从现有数组中删除元素 - 一旦创建了数组,其长度就固定了。您可以替换元素,但不能添加或删除它们。
选项:
更改变量的值以引用新列表,例如
title_list = new String[] { title_list[1], title_list[2] };
使用List<String>
代替ArrayList<String>
作为实施