improve formatting and remove noise - java

I have a problem with my app when I try to return a string array from an activity that was launched for a result. For some strange reason, my app also doesn't display the action bar, no matter what I do. I have put the code below.
MainActivity is launched first then DropDownList is called for Result.
DropDownList.Java
public class DropDownList extends Activity implements View.OnClickListener {
private ListView lView;
String[] lv_items;
ArrayAdapter<String> adapter;
Button button;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_drop_down_list);
lv_items = getResources().getStringArray(R.array.subjects_List);
findViewsById();
lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the one option from list
lView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
button.setOnClickListener(this);
}
private void findViewsById() {
lView = (ListView) findViewById(R.id.ListView01);
button = (Button) findViewById(R.id.submitButton);
}
//I BELIEVE THIS IS WHERE THE PROBLEMATIC CODE IS
public void onClick(View v) {
SparseBooleanArray checked = lView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
Intent returnIntent = new Intent(getApplicationContext(),
MainActivity.class);
// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
returnIntent.putExtras(b);
// start the ResultActivity
setResult(RESULT_OK, returnIntent);
/**returnIntent.putExtra("SelectedBook",book);*/
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(id) {
case R.id.action_ok:
break;
case R.id.about_menu:
Toast.makeText(this, "developed by Seyi Oluwasanmi",
Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings:
Toast.makeText(getApplicationContext(),"Settings Clicked",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
MainActivity.Java
public class MainActivity extends Activity {
public static final int ReqCode = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton addButton = (ImageButton) findViewById(R.id.add_button);
ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
#Override
public void getOutline(View view, Outline outline) {
// Or read size directly from the view's width/height
int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
outline.setOval(0, 0, size, size);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, DropDownList.class);
startActivityForResult(myIntent, ReqCode);
}
});
}
};
addButton.setOutlineProvider(viewOutlineProvider);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ReqCode:
if (resultCode == RESULT_OK) {
ArraySubs();
break;
}
}
}
public void ArraySubs() {
Bundle b = getIntent().getExtras();
String[] subChoices = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.outputList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, subChoices);
lv.setAdapter(adapter);
};
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater blowUp=getMenuInflater();
blowUp.inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.action_ok:
break;
case R.id.action_settings:
Toast.makeText(getApplicationContext(),"Settings Clicked", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
MENU.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
<item android:id="#+id/action_ok"
android:icon="#drawable/ic_menu_done"
android:title="#string/action_ok"
android:showAsAction="ifRoom"
/>
<item android:id="#+id/about_menu"
android:title="#string/about_menu"
android:showAsAction="ifRoom"
/>
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="ifRoom"
/>
</menu>
String Array of Subjects
<string-array name="subjects_List">
<item>Maths</item>
<item>English</item>
<item>Physics</item>
<item>Biology</item>
<item>Computing</item>
<item>Chemistry</item>
<item>French</item>
<item>Music</item>
<item>Philosophy</item>
<item>Art</item>
</string-array>

For the action bar issue, have your activities extend "ActionBarActivity" rather than just "Activity" and that will be fixed.
For the other issue, your problem is here:
selectedItems.add(adapter.getItem(position));
because adapter is not being initialized.
Change the following:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_drop_down_list);
lv_items = getResources().getStringArray(R.array.subjects_List);
findViewsById();
lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the one option from list
lView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
button.setOnClickListener(this);
}
To:
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items);
lView.setAdapter(adapter);
That should fix the issue.
One other thing I noticed that will cause a crash is here:
public void ArraySubs() {
Bundle b = getIntent().getExtras();
String[] subChoices = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.outputList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, subChoices);
lv.setAdapter(adapter);
};
You are trying to get the intent of the MainActivity, which won't contain the array. You will need to pass in the intent from the onActivityResult. It also would be a good idea to put it in a try/catch in case the extra doesn't exist.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ReqCode:
if (resultCode == RESULT_OK) {
ArraySubs(data);
break;
}
}
}
public void ArraySubs(Intent data) {
try{
Bundle b = data.getExtras();
String[] subChoices = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.lv_list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, subChoices);
lv.setAdapter(adapter);
}
catch(Exception e){
Log.e("MainActivity", e.getMessage());
}
}

Im not too sure about your first problem but for the action bar try extending ActionBarActivity http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html

Related

How to create add and delete button for listview so next time user open the application added item stays there?

I need an answer on how to create an add button to add listview item, and a delete button to delete last added item. Look at my code. I made an add button but that item exists only for a few seconds and every time I close that page (go to other activity in usermode) it is deleted. Please let me know how can I fix this code and how can I write code for delete button. I need to know how to delete last made item. Thanks for your help in advance. I am looking forward to reply.
public class dodaj extends Activity {
ListView lv;
SearchView sv;
EditText txtinput;
ArrayList<String> arrayList;
String[] recepies={};
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dodaj);
registerClickCallback();
lv=(ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView);
txtinput=(EditText)findViewById(R.id.txtinput);
Button addbutton=(Button)findViewById(R.id.addbutton);
Button buttondel=(Button) findViewById(R.id.buttondel);
arrayList= new ArrayList<>(Arrays.asList(recepies));
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
String newItem=txtinput.getText().toString();
arrayList.add(newItem);
adapter.notifyDataSetChanged();
}
});
buttondel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
int i = arrayList.size()-1;
arrayList.remove(arrayList.get(i));
}
});
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
private void registerClickCallback(){
lv=(ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
TextView textView= (TextView) viewClicked;
if(position==0){
goToMojRecept1();
}else if(position==1){
goToMojRecept2();
}else if(position==2){
goToMojRecept3();
}else if(position==3){
goToMojRecept4();
}else if(position==4) {
goToMojRecept5();
}
}
});
}
private void goToMojRecept5() {
Intent intent = new Intent(this, MojRecept5.class);
startActivity(intent);
}
private void goToMojRecept4() {
Intent intent = new Intent(this, MojRecept4.class);
startActivity(intent);
}
private void goToMojRecept3() {
Intent intent = new Intent(this, MojRecept3.class);
startActivity(intent);
}
private void goToMojRecept2() {
Intent intent = new Intent(this, MojRecept2.class);
startActivity(intent);
}
private void goToMojRecept1() {
Intent intent = new Intent(this, MojRecept1.class);
startActivity(intent);
}

Why is my StringSet not saved to SharedPreferences?

I'm building an app that uses Google Places Api. Right now, when the user picks a place, the place name is added to a StringSet, which is then (supposed to be) saved to SharedPreferences. However, every time I restart the app, SharedPreferences is cleared. How do I fix this?
public class MainActivity extends AppCompatActivity {
PlacePicker.IntentBuilder builder;
int PLACE_PICKER_REQUEST;
ListView placeListView;
ArrayList<String> placeArrayList;
ArrayAdapter<String> arrayAdapter;
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
placeListView = (ListView) findViewById(R.id.placeListView);
placeArrayList = new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, placeArrayList);
placeListView.setAdapter(arrayAdapter);
sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLACE_PICKER_REQUEST = 1;
builder = new PlacePicker.IntentBuilder();
pickPlace();
}
});
}
public void pickPlace(){
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
placeArrayList.add((String) place.getName());
arrayAdapter.notifyDataSetChanged();
Set<String> set = new HashSet<String>();
set.addAll(placeArrayList);
editor.putStringSet("key", set);
sharedPreferences.edit().putStringSet("key", set).apply();
Log.e("places", String.valueOf(sharedPreferences.getStringSet("key", null)));
//Retrieve the values
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Error On Null Pointer But Still Unsolved on Android Studio

i am a newbie for Android Programming.
Here i have some problem when i want to make an activity (call Category_Setting) that showing list view, but when i switch from main activity to Category_Setting the error report in Android Studio gimme some error like this
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ever_ncn.cashflow/com.example.ever_ncn.cashflow.CategorySetting}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I have googling for it, asking some friend, but still i even don't know what is my error for.
Please somebody answer my question with simple understanding words.
Thank You..
NB. here is my code for MainActivity.java
public class MainActivity extends Activity implements OnItemSelectedListener {
private static Button BtnINewTrans;
private static Button BtnIViewCash;
private static Button BtnIAddCateg;
Spinner my_Spinner;
DatabaseHelper dbHelper = new DatabaseHelper(this);
//ArrayAdapter<String> adapterCategory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_Spinner = (Spinner)findViewById(R.id.spnCategSelect);
my_Spinner.setOnItemSelectedListener(this);
select_spinner_Category();
onButtonClickButtonListener();
}
/*ArrayList<String> my_array = new ArrayList<String>();
my_array = getTableValues();*/
/*ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row, my_array);
My_spinner.setAdapter(my_Adapter);*/
public void select_spinner_Category () {
my_Spinner = (Spinner)findViewById(R.id.spnCategSelect);
DatabaseHelper dbH = new DatabaseHelper(getApplicationContext());
List<String> listCategory = dbH.getAllCategory();
ArrayAdapter<String> adapterCategory = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, listCategory);
adapterCategory
.setDropDownViewResource(android.R.layout.simple_spinner_item);
my_Spinner.setAdapter(adapterCategory);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id){
String label = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "You selected "+label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/*ArrayList<String> arrayCategory;
arrayCategory = dbHelper.getAllCategory();
selectCategory = (Spinner) findViewById(R.id.spnCategSelect);
ArrayAdapter adapterCategory = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arrayCategory);
// adapterCategory = new ArrayList<String>(this, android.R.layout.simple_spinner_item, R.id.spnCategSelect, AllCategoryList);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCategory.setAdapter(adapterCategory);
selectCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
BtnINewTrans.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentNewTrans = new Intent ("com.example.ever_ncn.cashflow.NewTransaction");
startActivity(intentNewTrans);
}
}
);
BtnIViewCash = (Button)findViewById(R.id.btnViewCashflow);
BtnIViewCash.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentViewCash = new Intent ("com.example.ever_ncn.cashflow.ViewCashflow");
startActivity(intentViewCash);
}
}
);
BtnIAddCateg = (Button)findViewById(R.id.btnAddCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.CategorySetting");
startActivity(intentAddCateg);
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is Category_Setting.java (where i get this error)
public class CategorySetting extends Activity {
private SQLiteDatabase db;
private CursorAdapter currAdapter;
private static Button BtnIAddCateg;
private static Button BtnICancelCateg;
private static final String TAG = CategorySetting.class.getSimpleName();
DatabaseHelper dBHelper = new DatabaseHelper (this);
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onButtonClickButtonListener();
//reload();
}
public void reload(){
listView = (ListView) findViewById(R.id.listViewCateg);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "clicked on item: " + position);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category_setting, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnIAddCateg = (Button)findViewById(R.id.btnAddNewCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
startActivity(intentAddCateg);
}
}
);
BtnICancelCateg = (Button)findViewById(R.id.btnCancelCateg);
BtnICancelCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
In this method in Category_Setting.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onButtonClickButtonListener();
//reload();
}
you forgot to load the layout. You should add some code like you used in the MainActivity:
setContentView(R.layout.activity_main);
Right now, the layout is not loaded at all, so
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
will return null.

Change Action Bar Title using a string for Android

I want to change the Action Bar title in the .java file depending on which cell is tapped. When the new activity is called here, I am only able to change the action bar title through the xml file, but I want to use a string from my previous activity (in order to change the action bar title to whatever the cell title was in the previous activity).
In this case the String would be sText
public class ListViewAndroidExample extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.list_view_android_example, menu);
return super.onCreateOptionsMenu(menu);
}
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
try {
setContentView(R.layout.activity_list_view_android_example);
ListView mlistView = (ListView) findViewById(R.id.list);
mlistView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
new String[] {"#unlv", "#unr", "#ucla", "#usc"}));
mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text Game, Help, Home
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
String sText = ((TextView) view).getText().toString();
Intent intent;
intent = new Intent(ListViewAndroidExample.this, ChatRoom.class);
startActivity(intent);
//else if(sText.equals("Help")) ..........
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Created by Jason on 6/30/2014.
*/
public static class ChatRoom extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatlayout);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
}
Did you try
getActionBar().setTitle(sText);
or
getSupportActionBar().setTitle(sText);

Returning Data Result to Parent Activity using Intents

I am able to successfully transfer the string in my ListView in my first Activity to the EditText in my second Activity. I now want to edit the text and send it back to update my ListView in my first Activity. I basically want to have the edits be sent back to the first activity as a popup to help me test which string is being passed back
I'm not sure what Intent to put in my onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
Here is my first Activity:
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
private final int REQUEST_CODE = 20;
//private Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
onActivityResult(REQUEST_CODE, RESULT_OK, /** Intent variable **/);
}
private void launchEditItem(String item) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", item); // list item into edit text
//startActivityForResult(i, REQUEST_CODE);
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
String text = (String) lvItems.getItemAtPosition(pos);
launchEditItem(text);
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
}
I thought about using the Intent from the second activity but I'm not sure how to do so.
Here is my second Activity.
public class EditItemActivity extends Activity {
private EditText etEditItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
etEditItem = (EditText)findViewById(R.id.etEditItem);
etEditItem.setText(ItemToEdit);
onSubmit(etEditItem);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_item, menu);
return true;
}
public void DoneEdit(View v) {
this.finish();
}
public void onSubmit(View v) {
EditText etName = (EditText) findViewById(R.id.etEditItem);
Intent data = new Intent();
data.putExtra("EditedItem", etName.getText().toString());
setResult(RESULT_OK, data);
finish();
}
}
To get result form an activity (child) you do as follow :
In the parent activity
startActivityForResult(myIntent, 1);
global vars of your parent activity
boolean backFromChild = false;
String aString;
then still in the parent activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// code for result
aString = getIntent().getExtras().getString("aString");
backFromChild = true;
}
if (resultCode == RESULT_CANCELED) {
// Write your code on no result return
}
}
}
in your child you do somewhere something like that
Intent returnIntent = new Intent();
//example of sending back a string to the parent.
returnIntent.putExtra("aString", aString);
setResult(RESULT_OK, returnIntent);
finish();
The thing is that onResume of your parent activity will be called when returning from your child. In there you have to perform the update, in your case it is to update the information of the edited text :
#Override
public void onResume(){
super.onResume();
if (backFromChild){
backFromChild = false;
//do something with aString here
Toast.makeText(this, aString, Toast.LENGTH_SHORT).show();
}
}
Basically, in the onActivityResult I get the info back from the intent of the child. Then in onResume I use this info.
For your concern you can utilize SharedPreferences
For ex: Put data in SP in second activity like this
SharedPreferences spppp = getSharedPreferences("tab", 0);
SharedPreferences.Editor editors = spppp.edit();
editors.putString("for", "0");
editors.commit();
and fetch data for list view in first activity like this
SharedPreferences spppp = getSharedPreferences("tab", 0);
String your_list_view_value = spppp.getString("for", "");

Categories