here I have a Fragment, I use this code and everything works normally, and what I want to do is update my shown list if there is a new file, could you guys give any advice or hint?
CODE:
public class HomeFragment extends Fragment {
public static final String TITLE = "title";
private List<String> library = new ArrayList<String>();
private TextView tv;
private ListView lv;
private ArrayAdapter<String> adapter;
public static Handler handHF;
private String[] temp;
private Object UIlock = new Object();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_fragment, container,
false);
library = getLibraryList();
if (!library.isEmpty()) {
if (tv != null) {
tv.setVisibility(View.GONE);
} else {
temp = library.toArray(new String[library.size()]);
lv = (ListView) rootView.findViewById(R.id.library_list);
adapter = new ArrayAdapter<String>(rootView.getContext(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
setListener(lv);
tv = (TextView) rootView.findViewById(R.id.library_tv1);
tv.setVisibility(View.GONE);
tv = null;
}
} else {
tv = (TextView) rootView.findViewById(R.id.library_tv1);
tv.setText("No Manga found...");
}
return rootView;
}
#SuppressLint("HandlerLeak")
#Override
public void onResume() {
/*
* Fragment on pause state
*/
super.onResume();
handHF = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
refreshAdapter();
}
}
};
}
private void setListener(ListView lv) {
/*
* Sets listener on listView
*/
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(),
ChapterActivity.class);
myIntent.putExtra(TITLE, parent.getItemAtPosition(position)
.toString());
startActivity(myIntent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
return true;
}
});
}
private final List<String> getLibraryList() {
/*
* Returns List<String> of library
*/
List<String> l = new ArrayList<String>();
File dir = new File(Constants.UNDUH);
if (dir.exists()) {
File[] dirs = dir.listFiles();
for (File i : dirs) {
l.add(i.getName());
}
return l;
} else {
return l;
}
}
private void refreshAdapter() {
/*
* It will update library and
*/
synchronized (UIlock) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (tv != null) {
tv.setVisibility(View.GONE);
}
library = getLibraryList();
temp = library.toArray(new String[library.size()]);
lv = (ListView) getActivity().findViewById(
R.id.library_list);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
}
});
}
}
}
any advice will be appreciated, thank you!
Update your list of string which you are passing to the ListView in your case you are using
private String[] temp;
Use notifyDataSetChanged Method, just call this after your adapter and it will automatically adds more items to list if your temp[] increments.
like this
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
Where you are adding more data into temp[]
add an extra line
((ArrayAdapter) lv.getAdapter()).notifyDataSetChanged();
Related
I am new in android. I am connecting with server Mysql not using any API.
This is my MachineSearch code. In this list3.get(position) gives me previous list like without filter old data.
Everythings works perfect, but when I search, I got Previous List3 data.
On search, I got new filter data, but When I click I get old. And I have to pass two data id which hidden and name to be show.
Thanks in advance
public class MachineSearchList extends AppCompatActivity {
SearchView searchView;
CustomAdaptor adapter;
ArrayList<String> list1;
ArrayList<String> list2;
ArrayList<String> list3;
ListView listView;
String dataItemName;
String dataItemId;
ArrayList<SearchSetterandGetter> arrayList = new ArrayList<SearchSetterandGetter>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
setContentView(R.layout.employeelist_main);
super.onCreate(savedInstanceState);
listView = (ListView) findViewById(R.id.listemp);
searchList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dataItemName = list3.get(position);
dataItemId = list2.get(position);
openActivityOne();
}
});
searchView = (SearchView) findViewById(R.id.searchview_lay_act_xml);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return false;
}
});
}
public void searchList() {
try {
ArrayList<MachineSetterGetter> machineList = null;
MachineSearch emp = new MachineSearch();
machineList = emp.getmachineSearch();
list1 = new ArrayList<>();
list2 = new ArrayList<>();
list3 = new ArrayList<>();
for (MachineSetterGetter machine : machineList) {
list1.add(machine.getiTemId());
list2.add(machine.getiTemCode());
list3.add(machine.getiTemName());
}
for (int i = 0; i < list1.size(); i++) {
SearchSetterandGetter model = new SearchSetterandGetter(list1.get(i), list2.get(i), list3.get(i));
arrayList.add(model);
}
adapter = new CustomAdaptor(getApplicationContext(), arrayList);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
} catch (Exception exh) {
Log.e("******************", "check" + exh);
}
}
public void openActivityOne() {
Intent resultIntend = new Intent();
resultIntend.putExtra("result", dataItemName);
resultIntend.putExtra("hideId", dataItemId);
setResult(RESULT_OK, resultIntend);
finish();
}
}
my custom Adaptor
public class CustomAdaptor extends BaseAdapter {
Context applicationContext;
LayoutInflater inflater;
ArrayList<String> dataa1;
ArrayList<String> dataa2;
ArrayList<String> dataa3;
ArrayList<String> dataa3Search;
ArrayList<SearchSetterandGetter> modelList;
ArrayList<SearchSetterandGetter> arrayList;
public String getId;
public String getCode;
public String getName;
public CustomAdaptor(Context pplicationContext, ArrayList<SearchSetterandGetter> model) {
applicationContext=pplicationContext;
this.modelList=model;
this.arrayList = new ArrayList<SearchSetterandGetter>();
this.arrayList.addAll(modelList);
inflater = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return modelList.size();
}
#Override
public Object getItem(int position) {
return modelList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.employeeview_no_name, null);
TextView emp1 = (TextView) convertView.findViewById(R.id.empname1);
TextView emp2 = (TextView) convertView.findViewById(R.id.empname2);
TextView emp3 = (TextView) convertView.findViewById(R.id.empname3);
emp1.setText(modelList.get(position).getSno());
emp2.setText(modelList.get(position).getScode());
emp3.setText(modelList.get(position).getSearchName());
return convertView;
}
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
modelList.clear();
if (charText.length()==0){
modelList.addAll(arrayList);
}
else {
for ( SearchSetterandGetter model : arrayList){
if (model.getSearchName().toLowerCase(Locale.getDefault()).contains(charText)||model.getSno().toLowerCase(Locale.getDefault()).contains(charText)){
modelList.add(model);
}
}
}
notifyDataSetChanged();
// modelList.clear();
}
}
As I understood your adapter is not updating, try this. try to debug and check whether its updating or not
if(adapter !=null){
adapter = null;
}
adapter = new CustomAdaptor(this, arrayList);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.notifyDataSetChanged();
I am following a tutorial about multiple choice listview in android.
When executing the app, the listview shows some items, not all of them. After clicking on the listview, it shows all items.
I want to know where is the reason of that issue.
This is the code for MainActivity class:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
FloatingActionButton fab;
ListView list;
TextView txt_menu;
String dipilih;
private static final String TAG = MainActivity.class.getSimpleName();
Adapter adapter;
ProgressDialog pDialog;
List<Data> itemList = new ArrayList<Data>();
// Sesuaikan dengan IP Address PC/LAptop atau ip emulator bawaan android 10.0.2.2
private static String url = "https://.../test/menu.php";
public static final String TAG_NAMA = "nama";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
list = (ListView) findViewById(R.id.list_menu);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
callVolley();
adapter = new Adapter(this, (ArrayList<Data>) itemList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txt_menu = (TextView) dialogView.findViewById(R.id.txt_menu);
txt_menu.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void callVolley(){
itemList.clear();
// menapilkan dialog loading
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
showDialog();
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NAMA));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
And this is the Adapter class:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
viewHolder.menu.setText(items.getMenu());
}
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
If you need other code parts to detect the problem, please let me know.
EDIT
First launch
After clicking on the listview
The problem is this bit of your code in your adapter's getView() callback:
if(view == null) {
...
}else {
...
viewHolder.menu.setText(items.getMenu());
}
What's happening here is that you're only caling setText() when the item view is recycled by the ListView. The reason everything shows up after you click a checkbox is that the ListView rebinds everything when you call notifyDataSetChanged().
You should call this method outside of the if/else statement so that it is executed every time.
if(view == null) {
...
}else {
...
}
viewHolder.menu.setText(items.getMenu());
I think the issue you are having is coming from the getView() method in your Adapter class.
Since you are using a ViewHolder to recycle objects you are first checking if the exist first before creating them if(view == null). But, you are only creating them and not assigning the TextView objects a String value. You only do that once the object has already been created. So, when you click on an item, you are calling notifyDataSetChanged causing the list to be updated. Then the values are set in the `TextView.
So try this instead: put the line viewHolder.menu.setText(items.getMenu()); outside the conditional statement:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
try this once
adapter = new Adapter(this, (ArrayList) itemList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
list.setAdapter(adapter);
}
set adapter at the end
I built a listview that displays dynamic buttons with the name of tables in a database. When a person clicks the button it's supposed to grab the text of the button and then pass that to the next activity which would populate the information corresponding to the database table and display that text at the top of the screen. The code I've written keeps crashing when I click the button. Is there something else I need to call or does this code not work with a button?
public class UserArea extends AppCompatActivity {
SectionListAdapter sectionListAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
TextView tvWelcomeMsg = (TextView) findViewById(R.id.tvWelcome);
/**Get Sections and Display as buttons*/
listView = (ListView) findViewById(R.id.lvSections);
sectionListAdapter = new SectionListAdapter(this, R.layout.section_layout);
listView.setAdapter(sectionListAdapter);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
/** If data successfully gathered*/
if (success) {
JSONArray jsonArray= jsonResponse.getJSONArray("Flights");
int count = 0;
String flight;
while(count<jsonArray.length()) {
JSONObject SL = jsonArray.getJSONObject(count);
flight = SL.getString("Flight");
SectionList sl = new SectionList(flight);
sectionListAdapter.add(sl);
count++;
}
}
/** If data is not gathered*/
else {
AlertDialog.Builder builder = new AlertDialog.Builder(UserArea.this);
builder.setMessage("Failed to connect")
.setNegativeButton("Retry", null)
.create()
.show();
}
}
/** if any other response is received*/
catch (JSONException e) {
e.printStackTrace();
}
}
};
/**Creates Request to get the data*/
GetSectionRequest getSections = new GetSectionRequest(responseListener);
/**Creates a queue to run the code*/
RequestQueue queue = Volley.newRequestQueue(UserArea.this);
queue.add(getSections);
/**End*/
/**Creates onclicklistener to pass clicked section name*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent (UserArea.this, Personnel.class);
intent.putExtra("section", listView.getItemAtPosition(i).toString());
UserArea.this.startActivity(intent);
}
});
SectionListAdapter
public class SectionListAdapter extends ArrayAdapter {
List list = new ArrayList();
public SectionListAdapter(Context context, int resource) {
super(context, resource);
}
public void add(SectionList 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;
row = convertView;
SectionListAdapter.SectionListHolder sectionListHolder;
if (row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.section_layout, parent, false);
sectionListHolder = new SectionListAdapter.SectionListHolder();
sectionListHolder.bSection = row.findViewById(R.id.bSectionName);
}else{
sectionListHolder = (SectionListAdapter.SectionListHolder)row.getTag();
}
SectionList SectionList = (SectionList) this.getItem(position);
sectionListHolder.bSection.setText(SectionList.getFlight());
return row;
}
static class SectionListHolder{
Button bSection;
}
}
Log Cat
10-10 19:31:26.797 6595-6595/com.example.yikes.recall E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.yikes.recall, PID: 6595
java.lang.NullPointerException: Attempt to read from field 'android.widget.Button com.example.yikes.recall.SectionListAdapter$SectionListHolder.bSection' on a null object reference
I'm try code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ListView listView = new ListView(this);
listView.setBackgroundColor(Color.WHITE);
setContentView(listView);
final String[] activities = new String[]{"Item1", "Item2", "Item3", "Item4"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
listView.setAdapter(adapter);
for (String item : activities) {
adapter.add(item);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(MainActivity.this, SampleActivity.class);
intent.putExtra("item", item);
MainActivity.this.startActivity(intent);
}
});
}
It's working, I think
/**Creates Request to get the data*/
GetSectionRequest getSections = new GetSectionRequest(responseListener);
/**Creates a queue to run the code*/
RequestQueue queue = Volley.newRequestQueue(UserArea.this);
queue.add(getSections);
Need some time, you can add ProgressDialog when start app and dismiss when response callback. Hope it can help you!
I have currently implemented a listview, which when you click an item opens a second activity. In the second activity I have another listview which i can add items to, but when i go back to the first list and click another item, all the items from the second list appear for this one as well.
Any ideas how to sort this out? Can post code if needed
Here is the code for the first activity:
public class MainActivity extends Activity {
private ArrayList<String> entries;
private ArrayAdapter<String> entriesAdapter;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createListView();
createListViewListener();
}
private void createListView() {
list = (ListView) findViewById(R.id.diaryListView);
entries = new ArrayList<>();
readEntries();
entriesAdapter = new CustomAdapter(this, entries);
list.setAdapter(entriesAdapter);
}
private void createListViewListener() {
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
entries.remove(position);
entriesAdapter.notifyDataSetChanged();
writeEntries();
return true;
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("entry", entries.get(position));
startActivity(intent);
}
});
}
public void addEntry(View v) {
EditText entryEditText = (EditText) findViewById(R.id.entryEditText);
String diaryText = entryEditText.getText().toString();
entriesAdapter.add(diaryText);
entryEditText.setText("");
writeEntries();
}
private void readEntries() {
File filesDir = getFilesDir();
File journalEntriesFile = new File(filesDir, "journalEntries.txt");
try {
entries = new ArrayList<>(FileUtils.readLines(journalEntriesFile));
} catch (IOException e) {
entries = new ArrayList<>();
}
}
/**
* Method to save a list of tasks
*/
private void writeEntries() {
File filesDir = getFilesDir();
File journalEntriesFile = new File(filesDir, "journalEntries.txt");
try {
FileUtils.writeLines(journalEntriesFile, entries);
} catch (IOException e) {
e.printStackTrace();
}
}
and the second:
public class SecondActivity extends Activity {
private String entryName;
private TextView entryTitle;
private ArrayList<String> entryTask;
private ArrayAdapter<String> entryTaskAdapter;
private ListView entryTaskList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
displayEntryTitle();
createEntryTaskListView();
createEntryTaskListViewListener();
}
private void displayEntryTitle() {
entryTitle = (TextView) findViewById(R.id.entryTitle);
Intent intent = getIntent();
entryName = intent.getStringExtra("entry");
entryTitle.setText("" + entryName);
}
private void createEntryTaskListView() {
entryTaskList = (ListView) findViewById(R.id.entryTaskListView);
entryTask = new ArrayList<>();
readEntryTasks();
entryTaskAdapter = new CustomAdapter2(this, entryTask);
entryTaskList.setAdapter(entryTaskAdapter);
}
private void createEntryTaskListViewListener() {
entryTaskList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
entryTask.remove(position);
entryTaskAdapter.notifyDataSetChanged();
writeEntryTasks();
return true;
}
});
entryTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
View view2 = (LayoutInflater.from(SecondActivity.this)).inflate(R.layout.alert_dialog, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(SecondActivity.this);
alertBuilder.setTitle("Edit Journal Task Entry");
alertBuilder.setView(view2);
final EditText editEntryTaskText = (EditText) view2.findViewById(R.id.editEntryTask);
alertBuilder.setCancelable(true).setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String editEntry = editEntryTaskText.getText().toString();
editEntryTaskText.setText("" + editEntry);
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}
});
}
public void onAddEntryTask(View v) {
EditText editText = (EditText) findViewById(R.id.entryTaskEditText);
String entryTaskText = editText.getText().toString();
entryTaskAdapter.add(entryTaskText);
editText.setText("");
writeEntryTasks();
}
private void readEntryTasks() {
File filesDir = getFilesDir();
File taskEntriesFile = new File(filesDir, "taskEntries.txt");
try {
entryTask = new ArrayList<>(FileUtils.readLines(taskEntriesFile));
} catch (IOException e) {
entryTask = new ArrayList<>();
}
}
private void writeEntryTasks() {
File filesDir = getFilesDir();
File taskEntriesFile = new File(filesDir, "taskEntries.txt");
try {
FileUtils.writeLines(taskEntriesFile, entryTask);
} catch (IOException e) {
e.printStackTrace();
}
}
Without seeing how you get back to the first activity from the second activity I can only assume that ArrayList entrytask is getting inserted into ArrayList entries when you return so based on the limited information I have the best answer I can come up with is
private void createListView() {
list = (ListView) findViewById(R.id.diaryListView);
entries = new ArrayList<>();
list.setAdapter(null);
//ArrayList<String> entries = null;
readEntries();
entriesAdapter = new CustomAdapter(this, entries);
list.setAdapter(entriesAdapter);
}
I'm new to android. I'm trying to get my list view to update, I've tried everything...from calling notifydatasetchanged on the ui thread to just simply recreating my list adapter but for whatever reason when I update, no matter which method I use I have to scroll to see the changes. By this I mean that the data updates (say 13:01 changes to 13:02 in the list), it will update, but to see the change I have to scroll so that 13:01 goes off screen and then move back and it will have updated visually.
Why is this? (I can't post code right now as I'm on my phone but if required I will post later.)
EDIT: Here's the relevant code...sorry it took so long I haven't been at my computer for a couple of days.
Relevant parts of ListFragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.match_fragment, container, false);
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MatchAdapter adapter = (MatchAdapter) this.getListAdapter();
if(futureMatches)
adapter = new MatchAdapter (this.getActivity(), ((MainActivity)this.getActivity()).getMatches(), futureMatches);
else
adapter = new MatchAdapter (this.getActivity(), ((MainActivity)this.getActivity()).getPastMatches(), futureMatches);
setListAdapter(adapter);
}
public void refresh()
{
MatchAdapter adapter;
//Update array in mainactivity
if(futureMatches)
MainActivity.refreshMatches((MainActivity) getActivity());
else
MainActivity.refreshPastMatches((MainActivity) getActivity());
//put updated entries in the adapter
if(futureMatches)
adapter = new MatchAdapter (getActivity(), ((MainActivity)getActivity()).getMatches(), futureMatches);
else
adapter = new MatchAdapter (getActivity(), ((MainActivity)getActivity()).getPastMatches(), futureMatches);
setListAdapter(adapter);
updateList();
}
public void updateList(){
this.getActivity().runOnUiThread(new Runnable() {
public void run() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
getListView().refreshDrawableState();
getListView().invalidate();
}
});
}
public void onViewStateRestored(Bundle savedInstanceState)
{
super.onViewStateRestored(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
refresh();
}
My adapter class:
public class MatchAdapter extends BaseAdapter
{
private final Activity context;
private LayoutInflater inflater;
private boolean time = false;
private boolean futureMatchAdapter = true;
private ArrayList<String> matchList;
public MatchAdapter(Context cont, ArrayList<String> matches, boolean isFutureMatchAdapter)
{
matchList = matches;
futureMatchAdapter = isFutureMatchAdapter;
context = (Activity) cont;
inflater = LayoutInflater.from(context);
}
public int getCount()
{
return MatchAdapter.size();
}
#Override
public Object getItem(int position)
{
return MatchAdapter.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
String curPos = "";
curPos = MatchAdapter.get(position);
//times, future matches and past matches are handled differently
if(curPos.contains("Last updated:"))
time = true;
else
time = false;
if (convertView == null)
{
holder = new ViewHolder();
if(time)
{
convertView = inflater.inflate(R.layout.time_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_time);
}
else
{
if(futureMatchAdapter)
{
convertView = inflater.inflate(R.layout.feed_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_title);
}
else
{
convertView = inflater.inflate(R.layout.past_feed_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_title_past);
}
}
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
if(futureMatchAdapter)
holder.title.setText(matchList.get(position));
else
{
String matchString = matchList.get(position);
String alwaysVisible = matchString.replace("<", "vs");
alwaysVisible = alwaysVisible.replace(">", "vs");
if(!time)
alwaysVisible = alwaysVisible.substring(0, alwaysVisible.length() - 1);
holder.title.setText(alwaysVisible);
if(matchString.contains(">"))
{
String winner = matchString.substring(0, matchString.indexOf(">")) + "won!";
alwaysVisible = alwaysVisible.concat(winner);
}
else if(matchString.contains("<"))
{
String winner = matchString.substring(matchString.indexOf("<") + 2, matchString.indexOf("\n")) + " won!";
alwaysVisible = alwaysVisible.concat(winner);
}
holder.title.setOnClickListener(new pastMatchesOnclickListener(alwaysVisible)
{
public void onClick(View v)
{
((TextView) v).setText(matchWinner);
}
});
}
return convertView;
}
static class ViewHolder
{
TextView title;
TextView time;
}
}
did you try to update your list using the adapter?
dataadapter.clear();
dataadapter.addAll(allDataResult);
To show and update content in a ListView you should:
Create or find your ListView
Create your ListAdapter
Add your ListAdapter to your ListView
Add data to your ListAdapter
Call notifyDataSetChanged() on your ListAdapter.
Example:
ListView listView = (ListView) findViewById(R.id.listview);
MyListAdapter myListAdapter = new MyListAdapter();
listView.setAdapter(myListAdapter);
myListAdapter.add("Hello");
myListAdapter.add("Hi");
myListAdapter.notifyDataSetChanged();
Note: if you're using a subclass of ArrayAdapter the notifyDataSetChanged() will be called for you when you use the methods add(), addAll(), etc.