I have a listview on my mainactivity that is showing items from a database. I have an add button up in the action bar. When the add button is clicked on a dialog pops up and the user fills out fields for the new item and then they click "add" and it adds the item to the database. The only problem is that the listview on the mainactivity doesn't update to show the new item. I can close the app and reopen it and I see the new item. It just doesn't update immediatly. (Same problem with deleting an item, only the delete happens onLongPress)
Mainactivity.java
package blah.blah.blah
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class InitActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Gets the data repository in write mode
PlayersDBHelper mDbHelper = new PlayersDBHelper(getBaseContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}//End onCreate()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.init, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_add:
showAddPlayerDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showAddPlayerDialog() {
// Create an instance of the dialog fragment and show it
DialogFragment dialog = new addPlayerDialog();
dialog.show(this.getFragmentManager(), "addPlayerFragment");
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
Fragment playersFragment = new PlayersFragment();
return playersFragment;
} else if(position == 1){
Fragment otherFragment= new otherFragment();
return otherFragment;
} else {
Fragment otherFragment2 = new otherFragment2();
return otherFragment2;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}//End sectionsPagerAdapter()
public static class PlayersFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public int myFragmentId = 1;
private ListView mylistview;
private String[] values;
public ArrayAdapter<String> adapter;
public PlayersFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_players,
container, false);
mylistview = (ListView) rootView.findViewById(R.id.myListView);
registerForContextMenu(mylistview);
PlayersDBHelper mDbHelper = new PlayersDBHelper(rootView.getContext());
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PlayerEntry._ID,
PlayerEntry.COLUMN_NAME_ID,
PlayerEntry.COLUMN_NAME_NAME,
PlayerEntry.COLUMN_NAME_POSITION
};
String selection = null; //Null will return all rows for given table
String[] selectionArgs = null; //Null should return all data
// How you want the results sorted in the resulting Cursor
String sortOrder =
PlayerEntry.COLUMN_NAME_NAME + " DESC";
Cursor c = db.query(
PlayerEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
values = new String[] {};
String array[] = new String[c.getCount()];
int i = 0;
c.moveToFirst();
while (c.isAfterLast() == false) {
array[i] = c.getString(c.getColumnIndexOrThrow(PlayerEntry.COLUMN_NAME_NAME));
i++;
c.moveToNext();
}
for(int x = 0; x < array.length ; x++){
Log.d("Logan", "Entry at:" + x + " is " + array[x]);
values = push(values, array[x]);
}
adapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_list_item_1, values);
mylistview.setAdapter(adapter);
return rootView;
}
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
for (int i = 0; i < array.length; i++)
longer[i] = array[i];
longer[array.length] = push;
return longer;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.myListView) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(values[info.position]);
String[] menuItems = {"Edit", "Delete"};
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
PlayersDBHelper mDbHelper = new PlayersDBHelper(getActivity());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = {"Edit", "Delete"};
String menuItemName = menuItems[menuItemIndex];
String listItemName = values[info.position];
if(menuItemName.equalsIgnoreCase("Edit")) {
} else {
//menuItemName === Delete
// Define 'where' part of query.
String selection = PlayerEntry.COLUMN_NAME_NAME + " =? ";
// Specify arguments in placeholder order.
String[] selectionArgs = { listItemName };
// Issue SQL statement.
db.delete(PlayerEntry.TABLE_NAME, selection, selectionArgs);
adapter.notifyDataSetChanged();
}
return true;
}
}
public static class otherFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public otherFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lineup,
container, false);
return rootView;
}
}
public static class otherFragment2 extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public otherFragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_position,
container, false);
return rootView;
}
}
}
addPlayerDialog.java
package blah.blah.blah;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
public class addPlayerDialog extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Gets the data repository in write mode
PlayersDBHelper mDbHelper = new PlayersDBHelper(getActivity().getBaseContext());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
final View view = inflater.inflate(R.layout.addplayerdialog, null);
final ListView list = (ListView)view.findViewById(R.id.myListView);
builder.setView(view)
// Add action buttons
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
EditText fName = (EditText) view.findViewById(R.id.editFirstName);
Editable firstName = fName.getText();
EditText lName = (EditText) view.findViewById(R.id.editLastName);
Editable lastName = lName.getText();
EditText number = (EditText) view.findViewById(R.id.playerNumber);
int num = Integer.parseInt(number.getText().toString());
Spinner spinner = (Spinner) view.findViewById(R.id.positionSpinner);
String position = spinner.getSelectedItem().toString();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(PlayerEntry.COLUMN_NAME_ID, num);
values.put(PlayerEntry.COLUMN_NAME_NAME, firstName + " " + lastName);
values.put(PlayerEntry.COLUMN_NAME_POSITION, position);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
PlayerEntry.TABLE_NAME,
null,
values);
//**** HERE IS WHERE I THINK THE CHANGE NEEDS TO BE! ****
((ArrayAdapter) list.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
Spinner spinner = (Spinner) view.findViewById(R.id.positionSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.positions, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
return builder.create();
}
}
addPlayerDialog.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" >
<EditText
android:id="#+id/editFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/fName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/lName" />
<EditText
android:id="#+id/playerNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/playerNumberHint"
android:inputType="number" />
<Spinner
android:id="#+id/positionSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I think you inserted the data to the DB but forgot to call yourListViewAdapter.add method before calling notifyDataSetChanged
Related
In the following program, When I click on Add button in the options menu a dialog is opened wherein the user enters the data which is then shown in the ListView.
There are a number of problems with his code.
1) age.setText in the Custom Adapter causes the app to crash.Commenting out the age.settext line, it works well for the other two TextViews.
2) When i add data in the list using the dialog the second time, the list gets overwritten and no updation is done.
I want the list to be automatically updated when new data is entered rather than over writing it.
3) The data vanishes away when i restart the app. I want the data to be saved permanently.
Code for Custom Adapter is:
package com.example.sakshi.dialogsandmenus;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<Data> list;
private LayoutInflater mLayoutInflator;
public CustomAdapter(Context context, ArrayList list){
this.context=context;
this.list=list;
mLayoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
dob.setText(list.get(position).getDate());
return convertView;
}
}
Code for Main Activity is:
package com.example.sakshi.dialogsandmenus;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static android.R.id.list;
import static com.example.sakshi.dialogsandmenus.R.id.date;
public class MainActivity extends AppCompatActivity{
ListView listview;
ArrayList<Data> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.list_item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
if(id==R.id.add){
filldialog();
}
return super.onOptionsItemSelected(item);
}
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
arrayList = new ArrayList<>();
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
//customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
}
}
1) you have to convert the value of age to String before setText
//age.setText(list.get(position).getAge());
age.setText(Integer.toString(list.get(position).getAge()));
2) Every time new Arraylist initilaization
intarrayList = new ArrayList<>();
ArrayList arrayList = new ArrayList<>();
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
enter code here
3) Use Sqlite or anyStorage Option for data saving
You are setting int value directly to setText of ageTextView. You need to convert int to String before you setting a text to TextView.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
age.setText(String.valueOf(list.get(position).getAge())); // use this it will work
dob.setText(list.get(position).getDate());
return convertView;
}
}
Move these lines outside the onClickListener
arrayList = new ArrayList<>();
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
Because whenever you are clicking the button arraylist is initializing again.
I have Activity that shows only listview (He pulls the data from SQLite database), There is no limit for the data he can shows, and it work out well.
Now, I want to add a new little listview to the MainActivity which will show only the last five of the data.
I could not find anywhere on the network how to do it..
DataListActivity.java
package com.example.ido.grades;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class DataListActivity extends ActionBarActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
CourseDbHelper courseDbHelper;
Cursor cursor;
ListDataAdaptar listDataAdaptar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update_course);
hideActionBar();
listView = (ListView) findViewById(R.id.list_view);
listDataAdaptar = new ListDataAdaptar(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdaptar);
registerForContextMenu(listView);
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
cursor = courseDbHelper.getInformation(sqLiteDatabase);
registerForContextMenu(listView);
if (!cursor.moveToFirst()){
}
else {
do {
String year,semester,course,points,grade;
year = cursor.getString(0);
semester = cursor.getString(1);
course = cursor.getString(2);
points = cursor.getString(3);
grade = cursor.getString(4);
DataProvider dataProvider = new DataProvider(year,semester,course,points,grade);
listDataAdaptar.add(dataProvider);
}
while (cursor.moveToNext());
}
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_data_list, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int mySelectedRowIndex = info.position;
switch (item.getItemId()) {
case R.id.update_item:
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
DataProvider raw2 = (DataProvider)listDataAdaptar.getItem(mySelectedRowIndex);
Intent i = new Intent(DataListActivity.this, UpdateCourseActivity.class);
String year = raw2.getYear();
String semester = raw2.getSemester();
String course = raw2.getCourse();
String points = raw2.getPoints();
String grade = raw2.getGrade();
int semIndex;
if (semester.equals("A'")){
semIndex =1;
}
else if (semester.equals("B'")){
semIndex =2;
}
else{
semIndex=3;
}
i.putExtra("YEAR", year);
i.putExtra("SEMESTER", Integer.toString(semIndex));
i.putExtra("COURSE", course);
i.putExtra("POINTS", points);
i.putExtra("GRADE", grade);
i.putExtra("POS", Integer.toString(mySelectedRowIndex));
startActivity(i);
return true;
case R.id.delete_item:
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
DataProvider raw = (DataProvider)listDataAdaptar.getItem(mySelectedRowIndex);
courseDbHelper.deleteInformation(raw.getYear(), raw.getSemester(), raw.getCourse(), raw.getPoints(), raw.getGrade());
Toast.makeText(this,"delete, pos["+mySelectedRowIndex+"]",Toast.LENGTH_LONG).show();
finish();
startActivity(getIntent());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
private void hideActionBar() {
//Hide the action bar only if it exists
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
}
}
ListDataAdapter.java
package com.example.ido.grades;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ido on 08/08/2015.
*/
public class ListDataAdaptar extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdaptar(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler{
TextView YEAR,SEMESTER,COURSE,POINTS,GRADE;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.YEAR = (TextView)row.findViewById(R.id.textYear);
layoutHandler.SEMESTER = (TextView)row.findViewById(R.id.textSemester);
layoutHandler.COURSE = (TextView)row.findViewById(R.id.textCourse);
layoutHandler.POINTS = (TextView)row.findViewById(R.id.textPoints);
layoutHandler.GRADE = (TextView)row.findViewById(R.id.textGrade);
row.setTag(layoutHandler);
}
else{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.YEAR.setText(dataProvider.getYear());
layoutHandler.SEMESTER.setText(dataProvider.getSemester());
layoutHandler.COURSE.setText(dataProvider.getCourse());
layoutHandler.POINTS.setText(dataProvider.getPoints());
layoutHandler.GRADE.setText(dataProvider.getGrade());
return row;
}
}
You can move to the last position of your current cursor and move to previous rows getting required data. Sort of:
ArrayList string;
if (cursor.moveToLast()){
for (int i = 1; i<=6; i++) {
string.add(cursor.getString(cursor.getColumnIndex("your_data")));
cursor.moveToPrevious();
}
}
cursor.close();
The result will be ArrayList with last 6 strings of your cursor data. You can feed it to the new ArrayAdapter and show it on the screen.
Instead of ArrayList you can create another cursor as well with all existing data and feed it to already existing adapter for example as it's described here:
https://stackoverflow.com/a/18290921/4890659
Ignoring your code, you obviously have an Array of Objects your passing into the constructor of your Array Adapter.
Object[] data = new Object[]{...}
MyArrayAdapter myAdapter = new MyArrayAdapter(data ,... else)
You simply get this data array and append the last 6 elements to a new array.
Object[] data2 = new Object[6]
for(int i = data.length()-7; i<data.length(); i++){
data2[data.length()-i] = data[i]
Then create a new Adapter passing the new data2 array.
MyArrayAdapter myAdapter = new MyArrayAdapter(data2, ... else)
Create method that will return the last 6 rows i cursor [SQL query].
cursor = courseDbHelper.getInformationLast_6(sqLiteDatabase);
SQL:
SELECT * FROM table ORDER BY column DESC [ASC] LIMIT 6;
by this you can get 6 items in your list. Try with following code in your adapter class.
public int getCount() {
return 6;
}
than change your query to limit 6 by ascending order or descending order.
I follow the tutorial on Android Developer "Accessing Contacts" and implement step by step but i encounter a problem which through nullpointerexpection when i try to call the "setonitemclicklistener" inside the fragement. I tried number of solutions but i am not able to resolve the problem. Please help in resolving this issue. Thanks
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sharpapp.findloveone/com.mycompany.myapp.addfrndactivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$900(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5635)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mycompany.myapp.addfrndactivity$PlaceholderFragment.onActivityCreated(addfrndactivity.java:111)
at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1794)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:977)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5595)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
Code Snippet
package com.mycompany.myapp;
import android.annotation.SuppressLint;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.widget.AdapterView;
import android.widget.ListView;
public class addfrndactivity extends ActionBarActivity {
#SuppressLint("InlinedApi")
private final static String[] FROM_COLUMNS = {
Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
ContactsContract.Contacts.DISPLAY_NAME
};
private final static int[] TO_IDS = {
android.R.id.text1
};
static ListView mContactsList;
static long mContactId;
static String mContactKey;
static Uri mContactUri;
private static SimpleCursorAdapter mCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addfrndactivity);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_addfrndactivity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>,
AdapterView.OnItemClickListener{
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_addfrndactivity, container, false);
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(0, null, this);
// Gets the ListView from the View list of the parent activity
mContactsList = (ListView) getActivity().findViewById(android.R.id.list);
// Set the item click listener to be the current fragment.
mContactsList.setOnItemClickListener(this);
// Gets a CursorAdapter
mCursorAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.contacts_list_item,
null,
FROM_COLUMNS, TO_IDS,
0);
// Sets the adapter for the ListView
mContactsList.setAdapter(mCursorAdapter);
}
#SuppressLint("InlinedApi")
private final String[] PROJECTION =
{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
ContactsContract.Contacts.DISPLAY_NAME
};
private static final int CONTACT_ID_INDEX = 0;
private static final int LOOKUP_KEY_INDEX = 1;
// Defines the text expression
#SuppressLint("InlinedApi")
private final String SELECTION =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " LIKE ?" :
ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?";
// Defines a variable for the search string
private String mSearchString;
// Defines the array to hold values that replace the ?
private String[] mSelectionArgs = { mSearchString };
#Override
public void onItemClick(
AdapterView<?> parent, View item, int position, long rowID) {
// Get the Cursor
Cursor cursor = ((SimpleCursorAdapter) parent.getAdapter()).getCursor();
// Move to the selected contact
cursor.moveToPosition(position);
// Get the _ID value
mContactId = cursor.getLong(CONTACT_ID_INDEX);
// Get the selected LOOKUP KEY
mContactKey = cursor.getString(LOOKUP_KEY_INDEX);
// Create the contact's content Uri
mContactUri = ContactsContract.Contacts.getLookupUri(mContactId, mContactKey);
}
#Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {
/*
* Makes search string into pattern and
* stores it in the selection array
*/
mSelectionArgs[0] = "%" + mSearchString + "%";
// Starts the query
return new CursorLoader(
getActivity(),
ContactsContract.Contacts.CONTENT_URI,
PROJECTION,
SELECTION,
mSelectionArgs,
null
);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Put the result Cursor in the adapter for the ListView
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// Delete the reference to the existing Cursor
mCursorAdapter.swapCursor(null);
}
}
}
activity_addfrndactivity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mycompany.myapp.addfrndactivity"
tools:ignore="MergeRootFrame" />
fragement_addfrndactivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mycompany.myapp.addfrndactivity$PlaceholderFragment">
</RelativeLayout>
contact_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
goto this layout :
R.layout.fragment_addfrndactivity
and make sure you have a ListView with this id : android.R.id.list
most probably you dont have
so change this line to your id in the layout xml file:
// Gets the ListView from the View list of the parent activity
mContactsList = (ListView) getActivity().findViewById(ID_FROM_YOUR_XML_FILE);
I have built three row layout. Assume RowLayout1, RowLayout2, RowLayout3 are the three row layouts. I would like to add RowLayout1 as first row, followed by RowLayout2 and as last row rowLayout3. Data for RowLayout2 comes from sqllite, other data from values .
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Paasurams extends Activity {
private Divyadesamdb dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pasuram);
dbHelper = new Divyadesamdb(this);
dbHelper.open();
/*
* Check if data already exist if total count is
*/
int totalRows = dbHelper.getCountAllPasurams();
Log.d("VC", "totalRows = " + totalRows);
//dbHelper.deleteAllPasurams();
//Log.d("VC", "totalRows after delete = " + totalRows);
if (totalRows < 4535) {
// Clean all data commented to improve performance
dbHelper.deleteAllPasurams();
// Add some data
dbHelper.insertPasurams();
totalRows = dbHelper.getCountAllPasurams();
Log.d("VC","After insertPasurams rows found are "+totalRows);
}
Intent intent = getIntent();
String mcategory = intent.getStringExtra(MainActivity.EXTRA_CATEGORY);
String mstart = intent.getStringExtra(MainActivity.EXTRA_START);
String mending = intent.getStringExtra(MainActivity.EXTRA_ENDING);
String mpasuramNumber = intent
.getStringExtra(MainActivity.EXTRA_PASURAMNUMBER);
String maayiram = intent.getStringExtra(MainActivity.EXTRA_AAYIRAM);
String mazhwaar = intent.getStringExtra(MainActivity.EXTRA_AZHWAAR);
String mmangalasasanamOn = intent
.getStringExtra(MainActivity.EXTRA_MANGALASASANAMON);
String msubCategory = intent
.getStringExtra(MainActivity.EXTRA_SUBCATEGORY);
String mtitle = intent.getStringExtra(MainActivity.EXTRA_TITLE);
// Generate ListView from SQLite Database
displayListView(mpasuramNumber, maayiram, mazhwaar, mcategory,
mmangalasasanamOn, msubCategory, mtitle, mstart, mending);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void displayListView(String mpasuramNumber, String maayiram,
String mazhwaar, String mcategory, String mmangalasasanamOn,
String msubCategory, String mtitle, String mstart, String mending) {
String category = mcategory;
String starting = mstart;
String ending = mending;
String pasuramNumber = mpasuramNumber;
String aayiram = maayiram;
String azhwaar = mazhwaar;
String mangalasasanamOn = mmangalasasanamOn;
String subCategory = msubCategory;
String title = mtitle;
int rowsFound = 0;
Cursor cursor = dbHelper.fetchAllPasurams(pasuramNumber, aayiram,
azhwaar, category, mangalasasanamOn, subCategory, title,
starting, ending);
/*
* How many rows returned from the query
*/
rowsFound = cursor.getCount();
// the desired columns to be bound
String[] columns = new String[] {
Divyadesamdb.PASURAMS_COLUMN_PAASURAMNUMBER,
Divyadesamdb.PASURAMS_COLUMN_AAYIRAM,
Divyadesamdb.PASURAMS_COLUMN_AZHWAAR,
Divyadesamdb.PASURAMS_COLUMN_CATEGORY,
Divyadesamdb.PASURAMS_COLUMN_MANGALASASANAMON,
Divyadesamdb.PASURAMS_COLUMN_PAASURAM_EN_STR,
Divyadesamdb.PASURAMS_COLUMN_SUBCATEGORY,
Divyadesamdb.PASURAMS_COLUMN_TITLE,
Divyadesamdb.PASURAMS_COLUMN_TITLENUMBER,
Divyadesamdb.PASURAMS_COLUMN_IMAGE_ID };
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.tvPaasuramNumber, R.id.tvAayiram,
R.id.tvAzhwaar, R.id.tvCategory, R.id.tvMangalasasanamOn,
R.id.tvPaasuram, R.id.tvSubCategory, R.id.tvTitle,
R.id.tvtvTitleNumber, R.id.ivAzhwaar };
// create the adapter using the cursor pointing to the desired data
// as well as the layout information
MyCursorAdapter dataAdapter = new MyCursorAdapter(this,
R.layout.paasuram_single_item, cursor, columns, to, 0);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(dataAdapter);
Log.d("VC", "Found rows " + rowsFound);
}
// extend the SimpleCursorAdapter to create a custom class where we
// can override the getView to change the row colors
private class MyCursorAdapter extends SimpleCursorAdapter {
Context mContext;
public MyCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// get reference to the row
View view = super.getView(position, convertView, parent);
// check for odd or even to set alternate colors to the row
// background
// want to get the value of this text view,
// but not getting handle.
if (position % 2 == 0) {
view.setBackgroundColor(Color.rgb(238, 233, 233));
} else {
view.setBackgroundColor(Color.rgb(255, 255, 255));
}
return view;
}
}
}
When I first run my app, the CheckBox items in my ListView are unchecked. In my layout.xml I have a single CheckBox above my ListView items. When that single CheckBox above my ListView is checked it should mark all the CheckBox items in my ListView as checked. My code below does not update the display of my CheckBox items in my ListView as checked but when I tried to get the boolean of each CheckBox item in my ListView by calling checkItem.isChecked() and let it display in my logcat, it returns true. Did I miss something?
package com.usjr.sss.fragment;
import java.util.ArrayList;
import com.usjr.sss.R;
import com.usjr.sss.activity.CourseFragmentActivity;
import com.usjr.sss.adapter.InfoTechAdapter;
import com.usjr.sss.adapter.SubjectDbAdapter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
public class InfoTechFirstYearFragment extends Fragment {
private CheckBox checkFirstYearFirstSem;
private ListView listItFirstYearFirstSem;
private ListView listItFirstYearSecondSem;
private InfoTechAdapter infoTechAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_it_first_year, container,
false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("InfoTechFirstYearFragment", "onActivityCreated");
listItFirstYearFirstSem = (ListView) getActivity().findViewById(
R.id.listItFirstYearFirstSem);
listItFirstYearSecondSem = (ListView) getActivity().findViewById(
R.id.listItFirstYearSecondSem);
}
#Override
public void onStart() {
super.onStart();
Log.i("InfoTechFirstYearFragment", "onStart");
SubjectDbAdapter subjectDbAdapter = new SubjectDbAdapter(getActivity());
subjectDbAdapter.open();
Cursor cursor = subjectDbAdapter.fetchAllSubjects();
ArrayList<String> arrayListSubject = new ArrayList<String>();
ArrayList<String> arrayListFirstSem = new ArrayList<String>();
ArrayList<String> arrayListSecondSem = new ArrayList<String>();
while (cursor.moveToNext()) {
String subject = cursor.getString(cursor
.getColumnIndexOrThrow(SubjectDbAdapter.SUBJECT_ID));
arrayListSubject.add(subject);
}// end while
subjectDbAdapter.close();
int index;
/**
* 1st yr 1st sem
*/
for (index = 0; index < 9; index++) {
arrayListFirstSem.add(arrayListSubject.get(index));
}
infoTechAdapter = new InfoTechAdapter(
(CourseFragmentActivity) getActivity(), arrayListFirstSem);
listItFirstYearFirstSem.setAdapter(infoTechAdapter);
/**
* 1st yr 2nd sem
*/
for (index = 9; index < 18; index++) {
arrayListSecondSem.add(arrayListSubject.get(index));
}
infoTechAdapter = new InfoTechAdapter(
(CourseFragmentActivity) getActivity(), arrayListSecondSem);
listItFirstYearSecondSem.setAdapter(infoTechAdapter);
/**
* MARK ALL THE CHECKBOX AS CHECKED
*/
checkFirstYearFirstSem = (CheckBox) getActivity().findViewById(
R.id.checkFirstYearFirstSem);
checkFirstYearFirstSem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (checkFirstYearFirstSem.isChecked()) {
Toast.makeText(getActivity(), "ckecked", Toast.LENGTH_SHORT)
.show();
int count = listItFirstYearFirstSem.getCount();
for (int index = 0; index < count; index++) {
// View viewMy =
// listItFirstYearFirstSem.getChildAt(index);
// Object id = v.getTag();
View viewItem = (View) listItFirstYearFirstSem
.getAdapter().getView(index, getView(),
listItFirstYearFirstSem);
CheckBox checkItem = (CheckBox) viewItem
.findViewById(R.id.subject);
checkItem.setChecked(true);
listItFirstYearFirstSem.setItemChecked(index, true);
infoTechAdapter.notifyDataSetChanged();
Log.i("checkItem",
String.valueOf(checkItem.getText().toString()));
Log.i("checkItem",
String.valueOf(checkItem.isChecked()));
}
} else {
Toast.makeText(getActivity(), "unckecked",
Toast.LENGTH_SHORT).show();
}// end if-else(checkFirstYearFirstSem.isChecked())
}// end onClick
});// end OnClickListener
}// end onStart()
}
I solved it myself yey!
Instead of using
View viewItem = (View) listItFirstYearFirstSem.getAdapter().getView(index, getView(), listItFirstYearFirstSem);
I used
View viewItem = listItFirstYearFirstSem.getChildAt(index);
Then
CheckBox checkItem = (CheckBox) viewMy.findViewById(R.id.subject);
checkItem.setChecked(true);