【发布时间】:2014-10-05 19:42:57
【问题描述】:
我有一个包含三个项目的数组,例如:
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;
}
但它不起作用。
【问题讨论】:
-
你不能从数组中删除一个元素,它有一个固定的大小。你必须创建一个新的、更小的数组,然后复制你想要的元素。
-
@Keppil 为什么操作不能从数组中删除任何元素。 op 唯一需要做的就是根据已删除数组的索引向前或向后移动其他现有元素
-
说“它不起作用”并不能告诉我们您预期会发生什么或实际发生了什么。
标签: java android arrays arraylist