I faced with problem that I cant figure out. I have FragmentA and FragmentB. When I do first time transaction to FragmentB ListView doesn`t filling. If I press "back" and do transaction again, then ListView is filling.
Whats wrong with my code?
Here is my Fragment Code:
public class RegionListFrag extends android.support.v4.app.Fragment {
ArrayList<String> names = new ArrayList<>();
RegionAddAdapter regionAddAdapter;
ListView listView;
DBHelper dbHelper;
SQLiteDatabase db;
final String LOG_TAG = "myLogs";
RegionNameClass regionNameClass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
((MainActivity)getActivity()).changeTbOn();
MainActivity.toolbar.setTitle("Regions");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.region_layout, container, false);
MainActivity.toolbar.setTitle("Regions");
listView = (ListView) rootView.findViewById(R.id.region_lv);
regionAddAdapter = new RegionAddAdapter(getActivity(),
setRv());
listView.setAdapter(regionAddAdapter);
listView.setPadding(0, 110, 0, 0);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_toolbar, menu);
super.onCreateOptionsMenu(menu,inflater);
Menu myMenu = menu;
MenuItem nextItem = myMenu.findItem(R.id.accept_category);
nextItem.setVisible(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
getFragmentManager().popBackStack();
getFragmentManager().beginTransaction().commit();
return true;
}
if (item.getItemId() == R.id.accept_category) {
}
return super.onOptionsItemSelected(item);
}
ArrayList<RegionNameClass> setRv(){
dbHelper = new DBHelper(getActivity());
db = dbHelper.getWritableDatabase();
Cursor c = db.query("regiontable", null, null, null, null, null,
null);
ArrayList<RegionNameClass> rvArray = new ArrayList<RegionNameClass>();
while(c.moveToNext()){
String name = c.getString(c.getColumnIndex("regNames"));
RegionNameClass regionObj = new RegionNameClass(name);
rvArray.add(regionObj);
}
Log.d(LOG_TAG, "array size - " + rvArray.size());
return rvArray;
}
}
Here is my Adapter:
public class RegionAddAdapter extends ArrayAdapter<RegionNameClass> {
private static ArrayList<RegionNameClass> list = new ArrayList<RegionNameClass>();
private final Activity context;
public ArrayList<RegionNameClass> selectedStrings = new ArrayList<RegionNameClass>();
final String LOG_TAG = "myLogs";
RegionNameClass regionNameClass;
public RegionAddAdapter(Activity context, ArrayList<RegionNameClass> top) {
super(context, R.layout.region_row, list);
this.context = context;
list = top;
}
static class ViewHolder {
protected TextView myTv;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
RegionNameClass myClass = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.region_row, parent, false);
}
TextView tvName = (TextView) convertView.findViewById(R.id.region_tv);
tvName.setText(myClass.name);
return convertView;
}
}
Please check in RegionAddAdapter, update as below
public RegionAddAdapter(Activity context, ArrayList<RegionNameClass> top) {
super(context, R.layout.region_row, top);
this.context = context;
list = top;
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to implement search in my app, and activity crashes when I click on search icon. The error is: https://i.imgur.com/CDOE9fT.png
Here is the code of Activity:
public class SearchActivity extends AppCompatActivity implements OnItemClickListener, AdapterView.OnItemClickListener {
DBHelper dbHelper;
SQLiteDatabase database;
ArrayList<Reminder> ReminderList = new ArrayList<>();
ListView listView;
MaterialSearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Material search");
toolbar.setTitleTextColor(Color.parseColor("#FFFFFF"));
dbHelper = new DBHelper(this);
database = dbHelper.getWritableDatabase();
//listView = (ListView) findViewById(R.id.ListOfReminders);
listView = (ListView)findViewById(R.id.ListOfReminders);
Cursor cursor = database.query(TABLE_REMINDERS, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
int idIndex = cursor.getInt(cursor.getColumnIndex(DBHelper.KEY_ID));
String nameIndex = cursor.getString(cursor.getColumnIndex(KEY_NAME));
String hourIndex = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_HOUR));
String dateIndex = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_DATE));
String name = nameIndex;
String hour = hourIndex;
String date = dateIndex;
ReminderList.add(new Reminder(idIndex, name, hour, date));
ReminderListAdapter2 adapter = new ReminderListAdapter2(this, R.layout.reminder_view2, ReminderList);
adapter.setListener(this);
listView.setAdapter(adapter);
} while (cursor.moveToNext());
} else
Log.d("mLog", "0 rows in db");
searchView = (MaterialSearchView)findViewById(R.id.search_view);
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
#Override
public void onSearchViewShown() {
}
#Override
public void onSearchViewClosed() {
listView = (ListView)findViewById(R.id.ListOfReminders);
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this, android.R.layout.simple_list_item_1,ReminderList);
listView.setAdapter(adapter);
}
}); searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText != null && !newText.isEmpty()){
ArrayList<Reminder> lstFound = new ArrayList<>();
for(Reminder item:ReminderList){
if(item.getName().contains(newText))
lstFound.add(new Reminder(item.getId(), item.getName(), item.getHour(), item.getDate()));
}
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this,android.R.layout.simple_list_item_1,lstFound);
listView.setAdapter(adapter);
} else {
ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this,android.R.layout.simple_list_item_1,ReminderList);
listView.setAdapter(adapter);
}
return true;
}});
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_item,menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void OnItemClick(View view, int position, int id, String name, String date, String hour) {
}}
Code of adapter:
public class ReminderListAdapter2 extends ArrayAdapter<Reminder> {
private Context mContext;
private int mResource;
OnItemClickListener listener;
public ReminderListAdapter2(#NonNull Context context, int resource, #NonNull ArrayList<Reminder> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
public void setListener(OnItemClickListener listener) {
this.listener = listener;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final int id = getItem(position).getId();
final String name = getItem(position).getName();
final String hour = getItem(position).getHour();
final String date = getItem(position).getDate();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
final TextView resId = convertView.findViewById(R.id.textId);
final TextView resName = convertView.findViewById(R.id.textName);
final TextView resHour = convertView.findViewById(R.id.textHour);
final TextView resDate = convertView.findViewById(R.id.textDate);
resId.setText(String.valueOf(id));
resName.setText(name);
resHour.setText(hour);
resDate.setText(date);
return convertView;
}}
Why object reference is null? Sorry if it is a stupid error, it's first app.
I tried to change lstFound.add(new Reminder(item.getId(), item.getName(), item.getHour(), item.getDate())); with lstFound.add(this);, but it is also null reference.
According to documentation:
To display a more custom view for each item in your dataset, implement a ListAdapter. For example, extend BaseAdapter and create and configure the view for each data item in
If so the first argument of layout inflater method should be layout instead of int
e.g convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
In your case you are trying to inflate int instead of layout
convertView = inflater.inflate(mResource, parent, false);
Closed.
The error was in ReminderListAdapter2 adapter = new ReminderListAdapter2(SearchActivity.this, android.R.layout.simple_list_item_1,ReminderList);
androidR.layout.simple_list_item_1 need to be changed to R.layout.reminderview2
I'm trying to refresh my listview on spinner item selection. I know there have a lot of solution but i could not solve it.I have tried notifyDataSetChanged() but it's not working.
I'm new in android. Please help me i,m stuck on it.
Here is my Adapter class:
public class ListDataAdaptar extends ArrayAdapter {
List<DataProvider> mlist;
public ListDataAdaptar(Context context, int resource,List<DataProvider> list) {
super(context, resource);
mlist=list;
}
static class LayoutHandler{
TextView amount,date,title;
TextView total;
}
#Override
public int getCount() {
return mlist.size();
}
#Nullable
#Override
public Object getItem(int position) {
return mlist.get(position);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View mView= convertView;
LayoutHandler layoutHandler;
if (mView==null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView=layoutInflater.inflate(R.layout.display_income_row,parent,false);
layoutHandler=new LayoutHandler();
layoutHandler.title= (TextView) mView.findViewById(R.id.income );
layoutHandler.amount=(TextView)mView.findViewById(R.id.income_amount);
layoutHandler.date= (TextView) mView.findViewById(R.id.date);
mView.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) mView.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
Double s= new Double(dataProvider.getMoney());
layoutHandler.amount.setText(""+s);
layoutHandler.date.setText(dataProvider.getDate());
layoutHandler.title.setText(dataProvider.getName());
return mView;
}
}
And in this class i'm using Spinner:
public class IncomeReport extends AppCompatActivity {
ListView list;
Toolbar toolbar;
private DatabaseHandler handler;
private List<DataProvider> amountList;
private ListDataAdaptar listDataAdapter;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.income_report);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
list = (ListView)findViewById(R.id.listView);
amountList = new ArrayList<>();
handler = new DatabaseHandler(this);
}
public List getMonthItem() {
Cursor cursor = handler.displayIncomeMonthReport();
if (cursor.moveToFirst()) {
do {
double amount;
String payer;
String note;
String date;
amount = Double.parseDouble(cursor.getString(cursor.getColumnIndex(handler.AMOUNT)));
payer = cursor.getString(cursor.getColumnIndex(handler.PAYER_NAME));
note = cursor.getString(cursor.getColumnIndex(handler.NOTE));
date=cursor.getString(cursor.getColumnIndex(handler.DATE));
DataProvider provider = new DataProvider(amount, payer,note,date);
amountList.add(provider);
listDataAdapter = new ListDataAdaptar(this, R.layout.display_income_row, amountList);
list.setAdapter(listDataAdapter);
listDataAdapter.notifyDataSetChanged();
} while (cursor.moveToNext());
cursor.close();
handler.close();
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.spinner_menu, menu);
MenuItem item = menu.findItem(R.id.spinner);
spinner = (Spinner) MenuItemCompat.getActionView(item);
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.report, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final int number = getIntent().getExtras().getInt("pos1");
spinner.setSelection(number);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
switch (pos){
case (0):
getMonthItem();
listDataAdapter.notifyDataSetChanged();
break;
case (1):
getYearItem();
listDataAdapter.notifyDataSetChanged();
break;
default:
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return true;
}
}
First , I want to say that you should not new Adapter and setAdapter in getMonthItem() even in do...while ,do it in onCreate() is better. Then , when you select item , are you sure your data list has changed ? Check it again ,hope it helps.
I made two activities, one for listing the data and second activity is form for entering the data. For this, I used List and custom ArrayAdapter as I did it when putting the two displays in same activity. When the two displays are in same window, there is no problem. After I separated activities, I put the List and custom ArrayAdapter in separate java file so that I can access them from 2 activities.
I saved the data by calling static function
"addRestaurant(Restaurant r)"
from DetailForm.java. Custom Adapter RestaurantAdapter is made static so that it can fit in addRestaurant(Restaurant).After doing this, the data is saved but the ListView does not display them. Can any one help me here ?
/*************************MainActivity.java **************************/
public class MainActivity extends ActionBarActivity {
public final static String ID_EXTRA="apt.tutorial._ID";
RestaurantList restaurantlist = null;
ListView list = null;
#Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
restaurantlist = new RestaurantList(MainActivity.this);
list = (ListView) findViewById(R.id.list);
restaurantlist.setlistadapter(list);
}
#Override public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId() == R.id.option) {
Intent intent = new Intent(MainActivity.this, DetailForm.class);
startActivity(intent);
return (true);
}
return true;
}
}
/*******************************DetailForm.Java ********************/
public class DetailForm extends ActionBarActivity {
EditText name=null;
EditText address=null;
EditText notes=null;
RadioGroup types=null;
String restaurantId=null;
Restaurant current = null;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_form);
name=(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.addr);
notes=(EditText)findViewById(R.id.notes);
types=(RadioGroup)findViewById(R.id.types);
Button save=(Button)findViewById(R.id.save);
save.setOnClickListener(onSave);
restaurantId = getIntent().getStringExtra(MainActivity.ID_EXTRA);
}
public View.OnClickListener onSave=new View.OnClickListener(){
public void onClick(View v) {
String type=null;
current = new Restaurant();
String newname = name.getText().toString();
String newaddr = address.getText().toString();
current.setName(newname);
current.setAddress(newaddr);
current.setNotes(notes.getText().toString());
switch (types.getCheckedRadioButtonId()) {
case R.id.sit_down:
current.setType("sit_down");
break;
case R.id.take_out:
current.setType("take_out");
break;
case R.id.delivery:
current.setType("delivery");
break;
}
RestaurantList.addRestaurant(current); //adapter.add(current); // add values
name.setText("");
address.setText("");
notes.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
}
};
#Override public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option, menu);
return true;
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.ViewList) {
Intent intent = new Intent(DetailForm.this, MainActivity.class);
startActivity(intent);
return (true);
}
return true;
}
}
/*************************RestaurantList.java ***********************/
public class RestaurantList {
List<Restaurant> model;
static RestaurantAdapter adapter;
public RestaurantList(Context context) {
model = new ArrayList<Restaurant>();
adapter = new RestaurantAdapter(context);
}
public void setlistadapter(ListView listview){
listview.setAdapter(adapter);
}
public static void addRestaurant(Restaurant r){
adapter.add(r);
}
public class RestaurantAdapter extends ArrayAdapter<Restaurant> {
Context mycontext;
RestaurantAdapter(Context context){
super(context, R.layout.row, model);
mycontext = context;
}
#Override public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
RestaurantHolder holder = null;
if (row == null){
LayoutInflater inflater = ((Activity)mycontext).getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
holder = new RestaurantHolder(row);
row.setTag(holder);
} else {
holder = (RestaurantHolder)row.getTag();
}
holder.populateFrom(model.get(position));
return (row);
}
}
public static class RestaurantHolder{
private TextView name=null;
private TextView address=null;
private ImageView icon=null;
RestaurantHolder(View row) {
name=(TextView)row.findViewById(R.id.title);
address=(TextView)row.findViewById(R.id.address);
icon=(ImageView)row.findViewById(R.id.icon);
}
void populateFrom(Restaurant r){
name.setText(r.getName());
address.setText(r.getAddress());
if (r.getType().equals("sit_down")) {
icon.setImageResource(R.drawable.ball_red);
}
else if (r.getType().equals("take_out")) {
icon.setImageResource(R.drawable.ball_yellow);
}
else {
icon.setImageResource(R.drawable.ball_green);
}
}
}
}
List<Restaurant> modelis always empty that is why you are not able to see the listView
public class DetailForm extends AppCompatActivity implements View.OnClickListener {
EditText etName;
EditText etAddress;
EditText etNote;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName= (EditText) findViewById(R.id.name);
etAddress= (EditText) findViewById(R.id.address);
etNote = (EditText) findViewById(R.id.place);
save= (Button) findViewById(R.id.save);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String name =etName.getText().toString();
String address=etName.getText().toString();
String notes= etNote.getText().toString();
Restaurant restaurant=new Restaurant(name,address,notes);
RestaurantList.addRestaurant(restaurant);
Intent intent=new Intent(this, ListingActivity.class);
startActivity(intent);
}
}
Listing Activity
public class ListingActivity extends AppCompatActivity{
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
listView= (ListView) findViewById(R.id.listView);
listView.setAdapter(new RestaurantAdapter(this,RestaurantList.getRestaurentsList()));
}
}
Restaurant
public class Restaurant {
String name;
String address;
String notes;
public Restaurant(String name, String address, String notes) {
this.name = name;
this.address = address;
this.notes = notes;
}
}
RestaurantAdapter
public class RestaurantAdapter extends ArrayAdapter {
List<Restaurant> mRestaurants;
private LayoutInflater mLayoutInflater;
public RestaurantAdapter(Context context, List restorentsList) {
super(context, R.layout.row, restorentsList);
mRestaurants = restorentsList;
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RestaurantHolder holder = new RestaurantHolder();
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.row, parent, false);
holder.name= (TextView) convertView.findViewById(R.id.name);
holder.address= (TextView) convertView.findViewById(R.id.address);
holder.note= (TextView) convertView.findViewById(R.id.note);
convertView.setTag(holder);
} else {
holder = (RestaurantHolder) convertView.getTag();
}
final Restaurant restaurant = mRestaurants.get(position);
holder.name.setText(restaurant.name);
holder.address.setText(restaurant.address);
holder.note.setText(restaurant.notes);
return (convertView);
}
public static class RestaurantHolder {
private TextView name;
private TextView address;
private TextView note;
}
}
RestaurantList
public class RestaurantList {
private static List<Restaurant> restaurants=new ArrayList<>();
public static void addRestaurant(Restaurant restaurant) {
restaurants.add(restaurant);
}
public static List<Restaurant> getRestaurentsList()
{
return restaurants;
}
}
I have provided the snippens for all the operations hope this helps
The problem is you start a "new MainActivity" when you click on ViewList in your menu instead of back to the "original MainActivity" (if don't get it, press back button after Saved :) ). If you really want to make the least changes to see the result, change your onOptionsItemSelected() in DetailForm:
#Override public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.ViewList) {
finish();
}
return true;
}
I am currently modifying an android app that I need to add a listview to an existing fragment. As I am new to android, I am just imitating the code from the apps. I created a new arrayadapter, a new class of data and made some modifies to the existing fragment class. The problem is I cannot see my list in the app. Below are my codes.
Adapter
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRec;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRec)
{
super(context, resourceId, checkInRec);
this.resourceId = resourceId;
this.context = context;
this.checkInRec = checkInRec;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_name);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkindate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_points);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
CheckInRecord.CheckInRec checkInrec = checkInRec.get(position);
textViewName.setText(checkInrec.providerName);
textViewCheckInDate.setText(checkInrec.checkInDate);
textViewPoints.setText(checkInrec.providerPoints);
ImageLoader.getInstance().displayImage(checkInrec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRec.get(position).isPrize);}
}
Data type
public class CheckInRecord {
public int userPoints;
public String userName;
public String gender;
public String birthDate;
public String location;
public String userIcon;
public List<CheckInRec> checkInRecList = new ArrayList<CheckInRec>();
public void addCheckInRec(String providerName, String providerLocation, String providerIcon,
String checkInDate, int providerPoints, int isPrize){
CheckInRec checkInRec = new CheckInRec();
checkInRec.providerName = providerName;
checkInRec.providerLocation = providerLocation;
checkInRec.providerIcon = providerIcon;
checkInRec.checkInDate = checkInDate;
checkInRec.providerPoints = providerPoints;
checkInRec.isPrize = isPrize;
checkInRecList.add(checkInRec);
}
public List<String> recImages(){
List<String> resultList = new ArrayList<String>();
if (this.checkInRecList == null){
return resultList;
}
for (CheckInRec rec : this.checkInRecList){
resultList.add(rec.providerIcon);
}
return resultList;
}
public class CheckInRec{
public String providerName;
public String providerLocation;
public String providerIcon;
public String checkInDate;
public int providerPoints;
public int isPrize;
}
}
Fragment
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRec = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppDataManager.getInstance().setAllowCheckIn(true);
progressDialog = ProgressDialog.show(getActivity(), "", "");
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) view.findViewById(R.id.tv_name);
textViewPoints = (TextView) view.findViewById(R.id.tv_points);
ListView listViewCheckInRec = (ListView) view.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity().getApplicationContext(), R.layout.row_record, checkInRec);
listViewCheckInRec.setAdapter(recordArrayAdapter);
return view;
}
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
refreshName();
}
}
public void refreshName() {
progressDialog = ProgressDialog.show(getActivity(), "", "");
AppDataManager dataManager = AppDataManager.getInstance();
ApiManager.getInstance().checkInHistories(dataManager.getUserToken(), dataManager.getUserPhone(), Utility.getPictureSize(), this);
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
// this.checkInRec.clear();
// this.checkInRec.addAll(checkInRecord.checkInRecList);
//
// recordArrayAdapter.notifyDataSetChanged();
}
}
}
The problem is I cannot see my list in the app.
That is because checkInRec does now have any elements inside of it.
I can really tell that it is empty because you commented this out:
// this.checkInRec.clear(); //clear the old data from the list
// this.checkInRec.addAll(checkInRecord.checkInRecList); //add all the data inside the checkInRecord.checkInRecList
//
// recordArrayAdapter.notifyDataSetChanged(); //refreshing the ListView to display the new data
now what are those doing is that clearing the old list array and adding the new set of data from checkInRecord.checkInRecList and refreshing the ListView so those new data are implemented/shown in your ListView.
I have the following code which displays a ListFragment. Once a row is selected i turn the row's background to red. If i click another row then that turns red but the first selected row remains red.
How can i turn the colour back for the deselected rows? I've tried a few things like, clearCoices(), list.invalidate(), list.requestLayout(), list.refreshDrawableState. None of them seem to work.
Thanks in advance, Matt
public class CarerDetailsFragment extends ListFragment{
private static final String TAG = CarerDetailsFragment.class.getSimpleName();
MySimpleArrayAdapter myAdapter;
TwoDimensionalArrayList rotaArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getArguments();
if(b != null){
rotaArray = (TwoDimensionalArrayList) b.get("rotaArray");
Log.e(TAG, "rotaArray in CarerDetailsFragment has size " + rotaArray.size());
}else{
Log.e(TAG, "Bundle b = null!!!!!!!!!!!");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.carerdetailsfragmentlayout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
myAdapter = (MySimpleArrayAdapter) new MySimpleArrayAdapter(getActivity(), rotaArray);
setListAdapter(myAdapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.e(TAG, "onListItemClick");
l.clearChoices();
v.setBackgroundColor(Color.parseColor("#FF0000"));
String name;
String actTimeIn;
String actTimeOut;
String doubleUpValue;
String status;
String startTime;
String clientID;
String notes;
Bundle b = new Bundle();
b.putString("name", name);
b.putString("actTimeIn", actTimeIn);
Fragment newFragment = new CarerPurposeOfCallFragment();
newFragment.setArguments(b);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.carerpurposeofcall, newFragment);
//transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
private class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<?> list;
String justTime;
String statusField;
String callID;
String needName;
public MySimpleArrayAdapter(Context context, ArrayList<?> list) {
super(context, R.layout.rotarowlayout);
Log.e(TAG, "inside adapter constructor");
this.context = context;
this.list = list;
//Log.e(TAG, "list has size of " + this.list.size());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rotarowlayout, parent, false);
TextView startTime = (TextView) rowView.findViewById(R.id.rowstarttime);
TextView duration = (TextView) rowView.findViewById(R.id.rowduration);
TextView status = (TextView) rowView.findViewById(R.id.rowstatus);
TextView name = (TextView) rowView.findViewById(R.id.rowclientname);
final ImageView noteStatus = (ImageView)rowView.findViewById(R.id.notestatus);
return rowView;
}
#Override
public int getCount() {
if(this.list != null){
return this.list.size();
}else{
return 0;
}
}
}// end of adapter class
}//end of CarerListFragment
Use myAdapter.toggleSelection(position); to select or unselect.
You probably need to have selectedList and do checks when you toggle.