customize listview can't show all data, android studio - android

I'm thinking how to show data at the customize listview page. can you guys help me to find out where is the mistakes?
here is the assignment
Model txn;
public SQLiteHelper mSQLiteHelper;
ListView mListView;
ArrayList<Model> mList;
RecordListAdapter mAdapter = null;
this is the initialization
mListView = findViewById(R.id.listView);
mList = new ArrayList<>();
mAdapter = new RecordListAdapter(this, R.layout.row, mList);
mListView.setAdapter(mAdapter);
mSQLiteHelper = new SQLiteHelper(this);
mList = new ArrayList<>();
This is my page which showing all data, I put a debugger to debug. It can get my all data which have 15 columns, But it can't show at the listview page. is there any mistake at this code?
try {
SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from Table1", null);
mList.clear();
while (cursor.moveToNext()) {
txn = new Model();
txn.setId(cursor.getInt(cursor.getColumnIndex("id")));
txn.setName(cursor.getString(cursor.getColumnIndex("name")));
txn.setAddress(cursor.getString(cursor.getColumnIndex("address")));
txn.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
mList.add(new Model());
}
mAdapter.notifyDataSetChanged();
if (mList.size() == 0) {
Toast.makeText(this, "No record found...", Toast.LENGTH_SHORT).show();
}
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}

Please check below code
mListView = findViewById(R.id.listView);
mSQLiteHelper = new SQLiteHelper(this);
mList = new ArrayList<>();
mAdapter = new RecordListAdapter(this, R.layout.row, mList);
mListView.setAdapter(mAdapter);
Data binding function code
try {
SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from Table1", null);
mList.clear();
while (cursor.moveToNext()) {
txn = new Model();
txn.setId(cursor.getInt(cursor.getColumnIndex("id")));
txn.setName(cursor.getString(cursor.getColumnIndex("name")));
txn.setAddress(cursor.getString(cursor.getColumnIndex("address")));
txn.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
mList.add(txn);
}
mAdapter.notifyDataSetChanged();
if (mList.size() == 0) {
Toast.makeText(this, "No record found...", Toast.LENGTH_SHORT).show();
}
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
and I have one more suggestion, do not add listview click listener inside of your data binding function.

Related

Spinner not showing data

I am using a spinner in my program and it gets data from my azure SQL database, but when i clicked the drop down nothing happens. Here is my code
try {
ConnectionHelper conStr = new ConnectionHelper();
connect = conStr.connectionclass();
String query = "select * from fabric";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
ArrayList<String> data = new ArrayList<String>();
while (rs.next()) {
String id = rs.getString("FABRIC_NAME");
data.add(id);
}
String[] array = data.toArray(new String[0]);
ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, data);
Fabric.setAdapter(NoCoreAdapter);
} catch (SQLException e) {
e.printStackTrace();
}
Fabric.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String name = Fabric.getSelectedItem().toString();
Toast.makeText(Calc_140_plain.this, name, Toast.LENGTH_SHORT)
.show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
i cant seem to find an error in LogCat as well
Make sure your data array has some element
while (rs.next()) {
String id = rs.getString("FABRIC_NAME");
data.add(id);
}
Log.d("data","size:"+data.size());
print size after while to check data is not empty.
Try this:
ArrayAdapter NoCoreAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, data);
instead of:
ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, data);

How to set selection in spinner with SimpleAdapter?

I am populating spinner from below code and its working perfect. When user select any value from spinner then I am saving stateCodeId in sqlite. Now what I want that when user come again then I want to show the seleted value from ID which already saved in sqlite. How can I show value selected in spinner ?
public void fillStateData() {
try {
State_data = new ArrayList<Map<String, String>>();
State_data.clear();
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
int i = 0;
if (cursor_State.moveToFirst()) {
do {
Map<String, String> datanum = new HashMap<String, String>();
if (i == 0) {
datanum.put("nStateID", "0");
datanum.put("cStateName", "Select State");
State_data.add(datanum);
datanum = new HashMap<String, String>();
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
} else {
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
}
i += 1;
} while (cursor_State.moveToNext());
}
String[] fromwhere = {"nStateID", "cStateName"};
int[] viewswhere = {R.id.txtnStateID, R.id.txtcStateName};
StateAdapter = new SimpleAdapter(getActivity(), State_data, R.layout.state_list_template, fromwhere, viewswhere);
spnState.setAdapter(StateAdapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView stateId = (TextView) view.findViewById(R.id.txtnStateID);
stateCodeId = stateId.getText().toString();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Like this I am getting ID from sqlite.
Cursor c = db.rawQuery("SELECT nStateId from MemberMaster where nCustID ="+SesPMbrID+"", null);
c.moveToFirst();
String state = c.getString(0);
Use
spinner.setSelection(position);

How to reset spinner list when fragment resume?

I have two spinner in my application which populating list from sqlite and it is working fine. When I select State in first spinner then second spinner list populate depend on first spinner. Now what I want that when I select item in both spinner and then I press back and again launch the activity then the list of second spinner still there. I want to clear list of second spinner when I press back button and Populate list in second spinner when user select value in first spinner.
public void fillStateData() {
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst()) {
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
stateCodeId = cursor.getString(0);
}
cursor.close();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void fillDistrictData(String stateCodeId) {
try {
district_array = new ArrayList<String>();
district_array.clear();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '" + stateCodeId + "'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
fillTalukaData(districtCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
add this method to activity.Hope this will work .
#Override
public void onBackPressed() {
spnDistrict.getAdapter().clear();
spnDistrict.getAdapter().notifyDataSetChanged();
finish();
}
Try using
adapter.clear();
spinner.setAdapter(new ArrayAdapter<String>(YourActivity.this,android.R.layout.simple_dropdown_item_1line,adapter));
Use Onresume for clear the array list you want
#Override
public void onResume() {
Log.e("DEBUG", "onResume of LoginFragment");
state_array.clear();
district_array.clear();
super.onResume();
}
or in onCreate view After Inttilizing array clean both arrayList.

Arraylist display selected listview to textview

I'm just a noob in android. I've got this code from someone's blog.
He made a simple database query and populate an arraylist in listview.
How do I get a value from each selected item in listview to text view in new activity?
Here's the arraylist code:
public ArrayList<ArrayList<Object>> rowTable() {
ArrayList<ArrayList<Object>> fillArray = new ArrayList<ArrayList<Object>>();
Cursor cur;
try {
cur = db.query(TABLE_TEST, new String[] { ROW_ID, ROW_NAME,
ROW_CLASS }, null, null, null, null, null);
cur.moveToFirst();
if (!cur.isAfterLast()) {
do {
ArrayList<Object> fillList = new ArrayList<Object>();
dataList.add(cur.getLong(0));
dataList.add(cur.getString(1));
dataList.add(cur.getString(2));
dataArray.add(fillList);
} while (cur.moveToNext());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR DATABASE", e.toString());
}
return fillArray;
}
and here's the listview code.
private void getArrayList() {
// TODO Auto-generated method stub
ArrayList<ArrayList<Object>> getData = dtbase.rowTable();//
name = new String[getData.size()];
for (int x = 0; x < getData.size(); x++) {
ArrayList<Object> getRow = getData.get(x);
name[x] = getRow.get(1).toString();
}
ArrayAdapter<String> sName = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, name);
lv.setAdapter(sName);
}
can you help me?
It's very easy to get the selected item
Here is the method you need to override.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
...
}
}
Then use the position argument to access the arraylist so you could display it in your textview.

deleting sqlite row using listview

I have a listview which connect to an sqlite database. at first it shows my sqlite fields. but my problem is,I can't delete row by setOnLongClickDelete().
error:
The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1510)
codes:
public class CartList extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList() {
// setListAdapter(new ArrayAdapter<String>(this,R.layout.cartformat,results));
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
if (c != null ) {
int totalPrice=0;
if (c.moveToFirst()) {
do {
String title = c.getString(c.getColumnIndex("title"));
int qty = c.getInt(c.getColumnIndex("qty"));
int price = c.getInt(c.getColumnIndex("price"));
int pricePerTitle=price*qty;
results.add("Title: " +title+ ",Quantity: "+qty+", Price: $"+pricePerTitle);
totalPrice=totalPrice+pricePerTitle;
}while (c.moveToNext());
}
TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
String total= Integer.toString(totalPrice);
tTotalPrice.setText(total);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
try{ String currentString = results.get(position);
String resultRegexString = "Title\\:([^,]+),Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(currentString);
if(resultRegexMatcher.find()){
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3)));
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
database.delete("CART", whereClause, null);
database.close();
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
results.remove(position);
}
return true;
} catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
return false;
}
}
} );
displayResultList();
}
}
following Toast works:
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
If you are able to successfully remove the data from the SQLite database then you simply make your listAdapter global and then adding the code
listAdapter.notifyDataSetChanged();
after
results.remove(position);
in your onItemLongClick. After this you can remove calling displayResultList(); in setOnLongClickDelete().

Categories

Resources