这里我使用带有 mysql 数据库的 Android。我已经创建了表,并且还将值存储到数据库中。它也显示在 ListView 中,但是当我尝试单击 ListView 中的项目时。它不会去其他 Activity 。请帮帮我。
这是我在适配器中的代码
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_entries, null, true);
TextView tvTitleEntry = listViewItem.findViewById(R.id.tvTitleEntry);
TextView tvCityEntry = listViewItem.findViewById(R.id.tvCityEntry);
final Entry entry = entryList.get(position);
tvTitleEntry.setText(entry.getTitle());
tvCityEntry.setText(entry.getCity());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String title = ((TextView) view).getText().toString();
Intent i = new Intent(getApplicationContext(), ViewEntry.class);
i.putExtra("title", title);
startActivity(i);
}
});
return listViewItem;
}
}
另一个 Activity (ViewEntry 类)代码
TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
Intent i = getIntent();
String title = i.getStringExtra("title");
tvTitle.setText(title);
日志猫
java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
at com.example.arko.torranboapplicationentry.EntriesActivity$EntryAdapter$1.onItemClick(EntriesActivity.java:125)
at android.widget.AdapterView.performItemClick(AdapterView.java:305)
at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3057)
at android.widget.AbsListView$3.run(AbsListView.java:3864)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
我该如何解决这个问题?
最佳答案
String title = ((TextView) view).getText().toString();
在这一行中,您尝试将 ListView 项的 View 转换为 TextView ,这会引发异常。
将其更改为onclicklistener,并从 ListView 项的 View 中获取textview
listViewItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = ((TextView)v.findViewById(R.id.tvTitleEntry)).getText().toString();
Intent i = new Intent(getApplicationContext(), ViewEntry.class);
i.putExtra("title", title);
context.startActivity(i);
}
});
关于android - 如何将存储在数据库中的 Listview 中的值获取到另一个 Activity ?使用Android和Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48635966/