Can't use Spinner.setSelection from Database - android

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

Related

How to populate autocomplete textview based on the selection of first?

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

Filtered ListView onItemClick returns Item at original position for online Activities

Hi I am trying to make a apps that contains some list item with auto suggestion from a website. but when i Click one of the Item it return only first item related value. But i want only related value from them.
This is my Main Activity:
public class MainActivity extends AppCompatActivity {
ListView vl;
Button b;
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> news_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vl = (ListView) findViewById(R.id.myList);
b= (Button) findViewById(R.id.addNewbutton);
inputSearch = (EditText) findViewById(R.id.inputSerach);
fetchingData();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddingNews.class));
}
});
}
void fetchingData(){
String myURL = "http://192.168.56.1/android/api/gettingnews.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(myURL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
final String[] news_title = new String[response.length()];
final String[] news_detail = new String[response.length()];
final String[] news_time = new String[response.length()];
for (int i =0; i < response.length(); i++){
try {
JSONObject jsonObject = (JSONObject) response.get(i);
news_title[i] = jsonObject.getString("title");
news_detail[i] = jsonObject.getString("news");
news_time[i] = jsonObject.getString("time");
} catch (JSONException e) {
e.printStackTrace();
}
}
// vl.setAdapter(new ArrayAdapter(getApplicationContext(), R.layout.mylistview, R.id.textViewforlist, news_title));
// Adding items to listview
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.mylistview, R.id.textViewforlist, news_title);
vl.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
vl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Details.class);
intent.putExtra("MyTitle", news_title[position]);
intent.putExtra("MyNews", news_detail[position]);
intent.putExtra("MyTime", news_time[position]);
startActivity(intent);
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley Log", error);
}
});
com.example.forkan.tuntuninews.AppController.getInstance().addToRequestQueue(jsonArrayRequest);
Toast.makeText(getApplicationContext(),"Data Loaded Successfully", Toast.LENGTH_LONG).show();
}
}
and this is My Details: activites;
public class Details extends AppCompatActivity {
TextView title, time, details;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
title = (TextView) findViewById(R.id.mytitle);
time = (TextView) findViewById(R.id.mytime);
details = (TextView) findViewById(R.id.mydetail);
String _title = getIntent().getStringExtra("MyTitle");
String _news = getIntent().getStringExtra("MyNews");
String _time = getIntent().getStringExtra("MyTime");
title.setText(_title);
time.setText(_time+"\n\n");
details.setText(_news);
}
}
How Can i Fix it Please Help me..

Invoking a Spinner onitemselect listener

I'm really close to getting my spinner to do something when an item is selected. I just can't figure out how to set up the onitemselectedlistener correctly. I think my problem is not knowing how to pass the arguments to my onItemSelected method. Help to get the final part of this working is very much appreciated.
Here is the code:
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String[][] testScoreList = new String[3][3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Load test scores into arraylist
nameArrayListMethod();
spinner.setOnItemSelectedListener(onItemSelected());
}
//This method loads test scores into an array and populates spinner
public void nameArrayListMethod (){
InputStreamReader InputSR = null;
BufferedReader BufferedRdr = null;
String thisLine = null;
AssetManager am = getAssets();
String[] SpinnerNames = new String[3];
try {
InputSR = new InputStreamReader(am.open("scoresdata/test_scores.txt"));
BufferedRdr = new BufferedReader(InputSR);
// open input stream test_scores for reading purpose.
int i = 0;
while ((thisLine = BufferedRdr.readLine()) != null) {
//System.out.println(thisLine);
String[] parts = thisLine.split(" ");
testScoreList[i][0] = parts[0];
testScoreList[i][1] = parts[1];
testScoreList[i][2] = parts[2];
SpinnerNames[i] = testScoreList[i][0]; //Extract first column for spinner
i = i +1;
}
BufferedRdr.close();
InputSR.close();
} catch (Exception e) {
e.printStackTrace();
}
spinner= (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, SpinnerNames);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
}
You can add data Tow ways
Method 1
if you have a simple one line data the use this method.
step 1
Add string array in string.xml file
<string-array name="ArrayName">
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
<item>E</item>
<item>F</item>
</string-array>
add android:entries="#string/ArrayName" in your xml spinner component
and get selected value using String text = spinner.getSelectedItem().toString();
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "Value = "+spinner.getSelectedItem().toString();, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
}
});
Method 2
for using custom adapter HERE is complete tutorial
It looks like:
spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
});
Try this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

spinner data from sqlite

I'm trying to fill spinner item from sqlite table
i have no idea how to do it , i tried to follow other example but i think its different than mine
what is the easiest way to do it and how can i set onclicklistener for each item
Thanks in advance
MainActivity + sqliteopenhelper
public ArrayList<String> getTableValues() {
ArrayList<String> my_array = new ArrayList<String>();
try {
SQLiteDatabase db = this.getWritableDatabase();
Cursor resultPPNAME = db.rawQuery("select NAMEPPL from " + Table_name2, null);
if (resultPPNAME.moveToFirst()) {
String PPLNAMESPIN = resultPPNAME.getString(0);
my_array.add(PPLNAMESPIN);
}
while (resultPPNAME.moveToNext()) ;
} catch (Exception e) {
}
return my_array;
}
MainActivity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
DB db;
Button addmed,addpl;
TextView PPLNAMERES;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PPLNAMERES = (TextView)findViewById(R.id.PPLNAMEGETNAME);
db = new DB(this);
listView();
String spinValue = db.getMainData().toString();
ArrayList<String> my_array= new ArrayList<String>();
my_array = db.getTableValues();
Spinner spinner = (Spinner)findViewById(R.id.spin1);
ArrayAdapter<String> my_adapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,my_array);
spinner.setAdapter(my_adapter);
}
public void addmedView(View view){
Intent ADDMEDVIEW = new Intent(this,ADDMEDCINEVIEW.class);
startActivity(ADDMEDVIEW);
}
public void addpplview(View view){
Intent ADDPPLVIEWS = new Intent(this,ADDPPLVIEW.class);
startActivity(ADDPPLVIEWS);
}
public void listView(){
Cursor res= db.getMainData();
if(res.moveToFirst()){
PPLNAMERES.setText(res.getString(0));
} else{
Toast.makeText(MainActivity.this,"No Data",Toast.LENGTH_LONG).show();
return;
}}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}}
adapter code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PPLNAMERES = (TextView)findViewById(R.id.PPLNAMEGETNAME);
db = new DB(this);
ArrayList<String> my_array= new ArrayList<String>();
my_array = db.getTableValues();
Spinner spinner = (Spinner)findViewById(R.id.spin1);
ArrayAdapter<String> my_adapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,my_array);
spinner.setAdapter(my_adapter);
}
onitemselected methods
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
// try like this.
public ArrayList<String> getTableValues() {
ArrayList<String> my_array = new ArrayList<String>();
try {
SQLiteDatabase db = this.getWritableDatabase();
Cursor resultPPNAME = db.rawQuery("select NAMEPPL from " + Table_name2, null);
// Change Made HERE
resultPPNAME.moveToFirst();
while (cur.isAfterLast() == false) {
String PPLNAMESPIN = resultPPNAME.getString(0);
cur.moveToNext();
my_array.add(PPLNAMESPIN);
}
} catch (Exception e) {
}
return my_array;
}

Android Listview opens to another listview

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);
}

Categories

Resources