0

I am having trouble displaying the data in listview. In the dialogbox the user enters the item and click save button it stores the data in sqlite database but it does not displaying in listview. when i moved to MainActivity.java and returns back to AddCount.java it display the item which is stored in sqlite database. How can i display the item in listview as soon as user clicks save in dialogbox

public class AddCount extends AppCompatActivity {
   ArrayList<User>userList;
   User user;
   DbHandler myDB;
   Cursor data;
   int numRows;
    Two_columnListAdapter adapter;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_count);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ListView listView = (ListView)findViewById(R.id.listview);
        myDB = new DbHandler(this);
        userList = new ArrayList<>();
        data = myDB.getListContents();
         numRows = data.getCount();
        if (numRows == 0) {
                Toast.makeText(AddCount.this, "There is nothing in database", Toast.LENGTH_LONG).show();
            } else {
                while (data.moveToNext()) {
                    user = new User(data.getString(1), data.getString(2));
                    userList.add(user);
                }
            }

           adapter = new Two_columnListAdapter(this,R.layout.list_item_layout,userList);
        listView.setAdapter(adapter);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openDialog();
            }
        });

    }

    public void openDialog() {
final AlertDialog.Builder mydialog = new AlertDialog.Builder(AddCount.this);
mydialog.setTitle("Add Count");
LinearLayout layout = new LinearLayout(AddCount.this);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText title = new EditText(AddCount.this);
title.setHint("Title");
layout.addView(title);
final EditText value = new EditText(AddCount.this);
value.setHint("Count");
layout.addView(value);
mydialog.setView(layout);

        mydialog.setPositiveButton("Save", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
               String UserTitle = title.getText().toString();
               String UserCount = value.getText().toString();
               if (UserTitle.length()!= 0 && UserCount.length() != 0) {
                   AddData(UserTitle,UserCount);
                   title.setText("");
                   value.setText("");
                   adapter.notifyDataSetChanged();
               }
               else {
                   Toast.makeText(AddCount.this ,"Empty!",Toast.LENGTH_SHORT).show();
               }
            }
        }).create();
        mydialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        }).create();

mydialog.show();

    }
    public void AddData(String title,String count){
        boolean insertData = myDB.insertUserInputs(title, count);
        if (insertData==true){
            Toast.makeText(AddCount.this ,"Saved",Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(AddCount.this ,"Some thing went wrong",Toast.LENGTH_SHORT).show();
        }
    }


}

DbHandler.java (create and manage the database)

public class DbHandler extends SQLiteOpenHelper {       
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "users.db";
    private static final String TABLE_Inputs = "userinputs";
    private static final String KEY_ID = "id";
    private static final String KEY_Title = "Title";
    private static final String KEY_Count = "Count";


    public DbHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Create a new table
        String CREATE_TABLE = "CREATE TABLE " + TABLE_Inputs + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + "Title,Count)";
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if exist
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inputs);
        // Create tables again
        onCreate(db);
    }

    
    public boolean insertUserInputs(String UserTitle, String UserCount) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_Title, UserTitle);
        contentValues.put(KEY_Count, UserCount);
        long newRowId = db.insert(TABLE_Inputs, null, contentValues);
        if (newRowId == -1){
            return false;
        }
        else {
            return true;
        }
    }


    public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data =  db.rawQuery("SELECT * FROM " + TABLE_Inputs,null);
return data;
    }

}

Two_columnListAdapter.java

public class Two_columnListAdapter extends ArrayAdapter<User> {
    private LayoutInflater layoutInflater;
    private ArrayList<User>users;
    private int mviewResourceId;
    public Two_columnListAdapter(Context context,int textViewResourceId,ArrayList<User>users){
        super(context,textViewResourceId,users);
        this.users = users;
        layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mviewResourceId = textViewResourceId;
    }
    public View getView(int position, View convertView, ViewGroup parents){
        convertView = layoutInflater.inflate(mviewResourceId,null);
        User user= users.get(position);
        if (user != null){
            TextView  text = (TextView)convertView.findViewById(R.id.title);
            TextView num = (TextView)convertView.findViewById(R.id.value);
            if (text != null){
                text.setText(user.getText());
            }
            if (num != null){
                num.setText(user.getNum());
            }
        }
        return convertView;
    }
}
Learner
  • 41
  • 6

1 Answers1

0

You don't add anything to the list via your adapter, nor you add anything to the list directly when the data is saved to the DB. You shuold add items to the list via your adapter: adapter.add(someItem);

or you can add items to the list, then call notifyDataSetChanged

userlist.add(user);
adapter.notifyDataSetChanged();

In your OnClickListener add the user to the list via the adapter...

        mydialog.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
           String UserTitle = title.getText().toString();
           String UserCount = value.getText().toString();
           if (UserTitle.length()!= 0 && UserCount.length() != 0) {
               AddData(UserTitle,UserCount);
               title.setText("");
               value.setText("");
               
               adapter.add(new User(....));
               ...

Check out this answer on adapters.

blacix
  • 96
  • 8
  • Actually, I already tried adding adapter.add(user) inside my OnClickListener it just repeat what I inserted last not displaying newly added item in listview. When I go to MainActivity and returns back to listview it displaying new item. – Learner Oct 12 '20 at 17:20
  • can you post Two_columnListAdapter as well? – blacix Oct 12 '20 at 18:39
  • I posted my Two_columnListAdapter.java – Learner Oct 13 '20 at 10:04
  • 1
    when you switch to MainActivity and return back to AddCount activity, onCreate is called, where you populate the ListView. and still, in the code you posted, you make modifications neither to the adapter, nor to the list the adapter holds. Without it, the listview will not change for sure, so you should call adapter.Add(user) at some pont. Furthermore you don't need to store the list in Two_columnListAdapter, since the base class, ArrayAdapter does so, you set in the base class when calling super. You can get your item in getView by calling getItem(position) of the base class. – blacix Oct 13 '20 at 11:20