- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在开发 listview 应用程序,在此 Activity 中我使用了一个搜索框,但是当我在搜索框中输入文本时,出现错误 Java.lang.Classcast Exception: java.lang.String cannot be cast to
Activity
public class ConnectActivity extends Activity {
// unsorted list items
List<Company> mItems;
// array list to store section positions
ArrayList<Integer> mListSectionPos;
// array list to store listView data
ArrayList<String> mListItems;
// custom list view with pinned header
PinnedHeaderListView mListView;
// custom adapter
PinnedHeaderAdapter mAdaptor;
// search box
EditText mSearchView;
// loading view
ProgressBar mLoadingView;
// empty view
TextView mEmptyView;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.activity_open_translate,
R.anim.activity_close_scale);
// UI elements
setupViews();
mListSectionPos = new ArrayList<Integer>();
mListItems = new ArrayList<String>();
// for handling configuration change
if (savedInstanceState != null) {
mListItems = savedInstanceState.getStringArrayList("mListItems");
mListSectionPos = savedInstanceState
.getIntegerArrayList("mListSectionPos");
if (mListItems != null && mListItems.size() > 0
&& mListSectionPos != null && mListSectionPos.size() > 0) {
setListAdaptor();
}
String constraint = savedInstanceState.getString("constraint");
if (constraint != null && constraint.length() > 0) {
mSearchView.setText(constraint);
setIndexBarViewVisibility(constraint);
}
} else {
new Poplulate().execute(mItems);
}
}
@Override
protected void onPause() {
super.onPause();
// closing transition animations
overridePendingTransition(R.anim.activity_open_scale,
R.anim.activity_close_translate);
}
private void setupViews() {
setContentView(R.layout.activity_connect);
mSearchView = (EditText) findViewById(R.id.search_view);
mLoadingView = (ProgressBar) findViewById(R.id.loading_view);
mListView = (PinnedHeaderListView) findViewById(R.id.list_view);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView selectedCompanyName = (TextView) view.findViewById(R.id.row_title);
Toast.makeText(getApplicationContext(), selectedCompanyName.getText().toString(), Toast.LENGTH_SHORT).show();
Company selectedCopmanyData = new Select().from(Company.class).where("Company_Name = ?", selectedCompanyName.getText().toString().trim()).executeSingle();
startActivity(new Intent(ConnectActivity.this, CompanyActivity.class).putExtra("SELECTED_COMPANY", selectedCopmanyData));
}
});
mEmptyView = (TextView) findViewById(R.id.empty_view);
//mItems = new Select().from(Company.class).where("Bookmark = ?", true).orderBy("Company_Name ASC").execute();
mItems = new Select().from(Company.class).orderBy("Company_Name ASC").execute();
if (mItems.size() == 0) {
Company sampleData1 = new Company();
sampleData1.companyName = "MahenCO";
sampleData1.companyId = new Long(new SimpleDateFormat("ddMMyyyyHHmmSS").format(new Date()));
sampleData1.groupId = new Integer(1);
sampleData1.groupName = "Finance";
sampleData1.customerSupportNo = "12345678";
sampleData1.customerWebSite = "http://www.mahenco.com";
sampleData1.customerSupportEmail = "customersupport@mahenco.com";
sampleData1.bookmarked = false;
sampleData1.save();
Company sampleData2 = new Company();
sampleData2.companyName = "ECG Ltd";
sampleData2.companyId = new Long(new SimpleDateFormat("ddMMyyyyHHmmSS").format(new Date()));
sampleData2.groupId = new Integer(1);
sampleData2.groupName = "Insurance";
sampleData2.customerSupportNo = "18002666";
sampleData2.customerWebSite = "http://www.ecg.com";
sampleData2.customerSupportEmail = "customersupport@ecg.com";
sampleData2.bookmarked = true;
sampleData2.save();
mItems = new Select().from(Company.class).orderBy("Company_Name ASC").execute();
}
}
// I encountered an interesting problem with a TextWatcher listening for
// changes in an EditText.
// The afterTextChanged method was called, each time, the device orientation
// changed.
// An answer on Stackoverflow let me understand what was happening: Android
// recreates the activity, and
// the automatic restoration of the state of the input fields, is happening
// after onCreate had finished,
// where the TextWatcher was added as a TextChangedListener.The solution to
// the problem consisted in adding
// the TextWatcher in onPostCreate, which is called after restoration has
// taken place
//
// http://stackoverflow.com/questions/6028218/android-retain-callback-state-after-configuration-change/6029070#6029070
// http://stackoverflow.com/questions/5151095/textwatcher-called-even-if-text-is-set-before-adding-the-watcher
@Override
protected void onPostCreate(Bundle savedInstanceState) {
mSearchView.addTextChangedListener(filterTextWatcher);
super.onPostCreate(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.connect, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onOptionsMenuClosed(Menu menu) {
openOptionsMenu();
}
private void setListAdaptor() {
// create instance of PinnedHeaderAdapter and set adapter to list view
mAdaptor = new PinnedHeaderAdapter(this, mListItems, mListSectionPos);
mListView.setAdapter(mAdaptor);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
// set header view
View pinnedHeaderView = inflater.inflate(R.layout.section_row_view,
mListView, false);
mListView.setPinnedHeaderView(pinnedHeaderView);
// set index bar view
IndexBarView indexBarView = (IndexBarView) inflater.inflate(
R.layout.index_bar_view, mListView, false);
indexBarView.setData(mListView, mListItems, mListSectionPos);
mListView.setIndexBarView(indexBarView);
// set preview text view
View previewTextView = inflater.inflate(R.layout.preview_view,
mListView, false);
mListView.setPreviewView(previewTextView);
// for configure pinned header view on scroll change
mListView.setOnScrollListener(mAdaptor);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
String str = s.toString();
if (mAdaptor != null && str != null)
mAdaptor.getFilter().filter(str);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};
然后我进入了我的 listFilter。这是过滤器类
public class ListFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
// NOTE: this function is *always* called from a background thread,
// and
// not the UI thread.
String constraintStr = constraint.toString().toLowerCase(
Locale.getDefault());
FilterResults result = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
ArrayList<String> filterItems = new ArrayList<String>();
synchronized (this) {
for (int i = 0; i < mItems.size(); i++) {
String item = mItems.get(i).companyName;
if (item.toLowerCase(Locale.getDefault()).startsWith(
constraintStr)) {
filterItems.add(item);
}
}
result.count = filterItems.size();
result.values = filterItems;
}
} else {
synchronized (this) {
result.count = mItems.size();
result.values = mItems;
}
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
List<Company> filtered = (List<Company>) results.values;
setIndexBarViewVisibility(constraint.toString());
// sort array and extract sections in background Thread
new Poplulate().execute(filtered);
}
}
private void setIndexBarViewVisibility(String constraint) {
// hide index bar for search results
if (constraint != null && constraint.length() > 0) {
mListView.setIndexBarVisibility(false);
} else {
mListView.setIndexBarVisibility(true);
}
}
// sort array and extract sections in background Thread here we use
// AsyncTask
private class Poplulate extends AsyncTask<List<Company>, Void, Void> {
private void showLoading(View contentView, View loadingView,
View emptyView) {
contentView.setVisibility(View.GONE);
loadingView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
}
private void showContent(View contentView, View loadingView,
View emptyView) {
contentView.setVisibility(View.VISIBLE);
loadingView.setVisibility(View.GONE);
emptyView.setVisibility(View.GONE);
}
private void showEmptyText(View contentView, View loadingView,
View emptyView) {
contentView.setVisibility(View.GONE);
loadingView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}
@Override
protected void onPreExecute() {
// show loading indicator
showLoading(mListView, mLoadingView, mEmptyView);
super.onPreExecute();
}
@Override
protected Void doInBackground(List<Company>... params) {
mListItems.clear();
mListSectionPos.clear();
List<Company> items = params[0];
if (mItems.size() > 0) {
// NOT forget to sort array
// No need for sort as it has already sorted while feathing from database
//Collections.sort(items.);
int i = 0;
String prev_section = "";
while (i < items.size()) {
String current_item = items.get(i).companyName;
String current_section = current_item.substring(0, 1)
.toUpperCase(Locale.getDefault());
if (!prev_section.equals(current_section)) {
mListItems.add(current_section);
mListItems.add(current_item);
// array list of section positions
mListSectionPos
.add(mListItems.indexOf(current_section));
prev_section = current_section;
} else {
mListItems.add(current_item);
}
i++;
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (!isCancelled()) {
if (mListItems.size() <= 0) {
showEmptyText(mListView, mLoadingView, mEmptyView);
} else {
setListAdaptor();
showContent(mListView, mLoadingView, mEmptyView);
}
}
super.onPostExecute(result);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mListItems != null && mListItems.size() > 0) {
outState.putStringArrayList("mListItems", mListItems);
}
if (mListSectionPos != null && mListSectionPos.size() > 0) {
outState.putIntegerArrayList("mListSectionPos", mListSectionPos);
}
String searchText = mSearchView.getText().toString();
if (searchText != null && searchText.length() > 0) {
outState.putString("constraint", searchText);
}
super.onSaveInstanceState(outState);
}
}
提前致谢......
这段代码被Mr. Bhavy mehta采纳在github上
这是我的日志猫
FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to
at
我也更新了我的日志猫
最佳答案
这里的问题在于performFiltering。
您已在该方法中将 filterItems 定义为
ArrayList<String> filterItems = new ArrayList<String>()
然后您将过滤项添加到过滤结果中,如下所示:
result.count = filterItems.size();
result.values = filterItems;
(其中结果是 FilterResults 类型)。
但是,稍后您将 filterResults 中的值强制转换为 publishResults 中的 List
List<Company> filtered = (List<Company>) results.values;
这会导致doInBackground中出现运行时异常,当运行时系统发现你传递给它的对象,声称是一个List
您的问题的解决方案是将 filterItems 更改为公司列表,而不是字符串,并在公司名称与 performFiltering 内循环中的 constraintStr 匹配时向其添加 mItems[i] 元素。
例如:
protected FilterResults performFiltering(CharSequence constraint) {
// NOTE: this function is *always* called from a background thread,
// and
// not the UI thread.
String constraintStr = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
ArrayList<Company> filterItems = new ArrayList<Company>();
synchronized (this) {
for (int i = 0; i < mItems.size(); i++) {
Company company=mItems.get(i);
String companyName= company.companyName;
if (companyName.toLowerCase().startsWith(constraintStr)) {
filterItems.add(company);
}
}
result.count = filterItems.size();
result.values = filterItems;
}
} else {
synchronized (this) {
result.count = mItems.size();
result.values = mItems;
}
}
return result;
}
关于Java.lang.Classcast Exception : java. lang.String cannot be cast to error in android 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25728006/
关闭。这个问题是off-topic .它目前不接受答案。 想要改进这个问题? Update the question所以它是on-topic用于堆栈溢出。 关闭 12 年前。 Improve thi
我有一个动态网格,其中的数据功能需要正常工作,这样我才能逐步复制网格中的数据。假设在第 5 行中,我输入 10,则从第 6 行开始的后续行应从 11 开始读取,依此类推。 如果我转到空白的第一行并输入
我有一个关于我的按钮消失的问题 我已经把一个图像作为我的按钮 用这个函数动画 function example_animate(px) { $('#cont
我有一个具有 Facebook 连接和经典用户名/密码登录的网站。目前,如果用户单击 facebook_connect 按钮,系统即可运行。但是,我想将现有帐户链接到 facebook,因为用户可以选
我有一个正在为 iOS 开发的应用程序,该应用程序执行以下操作 加载和设置注释并启动核心定位和缩放到位置。 map 上有很多注释,从数据加载不会花很长时间,但将它们实际渲染到 map 上需要一段时间。
我被推荐使用 Heroku for Ruby on Rails 托管,到目前为止,我认为我真的会喜欢它。只是想知道是否有人可以帮助我找出问题所在。 我按照那里的说明在该网站上创建应用程序,创建并提交
我看过很多关于 SSL 错误的帖子和信息,我自己也偶然发现了一个。 我正在尝试使用 GlobalSign CA BE 证书通过 Android WebView 访问网页,但出现了不可信错误。 对于大多
我想开始使用 OpenGL 3+ 和 4,但我在使用 Glew 时遇到了问题。我试图将 glew32.lib 包含在附加依赖项中,并且我已将库和 .dll 移动到主文件夹中,因此不应该有任何路径问题。
我已经盯着这两个下载页面的源代码看了一段时间,但我似乎找不到问题。 我有两个下载页面,一个 javascript 可以工作,一个没有。 工作:http://justupload.it/v/lfd7不是
我一直在使用 jQuery,只是尝试在单击链接时替换文本字段以及隐藏/显示内容项。它似乎在 IE 中工作得很好,但我似乎无法让它在 FF 中工作。 我的 jQuery: $(function() {
我正在尝试为 NDK 编译套接字库,但出现以下两个错误: error: 'close' was not declared in this scope 和 error: 'min' is not a m
我正在使用 Selenium 浏览器自动化框架测试网站。在测试过程中,我切换到特定的框架,我们将其称为“frame_1”。后来,我在 Select 类中使用了 deselectAll() 方法。不久之
我正在尝试通过 Python 创建到 Heroku PostgreSQL 数据库的连接。我将 Windows10 与 Python 3.6.8 和 PostgreSQL 9.6 一起使用。 我从“ht
我有一个包含 2 列的数据框,我想根据两列之间的比较创建第三列。 所以逻辑是:第 1 列 val = 3,第 2 列 val = 4,因此新列值什么都没有 第 1 列 val = 3,第 2 列 va
我想知道如何调试 iphone 5 中的 css 问题。 我尝试使用 firelite 插件。但是从纵向旋转到横向时,火石占据了整个屏幕。 有没有其他方法可以调试 iphone 5 中的 css 问题
所以我有点难以理解为什么这不起作用。我正在尝试替换我正在处理的示例站点上的类别复选框。我试图让它做以下事情:未选中时以一种方式出现,悬停时以另一种方式出现(选中或未选中)选中时以第三种方式出现(而不是
Javascript CSS 问题: 我正在使用一个文本框来写入一个 div。我使用以下 javascript 获取文本框来执行此操作: function process_input(){
你好,我很难理解 P、NP 和多项式时间缩减的主题。我试过在网上搜索它并问过我的一些 friend ,但我没有得到任何好的答案。 我想问一个关于这个话题的一般性问题: 设 A,B 为 P 中的语言(或
你好,我一直在研究 https://leetcode.com/problems/2-keys-keyboard/并想到了这个动态规划问题。 您从空白页上的“A”开始,完成后得到一个数字 n,页面上应该
我正在使用 Cocoapods 和 KIF 在 Xcode 服务器上运行持续集成。我已经成功地为一个项目设置了它来报告每次提交。我现在正在使用第二个项目并收到错误: Bot Issue: warnin
我是一名优秀的程序员,十分优秀!