How to create a LeaderBoard in Android Studio? - android

Main Activity code
I want to insert this
public void method() {
name = LoginActivity.name;
score = GameView.valueCurrent;
ContentValues values = new ContentValues();
values.put("name", name);
values.put("score", score);
}
And dont " myDB.execSQL("INSERT INTO scores (name, score) VALUES ('Marie', '4');");"
public class MainActivity extends AppCompatActivity {
private List<Items> itemsList = new ArrayList<Items>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase myDB = null;
try {
//Create a Database if doesnt exist otherwise Open It
myDB = this.openOrCreateDatabase("leaderboard", MODE_PRIVATE, null);
//Create table in database if it doesnt exist allready
myDB.execSQL("CREATE TABLE IF NOT EXISTS scores (name TEXT, score TEXT);");
//Select all rows from the table
Cursor cursor = myDB.rawQuery("SELECT * FROM scores", null);
//If there are no rows (data) then insert some in the table
if (cursor != null) {
if (cursor.getCount() == 0) {
/*** In this case i want to put the values of the Users that are playing my app
myDB.execSQL("INSERT INTO scores (name, score) VALUES ('Andy', '7');");
myDB.execSQL("INSERT INTO scores (name, score) VALUES ('Marie', '4');");
myDB.execSQL("INSERT INTO scores (name, score) VALUES ('George', '1');");
**//
}
}
} catch (Exception e) {
} finally {
//Initialize and create a new adapter with layout named list found in activity_main layout
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, itemsList);
listView.setAdapter(adapter);
Cursor cursor = myDB.rawQuery("SELECT * FROM scores", null);
if (cursor.moveToFirst()) {
//read all rows from the database and add to the Items array
while (!cursor.isAfterLast()) {
Items items = new Items();
items.setName(cursor.getString(0));
items.setScore(cursor.getString(1));
itemsList.add(items);
cursor.moveToNext();
}
}
//All done, so notify the adapter to populate the list using the Items Array
adapter.notifyDataSetChanged();
}
}
}
CustomListAdapter code
public class CustomListAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater inflater;
private List<Items> itemsItems;
public CustomListAdapter(Context context, List<Items> itemsItems) {
this.mContext = context;
this.itemsItems = itemsItems;
}
#Override
public int getCount() {
return itemsItems.size();
}
#Override
public Object getItem(int location) {
return itemsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View scoreView, ViewGroup parent) {
ViewHolder holder;
if (inflater == null) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (scoreView == null) {
scoreView = inflater.inflate(R.layout.list_row, parent, false);
holder = new ViewHolder();
holder.name = (TextView) scoreView.findViewById(R.id.name);
holder.score = (TextView) scoreView.findViewById(R.id.score);
scoreView.setTag(holder);
} else {
holder = (ViewHolder) scoreView.getTag();
}
final Items m = itemsItems.get(position);
holder.name.setText(m.getName());
holder.score.setText(m.getScore());
return scoreView;
}
static class ViewHolder {
TextView name;
TextView score;
}
}
Items Code
public class Items {
private String name, score;
public Items() {
}
public Items(String name, String score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
Couple of more things.
How to show the current Leaderboard using this code of Database?
I dont know how to use on that.

Use Google Play: https://developers.google.com/games/services/android/leaderboards
Create Google Play Game In Developer Console
1)Add the BaseGameUtils SDK from here https://github.com/playgameservices/android-basic-samples
2) In app gradle:
dependencies {
compile 'compile project(':BaseGameUtils')'
}
3) Update Score: Games.Leaderboards.submitScore(mGoogleApiClient, LEADERBOARD_ID, 1337);
4)
Display Leaderboard: startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
LEADERBOARD_ID), REQUEST_LEADERBOARD);
Make sure you successfully connect to googleApiClient/Google Play Games Services

Related

dynamically update RecyclerView on SqLite database dataset change

I have a fairly simple implementation of a high score leader board here that saves the name provided by the user alongside his or her score.
Unfortunately, upon returning to the high score activity the RecyclerView will only show the score that had previously been populated, not the new one that was just entered. I am using notifyDatasetChanged() method in an async task. Still no success. Any pointers are much appreciated.
The high score activity:
public class HighscoreActivity extends AppCompatActivity implements View.OnClickListener{
SQLiteDatabase db;
ArrayList<String> nameList;
ArrayList<String> scoreList;
RecyclerView recyclerView;
ScoreRecViewAdapter scoreRecViewAdapter;
Button buttonStart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_highscore);
buttonStart = findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(this);
// create lists and table
nameList = new ArrayList<>();
scoreList = new ArrayList<>();
db = this.openOrCreateDatabase("Scores", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS scores(name VARCHAR, score VARCHAR)");
//Cursor c = db.rawQuery("SELECT * FROM scores", null);
Cursor c = db.rawQuery("SELECT * FROM scores ORDER BY score DESC", null);
// Fill list
int nameIndex = c.getColumnIndex("name");
int scoreIndex = c.getColumnIndex("score");
while ( c.moveToNext() ){
nameList.add(c.getString(nameIndex));
scoreList.add(c.getString(scoreIndex));
}
// put data in rec view
recyclerView = findViewById(R.id.recView);
scoreRecViewAdapter = new ScoreRecViewAdapter(this, nameList, scoreList);
recyclerView.setAdapter(scoreRecViewAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// enter new user data
Intent getter = getIntent();
String nameExtra = getter.getStringExtra("name");
String scoreExtra = getter.getStringExtra("score");
if( nameExtra != null && scoreExtra != null) {
// perform async task
new InsertIntoDatabase().execute(nameExtra, scoreExtra);
}
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.buttonStart) {
Intent actorQuizz = new Intent(this, MainActivity.class);
startActivity(actorQuizz);
}
}
public class InsertIntoDatabase extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... strings) {
db.execSQL("INSERT INTO scores (name, score) VALUES ('" + strings[0] + "', '" + strings[1] +"')");
Log.i("score saved", "success");
return "success";
}
#Override
protected void onPostExecute(String s) {
//nameList.clear();
//scoreList.clear();
Cursor c = db.rawQuery("SELECT * FROM scores", null);
// Fill list
int nameIndex = c.getColumnIndex("name");
int scoreIndex = c.getColumnIndex("score");
while ( c.moveToNext() ){
nameList.add(c.getString(nameIndex));
scoreList.add(c.getString(scoreIndex));
}
scoreRecViewAdapter.notifyDataSetChanged();
}
}
}
and the recyclerview adapter:
public class ScoreRecViewAdapter extends RecyclerView.Adapter {
Context mContext;
ArrayList<String> nameList;
ArrayList<String> scoreList;
public ScoreRecViewAdapter (Context context, ArrayList<String> nameList, ArrayList<String> scoreList) {
this.mContext = context;
this.nameList = nameList;
this.scoreList = scoreList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.rec_menu,parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.nameView.setText(nameList.get(position));
holder.scoreView.setText(scoreList.get(position));
}
#Override
public int getItemCount() {
return nameList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameView;
TextView scoreView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameView = itemView.findViewById(R.id.textViewName);
scoreView = itemView.findViewById(R.id.textViewScore);
}
}
}

How do I retrieve two fields from a prepopulate sqlite db and assign it to custom list view?

I want to retrieve data from two fields from prepopulate sqlite database. The fields are Organization Name (org_name) and Contact Number (contact_no). After that I need to assign org_name data to a large text field and contact_no to small text field in my custom list view.
I have tried this only with one field. It's working fine. But when I'm trying to retrieve two fields it's not working. This is what I tried. Please help me to solve this issue.
ContactView class
public class ContactView extends Activity {
private ListView listView;
private ListView listView1;
List<Organization> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBAccess databaseAccess = DBAccess.getInstance(this);
databaseAccess.open();
List<String> quotes = databaseAccess.getQuotes(getIntent().getStringExtra("ID_EXTRA"));
databaseAccess.close();
List<Organization> rowItem=new ArrayList<Organization>();
for(String quote:quotes){
Organization temp=new Organization(quote);
rowItem.add(temp);
}
listView = (ListView)findViewById(R.id.listView);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.single_row_item, rowItem);
listView.setAdapter(adapter);
}
Database Access Class
public class DBAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DBAccess instance;
String passedVar = null;
private ListView listView;
public DBAccess(Context context) {
this.openHelper = new HelloDatabase(context);
}
public static DBAccess getInstance(Context context) {
if (instance == null) {
instance = new DBAccess(context);
}
return instance;
}
public void open() {
this.database = openHelper.getWritableDatabase();
}
public void close() {
if (database != null) {
this.database.close();
}
}
public List<String> getQuotes(String id) {
List<String> list = new ArrayList<>();
Integer value;
if (id != null) {
Cursor cursor = database.rawQuery("SELECT org_name,contact_no FROM org_name WHERE category_id = \"" + id + "\"", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
list.add(cursor.getString(cursor.getColumnIndex("contact_no")));
cursor.moveToNext();
}
cursor.close();
}
return list;
}}
Bean class
public class Organization {
public String title;
public String telenum;
public Organization(String title,String telenum) {
this.title = title;
this.telenum=telenum;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTelenum(){
return telenum;
}
public void setTelenum(String telenum){
this.telenum=telenum;
}
}
CustomListViewAdapter class
public class CustomListViewAdapter extends ArrayAdapter<Organization> {
Context context;
public CustomListViewAdapter(Context context, int layout,
List<Organization> items) {
super(context, layout, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
TextView txtTitle;
TextView txtTele;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Organization rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.single_row_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.org_name);
holder.txtTele = (TextView) convertView.findViewById(R.id.tele_num);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtTitle.setText(rowItem.getTitle());
holder.txtTele.setText(rowItem.getTelenum());
return convertView;
}}
Note : If any one facing the same issue, kindly use SimpleCursorAdapter. Its simple, easy to use and efficient. Find a simple example here or checkout my answer on this thread https://stackoverflow.com/a/37560755/5460053
It is not working for two fields because of the following lines in getQuotes() method of DBAccess class :
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));//Adding org_name first. org_name is added at indexes : 0,2,4,...
list.add(cursor.getString(cursor.getColumnIndex("contact_no")));//Then adding contact_no. contact_no is added at indexes : 1,3,5,...
cursor.moveToNext();
}
Then while creating a datasource for the adapter, org_name and contact_no are added at alternate indexes
List<Organization> rowItem=new ArrayList<Organization>();
for(String quote:quotes){
Organization temp=new Organization(quote);//I wonder how this worked as there is only one contructor for Organization which is expecting 2 parameters
rowItem.add(temp);
}
Change your DBAccess class getQuotes() to this :
public List<Organization> getQuotes(String id) {
List<Organization> list = new ArrayList<>();
if (id != null) {
Cursor cursor = database.rawQuery("SELECT org_name,contact_no FROM org_name WHERE category_id = \"" + id + "\"", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Organization org = new Organization(cursor.getString(0),
cursor.getString(cursor.getColumnIndex("contact_no")));
list.add(org);
cursor.moveToNext();
}
cursor.close();
}
return list;
}
And change your ContactView Activity's onCreate() to this :
public class ContactView extends Activity {
private ListView listView;
private ListView listView1;
List<Organization> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBAccess databaseAccess = DBAccess.getInstance(this);
databaseAccess.open();
List<Organization> rowItem = databaseAccess.getQuotes(getIntent().getStringExtra("ID_EXTRA"));
databaseAccess.close();
listView = (ListView)findViewById(R.id.listView);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.single_row_item, rowItem);
listView.setAdapter(adapter);
}

Android: fill list view with data from sqlite

Overview: The programme I'm now trying to make has the following steps.
get the input data from users and store them in the SQLite database.
Fill the list view with the data retrieved from the database.
In order to implement 1, I first created the addNewItem() method as follows.
public void addNewPost(Post post) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// get the variables which are to be put into the database row.
String uploader = post.getUploader();
String content = post.getContent();
String privacy_level = post.getPrivacyLevel();
String uploaded_at = post.getUploadedAt();
String edited_at = post.getEditedAt();
values.put(KEY_UPLOADER, uploader);
values.put(KEY_CONTENT, content);
values.put(KEY_PRIVACY_LEVEL, privacy_level);
values.put(KEY_UPLOADED_AT, uploaded_at);
values.put(KEY_EDITED_AT, edited_at);
db.insert(TABLE_POST, null, values);
db.close();
}
And for 2, I created another method called initListView().
private void initListView() {
SQLiteDatabase db = sqliteHandler.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + SQLiteHandler.TABLE_POST, null);
username.clear();
uploaded_at.clear();
content.clear();
if(cursor.moveToFirst()) {
do {
username.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_UPLOADER)));
uploaded_at.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_UPLOADED_AT)));
content.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_CONTENT)));
} while(cursor.moveToNext());
}
FeedAdapter adapter = new FeedAdapter(this, username, uploaded_at, content);
listView.setAdapter(adapter);
cursor.close();
}
And finally this is the FeedAdapter class.
public class FeedAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> username;
private ArrayList<String> uploaded_at;
private ArrayList<String> content;
public FeedAdapter(Context context, ArrayList<String> username, ArrayList<String> uploaded_at, ArrayList<String> content) {
this.context = context;
this.username = username;
this.uploaded_at = uploaded_at;
this.content = content;
}
public int getCount() {
return username.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater;
if(convertView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, null);
ImageView ivFeedThumbnail = (ImageView) convertView.findViewById(R.id.ivFeedThumbnail);
TextView tvFeedUsername = (TextView) convertView.findViewById(R.id.tvFeedUsername);
TextView tvFeedUploaded = (TextView) convertView.findViewById(R.id.tvFeedCreated);
TextView tvFeedText = (TextView) convertView.findViewById(R.id.tvFeedText);
TextView tvFeedLikes = (TextView) convertView.findViewById(R.id.tvFeedLikes);
TextView tvFeedComments = (TextView) convertView.findViewById(R.id.tvFeedComments);
Button btnLike = (Button) convertView.findViewById(R.id.btnLike);
Button btnComment = (Button) convertView.findViewById(R.id.btnComment);
tvFeedUsername.setText(username.get(position));
tvFeedUploaded.setText(uploaded_at.get(position));
tvFeedText.setText(content.get(position));
}
return convertView;
}
}
The code seems to have no problem, but when I run the application, the list is still empty.
Any tips for the solution will be very much appreciated.

How to retrieve the next value in sqlite android

Hi I have an app that display the name and gender of the students. In my query, I limit the display to 20. How will I apply the display of 21-40 by clicking the next button. Also it will go back if i click previous.
MainActivity class
public class MainActivity extends Activity {
List<Students> GetAll;
DatabaseHelper db = new DatabaseHelper(this);
ListView lv;
Context context = this;
DatabaseHelper dbhelper;
Button btnprevious,btnnext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbhelper = new DatabaseHelper(MainActivity.this);
//Add below lines to your original code
try{
dbhelper.createDataBase();
}
catch(IOException e){
e.printStackTrace();
}
try {
dbhelper.openDataBase();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Till here
GetAll = dbhelper.getAll();
lv = (ListView) findViewById(R.id.list);
lv.setAdapter(new ViewAdapter());
}
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return GetAll.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item,null);
}
final TextView names = (TextView) convertView.findViewById(R.id.doctorlist_name);
final TextView gender = (TextView) convertView.findViewById(R.id.doctorlist_gender);
names.setText(GetAll.get(position).getname());
gender.setText(GetAll.get(position).getgender());
return convertView;
}
}
}
DatabaseHelper class
public List<Students> getAll() {
final int maxCount = 20;
List<Students> sList = new ArrayList<Students>();
{
String selectQuery =
"SELECT id,full_name,gender FROM students LIMIT " +maxCount+" ";
Log.e("students query: ", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Students si = new Students();
si.setid(Integer.parseInt(cursor.getString(0)));
si.setname(cursor.getString(1));
si.setgender(cursor.getString(2));
sList.add(si);
} while (cursor.moveToNext());
}
db.close();
}
return sList;
}
On next Button click increase index with 20 and on previous button click decrease the index to 20, You can achieve with below query.
String selectQuery = "SELECT id,full_name,gender FROM students LIMIT 20, "+index;
Edit:
public List<Students> getStudent(int index) {
final int maxCount = 20;
List<Students> sList = new ArrayList<Students>();{
String selectQuery = "SELECT id,full_name,gender FROM students LIMIT "+maxCount+", "+index;;
Log.e("students query: ", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Students si = new Students();
si.setid(Integer.parseInt(cursor.getString(0)));
si.setname(cursor.getString(1));
si.setgender(cursor.getString(2));
sList.add(si);
} while (cursor.moveToNext());
}
db.close();
}
return sList;
}
private int currentPageIndex=0;
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.prevBtn;
currentPageIndex -=20;
GetStudent.clear();
GetStudent.addAll(dbhelper.getStudent(int index));
adapter.notifyDataSetChanged();
break;
case R.id.nextBtn;
currentPageIndex +=20;
GetStudent.clear();
GetStudent.addAll(dbhelper.getStudent(int index));
adapter.notifyDataSetChanged();
break;
}
}
You can change the whereCluse:
for example next page: (page = 2)
id> 20*(page - 1) and LIMIT 20*(page)

Android notifyDataSetChanged from a custom adapter

So my app uses a local SQLite db through a contentProvider
In it's mainActivity I have a listView displaying the contents of a table from the above DB.
I use a custom adapter to display the listview. Each item has a button in it's (custom) layout, that when pressed, shows a custom dialog that inserts a new record in that table, then the dialog gets dismissed.
In order to achieve this behavior, I placed the button click handler inside the customAdapter.
I would like to be able to refresh the listView after the inserting is done (so when dialog is dismissed)
How can I achieve this?
I should probably need to call notifyDataSetChanged somehow from inside the custom Adapter but I can't.
In short, my custom adapter looks like this:
public class DisplayStuffAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> iduser;
private ArrayList<String> product;
public DisplayStuffAdapter(Context c){
this.mContext = c;
}
public DisplayStuffAdapter(Context c, ArrayList<String> id, ArrayList<String> userid, ArrayList<String> product) {
this.mContext = c;
this.id = id;
this.userid = userid;
this.product = product;
}
public int getCount() {
return id.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public class Holder {
TextView txt_id;
TextView txt_userid;
TextView txt_prod;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.myitem, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.tv_MkId);
mHolder.txt_userid = (TextView) child.findViewById(R.id.tv_MkUserId);
mHolder.txt_prod = (TextView) child.findViewById(R.id.tv_MkProduct);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_userid.setText(userid.get(pos));
mHolder.txt_prod.setText(product.get(pos));
Button bt = (Button) child.findViewById(R.id.itemButton);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(mContext);
final View promptsView = li.inflate(R.layout.bid_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder.setMessage("Input data")
.setIcon(R.drawable.add_red_24)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.setPositiveButton("Add new record", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ContentValues values = new ContentValues();
values.put(MyProvider.TCOL_ID, myid);
values.put(MyProvider.TCOL_OTHERID, Integer.toString(getActiveUserId()));
Uri uri = mContext.getContentResolver().insert(MyProvider.CONTENT_URI_TABLE, values);
values = new ContentValues();
dialogInterface.dismiss();
}
}
}
});
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
....
}
});
....
I remove some parts from the code to make it more readable.
Now, in my MainActivity, I set the adapter like this:
public class MainActivity extends Activity{
private ArrayList<String> id = new ArrayList<String>();
private ArrayList<String> userid = new ArrayList<String>();
private ArrayList<String> product = new ArrayList<String>();
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillListView();
}
...
private void fillListView(){
id.clear();
userid.clear();
product.clear();
String[] col = {MyProvider.TCOL_ID_ID, MyProvider.TCOL_USERID, MyProvider.TCOL_PROD};
String where = "done = 1";
Cursor mCursor = MainActivity.this.getContentResolver().query(MyProvider.CONTENT_URI_TABLE, col, where, null, MyProvider.TCOL_DATE + " desc");
if (mCursor != null) {
if (mCursor.moveToFirst()) {
do {
id.add(Integer.toString(mCursor.getInt(0)));
userid.add(Integer.toString(mCursor.getInt(1)));
product.add(mCursor.getString(2));
} while (mCursor.moveToNext());
}
}
DisplayStuffAdapter disadpt = new DisplayStuffAdapter(MainActivity.this,id,userid,product);
disadpt.notifyDataSetChanged();
ListView lv = (ListView) findViewById(R.id.mylistView);
lv.setAdapter(disadpt);
}
So this all works great, except that when I add a new record to the table using the customdialog described above... the dialog closes, and the listview remains unchanged.
How can I refresh the listView?
In general, when you're querying data from a DB, you should use ContentProvider and CursorLoader. You can configure your content provider to automatically notify loaders when some data changes, using ContentResolver notifyChange() method. Place the call to this method in your ContentProvider implementation (for example after the insert). This is an example of adapter you can use (but you can use SimpleCursorAdapter providing a view binder too).
public class CustomCursorAdapter extends CursorAdapter {
private LayoutInflater mInflater;
public CustomCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
if(cursor.getPosition()%2==1) {
view.setBackgroundColor(context.getResources().getColor(R.color.background_odd));
}
else {
view.setBackgroundColor(context.getResources().getColor(R.color.background_even));
}
TextView content = (TextView) view.findViewById(R.id.row_content);
content.setText(cursor.getString(cursor.getColumnIndex(Table.CONTENT)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mInflater.inflate(R.layout.listitem, parent, false);
}
}
public class DisplayStuffAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> iduser;
private ArrayList<String> product;
public DisplayStuffAdapter(Context c){
this.mContext = c;
}
public void loadData(){
id.clear();
userid.clear();
product.clear();
String[] col = {MyProvider.TCOL_ID_ID, MyProvider.TCOL_USERID, MyProvider.TCOL_PROD};
String where = "done = 1";
Cursor mCursor = MainActivity.this.getContentResolver().query(MyProvider.CONTENT_URI_TABLE, col, where, null, MyProvider.TCOL_DATE + " desc");
if (mCursor != null) {
if (mCursor.moveToFirst()) {
do {
id.add(Integer.toString(mCursor.getInt(0)));
userid.add(Integer.toString(mCursor.getInt(1)));
product.add(mCursor.getString(2));
} while (mCursor.moveToNext());
}
}
notifyDataSetChanged();
}
...
}
public class MainActivity extends Activity{
private DisplayStuffAdapter disadpt = null;
ContentObserver displayStuffObserver = new ContentObserver(new Handler()){
#Override
public void onChange(boolean selfChange) {
if(disadpt != null) {
disadpt.loadData();
}
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
disadpt = new DisplayStuffAdapter(this);
ListView lv = (ListView) findViewById(R.id.mylistView);
lv.setAdapter(disadpt);
disadpt.loadData();
getContentResolver().registerContentObserver(MyProvider.CONTENT_URI_TABLE,true, displayStuffObserver);
}
}
Do not forget to unregister your content observer
First of all, I am not getting why you are sending three different arraylists to the adapter. You can simply make a modal class having all the fields that you require in your adapter. Considering your current scenario it will be something like this
public class ModalClass {
private String id = "";
private String userId = "";
private String product = "";
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
}
So this is your modal class with getters and setters. Now all you have to do is you have to make an ArrayList of this modal class like this
List<ModalClass> modalClassList=new ArrayList<ModalClass>();
and you have to set all the data that you want to display in your list in this arraylist by making use of modal class setter functions. Like this
if (mCursor != null) {
if (mCursor.moveToFirst()) {
do {
ModalClass modalClass=new ModalClass();
modalClass.setId(Integer.toString(mCursor.getInt(0)));
modalClass.setUserId(Integer.toString(mCursor.getInt(1)));
modalClass.setProduct(mCursor.getString(2));
modalClassList.add(modalClass);
} while (mCursor.moveToNext());
}
}
and now you have your arraylist ready, so you can set it to your listview like this
ListView lv = (ListView) findViewById(R.id.mylistView);
DisplayStuffAdapter disadpt = new DisplayStuffAdapter(MainActivity.this,modalClassList);
lv.setAdapter(disadpt);
And accordingly you have to modify your adapter constructor which i think you can do by your own.
Also how to set values in your adapter, you can make use of your modal class getter methods like this.
ModalClass modalClass=modalClassList.get(pos);
mHolder.txt_id.setText(modalClass.getId());
mHolder.txt_userid.setText(modalClass.getUserId());
mHolder.txt_prod.setText(modalClass.getProduct());
Now when you want to insert a new row in your adapter, you have to simply create an object of ModalClass and set all the new values in that like we have done in our MainActivity class and then finally add that to your modalClassList followed by notifyDataSetChanged();
ModalClass modalClass=new ModalClass();
modalClass.setId(yourNewInsertedRowId);
modalClass.setUserId(yourNewInsertedRowUserId);
modalClass.setProduct(yourNewInsertedRowProduct);
modalClassList.add(modalClass);
notifyDataSetChanged();
And this time your list will be notify for sure. Cheers :)

Categories

Resources