应用正在打开查看秒钟,然后崩溃。 我正在尝试从firebase中获取值并使用checkbox在listview中显示.firebase包含我正在获取的三个值。 我从ListViewCheckboxesActivity添加时的值 像这样手动
ArrayList<States> stateList = new ArrayList<States>();
States _states = new States("10","BHAWARKUA",false);
stateList.add(_states);
logcat错误: ListViewCheckboxesActivity $ 1无法转换为android.content.Context
Logcat错误:
Process: com.example.listview1, PID: 22931
java.lang.ClassCastException:
com.example.listview1.ListViewCheckboxesActivity$1 cannot be cast to android.content.Context
at com.example.listview1.ListViewCheckboxesActivity$MyCustomAdapter.<init>(ListViewCheckboxesActivity.java:135)
at com.example.listview1.ListViewCheckboxesActivity$1.onChildAdded(ListViewCheckboxesActivity.java:55)
at com.google.android.gms.internal.firebase_database.zzbt.zza(Unknown Source:71)
at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source:2)
at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source:71)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:6651)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
States.java
public class States
{
String code = null;
String name = null;
boolean selected = false;
public States(String code, String name, boolean selected)
{
super();
this.code = code;
this.name = name;
this.selected = selected;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isSelected()
{
return selected;
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
}
ListViewCheckboxesActivity.java
public class ListViewCheckboxesActivity extends Activity
{
MyCustomAdapter dataAdapter = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<States> stateList = new ArrayList<States>();
final FirebaseDatabase firebaseDatabase=
FirebaseDatabase.getInstance();
DatabaseReference DatabaseReference =
firebaseDatabase.getReference();
DatabaseReference databaseReference=
DatabaseReference.child("ComingStudents");
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
databaseReference.addChildEventListener(new ChildEventListener()
{
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {States
value=dataSnapshot.child("stops").child("bhavarkuan")
.getValue(States.class);
stateList.add(value);
dataAdapter = new
MyCustomAdapter(this,R.layout.state_info, stateList);
ListView listView = findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new
OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View
view, int position, long id)
{
// When clicked, show a toast with the TextView
text
States state = (States)
parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),"Clicked
on Row: " + state.getName(),
Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
checkButtonClick();
}
private class MyCustomAdapter extends ArrayAdapter<States>
{
private ArrayList<States> stateList;
public MyCustomAdapter( ChildEventListener childEventListener,
int textViewResourceId, ArrayList<States> stateList)
{ super((Context) childEventListener, textViewResourceId,
stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
}
private class ViewHolder
{
TextView code;
CheckBox name;
}
@Override
public View getView(int position, View convertView, ViewGroup
parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.state_info, null);
holder = new ViewHolder();
holder.code = (TextView)
convertView.findViewById(R.id.code);
holder.name = (CheckBox)
convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new
View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
States _state = (States) cb.getTag();
Toast.makeText(getApplicationContext(), "Clicked
on Checkbox: " + cb.getText() + " is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
_state.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
States state = stateList.get(position);
holder.code.setText(" (" + state.getCode() + ")");
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());
holder.name.setTag(state);
return convertView;
}
}
private void checkButtonClick()
{
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<States> stateList = dataAdapter.stateList;
for(int i=0;i<stateList.size();i++)
{
States state = stateList.get(i);
if(state.isSelected())
{
responseText.append("\n" + state.getName());
}
}
Toast.makeText(getApplicationContext(),
responseText, Toast.LENGTH_LONG).show();
}
});
}
}
xmls:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#ffeeeeee">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="Available Stops" android:textSize="20sp" />
<Button android:id="@+id/findSelected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select your stops" />
<ListView android:id="@+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
state_info.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip">
<CheckBox android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:textColor="#ff00bb88"
android:focusableInTouchMode="false"
android:text="checkbox" />
<TextView android:id="@+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/checkBox1"
android:layout_alignBottom="@id/checkBox1"
android:layout_toRightOf="@id/checkBox1"
android:text="textview"
android:textColor="#ff000000"/>
</RelativeLayout>
答案 0 :(得分:0)
您可以更改适配器构造器吗
MyCustomAdapter( ChildEventListener childEventListener, int textViewResourceId, ArrayList<States> stateList)
到
MyCustomAdapter( ListViewCheckboxesActivity activity, int textViewResourceId, ArrayList<States> stateList)
在活动初始化时,将 ListViewCheckboxesActivity.this 作为值发送并尝试一次
您的构造函数正在尝试将ChildEventListener强制转换为上下文,这会引发我猜测的异常
答案 1 :(得分:0)
Suppose you firebase structure is like this.
States
autoId(XQSKNDLALALALDX...)
code
name
selected
autoId(XQSKNDLALALALDX...)
code
name
selected
your firebase query
MyCustomAdapter mAdapter = new MyCustomAdapter(this);
DatabaseReference dbRef = mDatabase.child("States");
dbRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
if (dataSnapshot.exists()) {
State state = dataSnapshot.getValue(State.class);
mAdapter.addState(state);
}
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { }
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
Your adapter
public class MyCustomAdapter extends RecyclerView.Adapter {
private List<State> stateList = new ArrayList<State>();
private Context mContext;
private LayoutInflater mInflater;
public MyCustomAdapter(Context context) {
this.mContext = context;
this.mInflater = LayoutInflater.from(mContext);
}
public void addState(State state) {
this.stateList.add(state);
this.notifyItemInserted(mChatList.size() - 1);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
//...
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
//...
}
}
答案 2 :(得分:0)
问题现在已经完全解决 查看我的代码
ListViewCheckboxesActivity.java
package com.example.listview1;
public class ListViewCheckboxesActivity extends Activity
{
MyCustomAdapter dataAdapter = null;
FirebaseDatabase database;
DatabaseReference ref;
States states ;
States _states ;
ArrayList<States> stateList;
List<String> keys;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
database= FirebaseDatabase.getInstance();
ref=database.getReference("Stops");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
stateList = new ArrayList<States>();
keys=new ArrayList<>();
System.out.println("@@@@");
//states=new States();
System.out.println("@@@@");
for(DataSnapshot ds: dataSnapshot.getChildren())
{
System.out.println(states=ds.getValue(States.class));
if(states.isSelected()==false) {
keys.add(ds.getKey());
_states = new States(states.getCode(), states.getName(), states.isSelected());
states.setKey(ds.getKey());
System.out.println(states.getKey()+" "+states.getName() + states.getCode() + states.isSelected());
stateList.add(_states);
System.out.println(stateList);
}
}
displayListView();
checkButtonClick();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
{
}
});
//Generate list View from ArrayList
//Generate list View from ArrayList
// displayListView();
}
private void displayListView()
{
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,R.layout.state_info, stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// When clicked, show a toast with the TextView text
States state = (States) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),"Clicked on Row: " + state.getName(),
Toast.LENGTH_LONG).show();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<States>
{
private ArrayList<States> stateList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<States> stateList)
{
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
}
private class ViewHolder
{
TextView code;
CheckBox name;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.state_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
States _state = (States) cb.getTag();
Toast.makeText(getApplicationContext(), "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
_state.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
States state = stateList.get(position);
holder.code.setText(" (" + state.getCode() + ")");
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());
holder.name.setTag(state);
return convertView;
}
}
private void checkButtonClick()
{
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
int j=0;
StringBuffer responseText = new StringBuffer();
final ArrayList<States> statList = dataAdapter.stateList;
for(int i=0;i<statList.size();i++)
{
final States sta = statList.get(i);
if(sta.isSelected()) {
responseText.append("\n" + sta.getName());
j = j + sta.getCode();
System.out.println("@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@");
System.out.println("!!!!!!!!!!!!!");
System.out.println(keys.get(i));
// ref=database.getReference("stops").child("")
}
}
if(j<=15) {
responseText.append("The following were selected \n");
Toast.makeText(getApplicationContext(),
responseText+" Your total number of students "+ j, Toast.LENGTH_LONG).show();
for(int i=0;i<statList.size();i++)
{
final States sta = statList.get(i);
if(sta.isSelected()) {
database.getReference("Stops").child(keys.get(i)).child("selected").setValue(true);
} // ref=database.getReference("stops").child("")
}
System.out.println("@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@@");
System.out.println("@@@@@@@@@@@@");
System.out.println("!!!!!!!!!!!!!");
}
else
{
responseText.append(" Does not comes under bus seats limited to 15\n");
Toast.makeText(getApplication(),
responseText, Toast.LENGTH_LONG).show();
for(int i=0;i<statList.size();i++)
{
final States stat = statList.get(i);
stat.setSelected(false);
}
displayListView();
}
}
});
}
}
States.java
package com.example.listview1;
public class States
{
int code ;
String name ;
boolean selected ;
String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public States() {
}
public States(int code, String name, boolean selected) {
this.code = code;
this.name = name;
this.selected = selected;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
数据库层次结构 “停止”:{ “ 01”:{ “代码”:3, “名称”:“ PALASIA”, “已选择”:是 }, “ 02”:{ “代码”:6 “名称”:“ mr10”, “已选择”:是 }, “ 03”:{ “代码”:2 “名称”:“ NAVLAKHA”, “已选择”:是 }, “ 04”:{ “代码”:4 “名称”:“ BHAWARKUA”, “已选择”:false }, “ 05”:{ “代码”:2 “ name”:“ MEGHDOOT GARDEN”, “已选择”:false }, “ 06”:{ “代码”:4 “ name”:“ VISHNUPURI COLONY”, “已选择”:false }, “ 07”:{ “代码”:6 “名称”:“ VIJAY NAGAR”, “已选择”:false }, “ 08”:{ “代码”:9 “名称”:“ MR 9”, “已选择”:false }, “ 09”:{ “代码”:4 “名称”:“ BAPAT CHAURAHA”, “已选择”:false } }