- 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/
reqwest v0.9 将 serde v1.0 作为依赖项,因此实现 converting serde_json errors into reqwest error . 在我的代码中,我使用 se
我有这个代码: let file = FileStorage { // ... }; file.write("Test", bytes.as_ref()) .map_err(|e| Mu
我只是尝试用angular-cli创建一个新项目,然后运行服务器,但是它停止并显示一条有趣的消息:Error: No errors。 我以这种方式更新了(希望有帮助):npm uninstall -g
我从我的 javascript 发送交易 Metamask 打开传输对话框 我确定 i get an error message in metamask (inpage.js:1 MetaMask -
这个问题在这里已经有了答案: How do you define custom `Error` types in Rust? (3 个答案) How to get a reference to a
我想知道两者之间有什么大的区别 if let error = error{} vs if error != nil?或者只是人们的不同之处,比如他们如何用代码表达自己? 例如,如果我使用这段代码: u
当我尝试发送超过 50KB 的图像时,我在 Blazor 服务器应用程序上收到以下错误消息 Error: Connection disconnected with error 'Error: Serv
我有一个error-page指令,它将所有异常重定向到错误显示页面 我的web.xml: [...] java.lang.Exception /vi
我有这样的对象: address: { "phone" : 888, "value" : 12 } 在 WHERE 中我需要通过 address.value 查找对象,但是在 SQL 中有函数
每次我尝试编译我的代码时,我都会遇到大量错误。这不是我的代码的问题,因为它在另一台计算机上工作得很好。我尝试重新安装和修复,但这没有帮助。这是整个错误消息: 1>------ Build starte
在我的代码的类部分,如果我写一个错误,则在不应该的情况下,将有几行报告为错误。我将'| error'放在可以从错误中恢复的良好/安全位置,但是我认为它没有使用它。也许它试图在某个地方恢复中间表情? 有
我遇到了 csv 输入文件整体读取故障的问题,我可以通过在 read_csv 函数中添加 "error_bad_lines=False" 来删除这些问题来解决这个问题。 但是我需要报告这些造成问题的文
在 Spring 中,验证后我们在 controller 中得到一个 BindingResult 对象。 很简单,如果我收到验证错误,我想重新显示我的表单,并在每个受影响的字段上方显示错误消息。 因此
我不知道出了什么问题,因为我用 Java 编程了大约一年,从来没有遇到过这个错误。在一分钟前在 Eclipse 中编译和运行工作,现在我得到这个错误: #A fatal error has been
SELECT to_char(messages. TIME, 'YYYY/MM/DD') AS FullDate, to_char(messages. TIME, 'MM/DD
我收到这些错误: AnonymousPath\Anonymized.vb : error BC30037: Character is not valid. AnonymousPath\Anonymiz
我刚刚安装了 gridengine 并在执行 qstat 时出现错误: error: commlib error: got select error (Connection refused) erro
嗨,我正在学习 PHP,我从 CRUD 系统开始,我在 Windows 上安装了 WAMP 服务器,当我运行它时,我收到以下错误消息。 SCREAM: Error suppression ignore
我刚刚开始一个新项目,我正在学习核心数据教程,可以找到:https://www.youtube.com/watch?v=zZJpsszfTHM 我似乎无法弄清楚为什么会抛出此错误。我有一个名为“Exp
当我使用 Jenkins 运行新构建时,出现以下错误: "FilePathY\XXX.cpp : fatal error C1853: 'FilePathZ\XXX.pch' precompiled
我是一名优秀的程序员,十分优秀!