There are 2 autocomplete textview one for the city and one for the state. I want that when a user enters the state in autocomplete textview then based on state selection, city autocomplete text view should be automatically filled. Like the ecommerce app whenever someone enters the postal code in the address section then the city and state get automatically filled and also the user has the option to select.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText edtxt_name_address, edtxt_email_address, edtxt_mobile_address, edtxt_alt_mob_address, edtxt_pincode, edtxt_addline1, edtxt_addline2;
Button buttonSaveAddress;
AutoCompleteTextView edtxt_city, edtxt_state;
private static final String KEY_STATE = "state";
private static final String KEY_CITIES = "cities";
private ProgressDialog pDialog;
private String cities_url = "http://api.androiddeft.com/cities/cities_array.json";
final List<State> statesList = new ArrayList<>();
final List<String> states = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtxt_city = findViewById(R.id.edtxt_city);
edtxt_state = findViewById(R.id.edtxt_state);
loadStateCityDetails();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, states);
edtxt_state.setThreshold(1);//will start working from first character
edtxt_state.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
//edtxt_city.setTextColor(Color.BLACK)
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
buttonSaveAddress = findViewById(R.id.buttonSaveAddress);
buttonSaveAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveAddress();
}
});
}
private void loadStateCityDetails() {
JsonArrayRequest jsArrayRequest = new JsonArrayRequest
(Request.Method.GET, cities_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray responseArray) {
try {
//Parse the JSON response array by iterating over it
for (int i = 0; i < responseArray.length(); i++) {
JSONObject response = responseArray.getJSONObject(i);
String state = response.getString(KEY_STATE);
JSONArray cities = response.getJSONArray(KEY_CITIES);
List<String> citiesList = new ArrayList<>();
for (int j = 0; j < cities.length(); j++) {
citiesList.add(cities.getString(j));
}
statesList.add(new State(state, citiesList));
states.add(state);
Log.d("lskd", String.valueOf(statesList));
Log.d("lskd", String.valueOf(states));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
private void saveAddress() {
if (TextUtils.isEmpty(city)) {
edtxt_city.setError("Please enter your City");
edtxt_city.requestFocus();
return;
}
if (TextUtils.isEmpty(state)) {
edtxt_state.setError("Please enter your State");
edtxt_state.requestFocus();
return;
}
Intent profile_next = new Intent(MainActivity.this, ProfileNextActivity.class);
startActivity(profile_next);
}
}
State.java
public class State {
private String stateName;
private List<String> cities;
public State(String stateName, List<String> cities) {
this.stateName = stateName;
this.cities = cities;
}
public String getStateName() {
return stateName;
}
public List<String> getCities() {
return cities;
}
}
State and city has one to many relation, I didn't particularly understand what you meant by automatically filled. If you want to populate the related cities of the selected state do the following.
Inside your edtxt_state.setOnItemSelectedListener
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
statesList.get(position).getCities(); //get your cities from selected state
//set adapter or notify city list of your `edtxt_city` AutoCompleteTextView
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
try this...
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
List<String> cityList = statesList.get(position).getCities();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, cityList);
edtxt_city.setThreshold(1);//will start working from first character
edtxt_city.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
set your adapter inside loadStateCityDetails(); after getting stateList
statesList.add(new State(state, citiesList));
states.add(state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, states);
edtxt_state.setThreshold(1);//will start working from first character
edtxt_state.setAdapter(adapter);
EDIT
edtxt_state.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
int pos = -1;
for (int i = 0; i < statesList.size(); i++) {
if (statesList.get(i).getStateName().equals(selection)) {
pos = i;
break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.select_dialog_item, statesList.get(pos).getCities());
edtxt_city.setThreshold(1);//will start working from first character
edtxt_city.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
}
});
you must get stateList
set city adapter as above
Related
I'm trying to implement multiple spinners in the app, in which the data is populated after a volley call. It should work in such way that; based on the selection of the first spinner value "id", the second spinner should populate its value from another api call taking the selected "id" as parameter.
I'm able to show the "name"(s) in the spinner now. But not sure how to get the id of the selected item for the second api call. Right now when I select any item in the first spinner, it only returns the id of the last item in the array.
Json Array Response:
[
{
"id":1,
"name":"Roger Federer",
"country":"Switzerland",
"city":"Basel"
},
{
"id":2,
"name":"Rafael Nadal",
"country":"Spain",
"city":"Madrid"
},
{
"id":3,
"name":"Novak Djokovic",
"country":"Serbia",
"city":"Monaco"
},
{
"id":4,
"name":"Andy Murray",
"country":"United Kingdom",
"city":"London"
},
{
"id":5,
"name":"Maria Sharapova",
"country":"Russia",
"city":"Moscow"
},
{
"id":8,
"name":"Ana Ivanovic",
"country":"Serbia",
"city":"Belgrade"
}
]
FirstLevel (model)
public class FirstLevel {
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
private String title;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private int id;
}
Java code
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<FirstLevel> FirstLevelDataAdapterClassList;
private int selectedFirstLevel;
...
public void FIRST_LEVEL_WEB_CALL(final ViewHolder viewHolder) {
//showSimpleProgressDialog(context, "Loading...", "Fetching Json", false);
JsonArrayRequest jsArrRequest = new JsonArrayRequest
(Request.Method.GET, HTTP_SERVER_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
FIRST_PARSE_DATA_AFTER_WEBCALL(response,viewHolder);
Log.i("FL", "FL");
//removeSimpleProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
}) {
};
requestQueue2 = Volley.newRequestQueue(context);
requestQueue2.add(jsArrRequest);
}
public void FIRST_PARSE_DATA_AFTER_WEBCALL(JSONArray array, final ViewHolder viewHolder) {
FirstLevelDataAdapterClassList = new ArrayList<>();
FirstLevel GetFirstLvDataModel = new FirstLevel();
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetFirstLvDataModel.setId(json.getString("id"));
GetFirstLvDataModel.setName(json.getString("name"));
FirstLevelDataAdapterClassList.add(GetFirstLvDataModel);
names.add(FirstLevelDataAdapterClassList.get(i).getTitle().toString());
} catch (JSONException e) {
e.printStackTrace();
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
viewHolder.spinFirst.setAdapter(spinnerArrayAdapter);
viewHolder.spinFirst.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedFirstLevel=FirstLevelDataAdapterClassList.get(position).getId();
Log.i("FLFL",selectedFirstLevel);
SECOND_LEVEL_WEB_CALL(viewHolder,selectedFirstLevel);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Your this line
selectedFirstLevel= //How to get the 'id' of the selected item here?
will be
selectedFirstLevel = FirstLevelDataAdapterClassList.get(position).getId();
Try this out. Thanks
FirstLevel GetFirstLvDataModel = new FirstLevel();
should be declare in forloop and adapter is outside of the loop.
try this method ->
public void FIRST_PARSE_DATA_AFTER_WEBCALL(JSONArray array, final ViewHolder viewHolder) {
FirstLevelDataAdapterClassList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
FirstLevel GetFirstLvDataModel = new FirstLevel(); // Define class object here
GetFirstLvDataModel.setId(json.getString("id"));
GetFirstLvDataModel.setName(json.getString("name"));
FirstLevelDataAdapterClassList.add(GetFirstLvDataModel);
names.add(FirstLevelDataAdapterClassList.get(i).getTitle().toString());
} catch (JSONException e) {
e.printStackTrace();
}
} // Close for loop here
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
viewHolder.spinFirst.setAdapter(spinnerArrayAdapter);
viewHolder.spinFirst.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedFirstLevel=FirstLevelDataAdapterClassList.get(position).getId();
Log.i("FLFL",selectedFirstLevel);
SECOND_LEVEL_WEB_CALL(viewHolder,selectedFirstLevel);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
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 make application can input data from spinner into database when user open activity spinner retrieve data from DB and then if the user change value of spinner, its refresh the spinner (In My case if user click the edit button, data not match with database) how can I fix this?
This is my code :
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editfpp);
getAlamatBill(id);
}
#Override
protected void onResume() {
super.onResume();
spinnerprovinsibill.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String kodeprovinsi = helper.getRefprovinsi(spinnerprovinsibill.getSelectedItem().toString());
ambilKabupaten(kodeprovinsi, spinnerkabupatenbill);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerkabupatenbill.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String kodekabupaten = helper.getRefkabupaten(spinnerkabupatenbill.getSelectedItem().toString());
ambilKecamatan(kodekabupaten, spinnerkecamatanbill);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void ambilKecamatan(String kodekabupaten, Spinner spinnerkecamatanbill) {
List<String> data = helper.getKecamatan(kodekabupaten);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_background, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerkecamatanbill.setAdapter(adapter);
}
private void ambilKabupaten(String kodeprovinsibill, Spinner spinnerkabupatenbill) {
List<String> data = helper.getKabupaten(kodeprovinsibill);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_background, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerkabupatenbill.setAdapter(adapter);
}
private void ambilProvinsiPilihan(Spinner spinner, String namaprovinsi, String kabupaten, String kecamatan, String kelurahan){
List<String> data = helper.getProvinsi();
ArrayAdapter<String> dataadapter = new ArrayAdapter<String>(this, R.layout.spinner_background, data);
dataadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataadapter);
int posisi = dataadapter.getPosition(namaprovinsi);
spinner.setSelection(posisi);
System.out.println("hasil = " + helper.getRefkabupaten(kabupaten) + " " + helper.getRefkecamatan(kecamatan));
}
private void getAlamatBill(String id) {
try {
System.out.println("persiapan data: " + id);
JSONArray array = new JSONArray(helper.getAlamatShip(id));
JSONObject object = array.getJSONObject(0);
String alamat = object.getString("alamat");
String kdpos = object.getString("kdpos");
String kelurahan = object.getString("kelurahan");
String kecamatan = object.getString("kecamatan");
String kabupaten = object.getString("kabupaten");
String provinsi = object.getString("provinsi");
String kota = object.getString("kota");
ambilProvinsiPilihanShip(spinnerprovinsiship, provinsi, kabupaten, kecamatan, kelurahan);
ambilKotaPilihan(spinnerkotaship, kota);
edalamatship.setText(alamat);
edkodeposship.setText(kdpos);
} catch (JSONException e) {
e.printStackTrace();
}
}
thanks in advance
_doctorSpinner = (Spinner) findViewById(R.id.input_doctor);
final ArrayList<String> docList = new ArrayList<String>();
DataUtil.getDoctorList(this.getApplicationContext(), new ServerCallBack() {
#Override
public void onSuccess(JSONObject result) {
}
#Override
public void onSuccess(String result) {
}
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
} catch (JSONException e) {
}
}
});
final ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, docList);
docAdapter.notifyDataSetChanged();
docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
_doctorSpinner.setAdapter(docAdapter);
_doctorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
In the above code i am getting a list of strings from server and populating in the spinner. When the activity is loaded i am unable to see the first item in the list("Select a doctor"). But when i click on spinner, i could see the items and select. Again then selected item is not visible as selected. Could anybody help me?
Thanks in advance.
_doctorSpinner = (Spinner) findViewById(R.id.input_doctor);
final ArrayList<String> docList = new ArrayList<String>();
DataUtil.getDoctorList(this.getApplicationContext(), new ServerCallBack() {
#Override
public void onSuccess(JSONObject result) {
}
#Override
public void onSuccess(String result) {
}
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
final ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, docList);
docAdapter.notifyDataSetChanged();
docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
_doctorSpinner.setAdapter(docAdapter);
_doctorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (JSONException e) {
}
}
});
webservice call work in background thread so ypou get list size zero when u set adapter so inialize and setadapter when call finish
Call notifyDataSetChanged(); after your data is added to the list.
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
if (null != docAdapter)
docAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
EDIT :
My bad I read the question incorrectly.
If you cannot see the text inside your spinner try this:
ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, docList);
And I don't believe you need to use docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
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);
}