[英]Unable to fetch data and display in listview in android
MySqliteDatabase Clas: MySqliteDatabase Clas:
public class MySqliteDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "EmaployeeDetail";
private static final String TABLE_EMployee = "Employee";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
public MySqliteDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_EMployee + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void addEmployee(Employee contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.get_name()); // Contact Name
values.put(KEY_EMAIL, contact.get_email()); // Contact Phone
// Inserting Row
db.insert(TABLE_EMployee, null, values);
// 2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}
public List<Employee> getAllContacts() {
List<Employee> contactList = new ArrayList<Employee>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_EMployee;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Employee contact = new Employee();
contact.set_id(Integer.parseInt(cursor.getString(0)));
contact.set_name(cursor.getString(1));
contact.set_email(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EMployee);
// Create tables again
onCreate(db);
}
}
ContanctAdapter Class : ContanctAdapter类:
public class ContanctAdapter extends ArrayAdapter<Employee> {
private Activity activity;
private List<Employee> items;
private int row;
private Employee objBean;
public ContanctAdapter(Activity act, int row, List<Employee> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return view;
objBean = items.get(position);
holder.tvname = (TextView) view.findViewById(R.id.tvname);
holder.tvEmail = (TextView) view.findViewById(R.id.tvemail);
if (holder.tvname != null && null != objBean.get_name()
&& objBean.get_name().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.get_name()));
}
if (holder.tvEmail != null && null != objBean.get_email()
&& objBean.get_email().trim().length() > 0) {
holder.tvEmail.setText(Html.fromHtml(objBean.get_email()));
}
return view;
}
public class ViewHolder {
public TextView tvname, tvEmail;
}
}
MainActivity Class: MainActivity类:
public class MainActivity extends Activity {
MySqliteDatabase db = new MySqliteDatabase(this);
EditText nametext;
EditText emailtext;
Button btn;
public List<Employee> list1 = new ArrayList<Employee>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nametext = (EditText) findViewById(R.id.editText1);
emailtext = (EditText) findViewById(R.id.editText2);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = nametext.getText().toString();
String email = emailtext.getText().toString();
db.addEmployee(new Employee(name, email));
Toast.makeText(getApplicationContext(), "SucessfullyInseter",
1000).show();
}
});
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
List<Employee> contacts = db.getAllContacts();
Employee emp = new Employee();
for (Employee cn : contacts) {
String log = "Id: " + cn.get_id() + " ,Name: " + cn.get_name()
+ " ,Phone: " + cn.get_email();
// Writing Contacts to log
Log.d("Name: ", log);
String name1 = cn.get_name();
String Email1 = cn.get_email();
ListView list = (ListView) findViewById(R.id.listView1);
emp.set_name(name1);
emp.set_email(Email1);
contacts.add(emp);
ContanctAdapter objAdapter = new ContanctAdapter(MainActivity.this,
R.layout.alluser_row, list1);
list.setAdapter(objAdapter);
}
}
}
I am Able to fetch data at this line Log.d("Name: ", log); 我能够在这一行获取数据Log.d(“ Name:”,log); but when i Print data in listview using this Line : 但是当我使用此行在列表视图中打印数据时:
ContanctAdapter objAdapter = new ContanctAdapter(MainActivity.this,
R.layout.alluser_row, list1);
list.setAdapter(objAdapter);
Application becomes crash i dont know what is the Problem why its Application crash please help where am doing wrong i am unable to find issue. 应用程序崩溃我不知道是什么问题,为什么它的应用程序崩溃请帮助哪里做错了我找不到问题。
Heer is my stack trace: Heer是我的堆栈跟踪:
03-24 10:20:27.850: E/AndroidRuntime(10129): FATAL EXCEPTION: main
03-24 10:20:27.850: E/AndroidRuntime(10129): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.crudexample/com.example.crudexample.MainActivity}: java.util.ConcurrentModificationException
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1964)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1989)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.app.ActivityThread.access$600(ActivityThread.java:126)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1155)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.os.Handler.dispatchMessage(Handler.java:99)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.os.Looper.loop(Looper.java:137)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.app.ActivityThread.main(ActivityThread.java:4482)
03-24 10:20:27.850: E/AndroidRuntime(10129): at java.lang.reflect.Method.invokeNative(Native Method)
03-24 10:20:27.850: E/AndroidRuntime(10129): at java.lang.reflect.Method.invoke(Method.java:511)
03-24 10:20:27.850: E/AndroidRuntime(10129): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
03-24 10:20:27.850: E/AndroidRuntime(10129): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
03-24 10:20:27.850: E/AndroidRuntime(10129): at dalvik.system.NativeStart.main(Native Method)
03-24 10:20:27.850: E/AndroidRuntime(10129): Caused by: java.util.ConcurrentModificationException
03-24 10:20:27.850: E/AndroidRuntime(10129): at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
03-24 10:20:27.850: E/AndroidRuntime(10129): at com.example.crudexample.MainActivity.onStart(MainActivity.java:62)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1133)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.app.Activity.performStart(Activity.java:4475)
03-24 10:20:27.850: E/AndroidRuntime(10129): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1937)
03-24 10:20:27.850: E/AndroidRuntime(10129): ... 11 more
You cannot modify a list you are currently iterating over. 您无法修改当前正在迭代的列表。 At least not the way you've done it. 至少不是您完成的方式。
for (Employee cn : contacts) {
...
contacts.add(emp);
...
}
I'd tell you how to fix it but frankly your code is confusing as hell. 我会告诉您如何解决它,但坦率地说,您的代码令人困惑。 Maybe this is what you meant: 也许这就是你的意思:
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
List<Employee> contacts = db.getAllContacts();
for (Employee cn : contacts) {
String log = "Id: " + cn.get_id() + " ,Name: " + cn.get_name()
+ " ,Phone: " + cn.get_email();
// Writing Contacts to log
Log.d("Name: ", log);
}
ListView list = (ListView) findViewById(R.id.listView1);
ContanctAdapter objAdapter = new ContanctAdapter(MainActivity.this,
R.layout.alluser_row, contacts);
list.setAdapter(objAdapter);
}
As already stated there is problem in code (ConcurrentModificcationException) 如前所述,代码中存在问题(ConcurrentModificcationException)
To fix there is no need to iterate over a loop 要解决此问题,无需遍历循环
List<Employee> contacts = db.getAllContacts();
ListView list = (ListView) findViewById(R.id.listView1);
ContanctAdapter objAdapter = new ContanctAdapter(MainActivity.this,
R.layout.alluser_row, contacts);
list.setAdapter(objAdapter);
You inflate a layout for each item in listview. 您为列表视图中的每个项目添加布局。 The number of items depends on the size of the list. 项目的数量取决于列表的大小。 There is no need for a for
loop in your activity code. 没有必要为一个for
您的活动代码回路。 You have a List
of Employee
that is passed to Custom Adapter ie ContanctAdapter
and you use the same there. 您有一个传递给“自定义适配器”(即ContanctAdapter
的Employee
List
,并在那里使用了该列表。
Also change 也改变
MySqliteDatabase db = new MySqliteDatabase(this)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
to 至
MySqliteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new MySqliteDatabase(this);
Context is available once Activity is created. 创建活动后即可使用上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.