Removing item from list on other activity - android

How can I remove a item from a ListActivity from a button on another Activity, the thing is,
I have this ListActivity:
public class ListaEventos extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onRestart();
republicar();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.lista_eventos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.criar_evento:
Intent criar = new Intent(this, CriarEvento.class);
startActivity(criar);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void republicar() {
List<DadosEvento> eventos = MySingleton.getInstance().getEventos();
setListAdapter(new ArrayAdapter<DadosEvento>(this, android.R.layout.simple_list_item_1, eventos));
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
DadosEvento clickNumber = MySingleton.getInstance().getEventos().get(position);
Intent intent = new Intent(this, ExibirEvento.class);
Bundle exibirEvento = new Bundle();
exibirEvento.putString("exibirNome", clickNumber.getNome());
exibirEvento.putString("exibirData", clickNumber.getData());
exibirEvento.putString("exibirEnd", clickNumber.getEndereco());
exibirEvento.putString("exibirTel", clickNumber.getTel());
intent.putExtras(exibirEvento);
startActivity(intent);
}
}
Other Activity:
public class ExibirEvento extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exibir_evento);
Intent intent = getIntent();
Bundle exibirEvento = intent.getExtras();
String exibirNome = exibirEvento.getString("exibirNome");
String exibirData = exibirEvento.getString("exibirData");
String exibirEnd = exibirEvento.getString("exibirEnd");
String exibirTel = exibirEvento.getString("exibirTel");
TextView exibir_nome = (TextView) findViewById(R.id.exibirevento_edittext_nome);
exibir_nome.setText(exibirNome);
TextView exibir_data = (TextView) findViewById(R.id.exibirevento_edittext_data);
exibir_data.setText(exibirData);
TextView exibir_end = (TextView) findViewById(R.id.exibirevento_edittext_end);
exibir_end.setText(exibirEnd);
TextView exibir_tel = (TextView) findViewById(R.id.exibirevento_edittext_tel);
exibir_tel.setText(exibirTel);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.exibir_evento, menu);
return true;
}
public void sairExibicao(View v) {
finish();
}
}
Now, on the ExibirEvento is where it shows me the infos about the Party, and there I need a button that removes that item from the List.

Well there are several scenarios that you can follow.
Use startActivityForResult instead of startActivity and then override the onActivityResult method and catch a proper requestCode and result (e. g. RESULT_OK) and delete current item and notifyDataChanged the adapter
Use singelton class, create newInstance, set values, and then refere to it from ExibirEvento
Use the database, and take advantage of ContentProvider and Loader, and pass only the ID of the entry to ExibirEvento
I think that the 3 option is the best way to go for.

Related

Passing variable from onCreate() to onPause()

I have a variable storyID that I have successfully set in onCreate. But when I try to access it in onPause it returns 0.
I presume this is a scoping issue, but can't see where I'm going wrong?
public class StoryBodyActivity extends AppCompatActivity {
private TextView storyBodyTextView;
private ScrollView storyBodyScrollView;
public int storyID;
Parcelable state;
int scrollY;
#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_story_body, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_body);
Bundle extras = getIntent().getExtras();
String story = extras.getString("story");
int storyID = extras.getInt("story_id");
Log.i("stories", Integer.toString(storyID));
// show back arrow
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(story);
storyBodyTextView = (TextView) findViewById(R.id.story_body_text_view);
storyBodyScrollView = (ScrollView) findViewById(R.id.story_body_scroll_view);
DatabaseHelper db = new DatabaseHelper(this);
String storyBody = db.getStoryBody(storyID);
storyBodyTextView.setText(Html.fromHtml(storyBody));
if(state != null) {
Log.d("pause", "trying to restore textview state..");
storyBodyTextView.onRestoreInstanceState(state);
}
int scroll = storyBodyScrollView.getScrollY();
Log.i("scroll", Integer.toString(scroll));
}
#Override
public void onPause() {
// Log.d("pause", "saving listview state # onPause");
// state = storyBodyTextView.onSaveInstanceState();
scrollY = storyBodyScrollView.getScrollY();
// Log.i("scroll", Integer.toString(scrollY));
Log.i("insert", Integer.toString(storyID));
DatabaseHelper db = new DatabaseHelper(this);
db.saveScrollPosition(scrollY, storyID);
super.onPause();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Remove int from int storyID in the onCreate method

Saving booleans to bundles for later use in Android

When I try to save a boolean to a Bundle, it appears to save (from Print Outs), but then the system does not invoke the onRestoreInstanceState method during the process of recreation after returning from visiting the settings page of the app. (The settings are in a separate activity, tapped on from the options list in the upper right-hand corner)
According to:
https://developer.android.com/training/basics/activity-lifecycle/recreating.html
The onRestoreInstanceState method will only be invoked if the Bundle != null.
I also put it into the onCreate method (with a null checker) and the Bundle always turns up null.
I don't have enough reputation to post images, but this link shows the logcat: https://www.dropbox.com/s/v6vw9ynw5az5zhg/AndroidLogCat.PNG?dl=0
public class MyActivity extends AppCompatActivity {
public final static String SWITCH_NAME = "com.company.name.myactivity.SWITCH";
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
System.out.println("RESTORING INSTANCE STATE");
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
System.out.println("RECEIVED INSTANCE STATE");
}
System.out.println("test");
super.onCreate(savedInstanceState);
System.out.println("TEST");
setContentView(R.layout.activity_my);
System.out.println("TeSt");
}
#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_my, menu);
return true;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
System.out.println("SAVING STEP 1: " + getSwitchValue());
savedInstanceState.putBoolean(SWITCH_NAME, getSwitchValue());
System.out.println("SAVING TEST BEFORE SUPERCLASS: " + savedInstanceState.getBoolean(SWITCH_NAME));
super.onSaveInstanceState(savedInstanceState);
System.out.println("SAVING TEST AFTER SUPERCLASS: " + savedInstanceState.getBoolean(SWITCH_NAME));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean getSwitchValue() {
boolean switchValue = true;
Switch aSwitch = (Switch) findViewById(R.id.switch1);
if (aSwitch != null) switchValue = aSwitch.isChecked();
return switchValue;
}
}
Thanks!
Robbie

passing value from mainactivity to a listview

Hi everyone I am currently developing an android app, I am having some confusions in the code, I have a main activity in which I store some array values.
I have two xml files(one mainactivity.xml and other the other one is listview.xml)
In main activity.xml there are four switches, when I click any particular switch it should take me to the listview.xml, with a corresponding array displayed on list view by list view adapter. The code is as follows
public class MainActivity extends ActionBarActivity {
ListView l;
Button chem = (Button) findViewById(R.id.button4);
public String[] contentc = {
"Abundance",
"Anxiety",
"Bruxism",
"Discipline",
"Drug Addiction"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l= (ListView) findViewById(R.id.listview);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_element, contentp);
chem.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
setContentView(R.layout.list);
l.setAdapter(adapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message")

saving items in Parse query adapter in main activity to favorites adapter by click

I want to be able to touch the items in the main activity and once touch the item will save to the favorites class. I'm assuming I need to implement and OnItemClickListener but I am having trouble implementing it correctly. please help
Also do I need to add another intent code and place the onclicklistener inside of there? If more information is needed please let me know, I have been stuck on this issue for awhile now. Thank you
This is my main activity code
import com.parse.ParseQueryAdapter;
public class WingmanListActivity extends ListActivity {
private ParseQueryAdapter<Tip> mainAdapter;
private FavoriteTipAdapter favoritesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setClickable(true);
mainAdapter = new ParseQueryAdapter<Tip>(this, Tip.class);
mainAdapter.setTextKey("title");
mainAdapter.setImageKey("photo");
//Subclass ParseQueryAdapter
favoritesAdapter = new FavoriteTipAdapter(this);
//Default view is all wingman tips
setListAdapter(mainAdapter);
/* String url = "http://twitter.com/";
WebView view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url); */
}
#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_wingman_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh: {
updateTipList();
break;
}
case R.id.action_favorites: {
showFavorites();
break;
}
case R.id.action_new: {
newTip();
break;
}
case R.id.twitter: {
twitter();
break;
}
}
return super.onOptionsItemSelected(item);
}
private void twitter() {
Intent a = new Intent(this, Twitter.class);
startActivityForResult(a, 0);
}
private void updateTipList() {
mainAdapter.loadObjects();
setListAdapter(mainAdapter);
}
private void showFavorites() {
favoritesAdapter.loadObjects();
setListAdapter(favoritesAdapter);
}
private void newTip() {
Intent i = new Intent(this, NewTipActivity.class);
startActivityForResult(i, 0);

error whilst passing values between activities

I have an activity which has an edit text which becomes visible when a button is clicked. I fill the edit text up and click another button. On clicking this button the edit text content must be sent to another activity.The first activity takes the edit text and queries a list of data from my Parse database and shows it in a ListView in the Second Activity.But whenever i click the first button(after entering the string) the app crashes.This is the first activity
public class MainActivity extends ActionBarActivity {
String name;
EditText search;
Button g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpSpinners();
Parse.initialize(this, "AAh5US7zhbYyFBexsv07cjo34ZZiB7KNe9SuTv7e",
"eKUG1pYaV50hVyDC9d4qZc4qf1dCtOTqnX92eGJV");
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation();
search = (EditText) findViewById(R.id.search);
g = (Button) findViewById(R.id.Go);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void byName(View v) {
search.setVisibility(View.VISIBLE);
search.requestFocus();
g.setVisibility(View.VISIBLE);
}
public void Go(View v) {
name = search.getText().toString();
final Intent i;
i = new Intent(MainActivity.this, ResterauntList1.class);
i.putExtra("restrauntName", name);
startActivity(i);
}
}
In the above byName is the onClick for making the EditText visible, and Go is the onClick for getting my EditText string and passing it to the next activity. The second activity is below
public class ResterauntList1 extends Activity {
String rValue;
ArrayAdapter<String> adapter;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resteraunt_list1);
Bundle bdl = getIntent().getExtras();
rValue = bdl.getString("restrauntName");
setContentView(R.layout.activity_resteraunt_list);
populateList(rValue, "name");
}
private void populateList(final String Value, final String Key) {
ParseQueryAdapter.QueryFactory<ParseObject> factory = new ParseQueryAdapter.QueryFactory<ParseObject>() {
#Override
#SuppressWarnings({ "unchecked", "rawtypes" })
public ParseQuery create() {
ParseQuery query = new ParseQuery("resdb");
query.whereEqualTo(Key, Value);
return query;
}
};
ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(
this, factory);
adapter.setTextKey("name");
adapter.addOnQueryLoadListener(new OnQueryLoadListener<ParseObject>() {
#Override
public void onLoading() {
mProgressDialog = new ProgressDialog(ResterauntList1.this);
mProgressDialog.setTitle("Searching for " + Value);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
public void onLoaded(List<ParseObject> objects, Exception e) {
mProgressDialog.dismiss();
}
});
final ListView listView = (ListView) findViewById(R.id.restListView1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ParseObject object = (ParseObject) listView
.getItemAtPosition(position);
String Id = object.getObjectId();
Intent i = new Intent(getApplicationContext(),
SingleRestraunt.class);
i.putExtra("restId", Id);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.resteraunt_list1, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The error as stated above occurs when I click the Go button.The error is
09-02 14:58:46.443: E/AndroidRuntime(3061): Process: com.example.gastronomaapp, PID: 3061
09-02 14:58:46.443: E/AndroidRuntime(3061): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gastronomaapp/com.example.gastronomaapp.ResterauntList1}: java.lang.NullPointerException
Any idea where I am making a mistake? The funniest thing almost the same code has worked in another part of my app. absolutely clueless whats wrong.
Bundle bdl = getIntent().getExtras();
rValue = bdl.getString("restrauntName");
change to
rValue = getIntent().getStringExtra("restrauntName");
You put the string directly on the intent, not packaged in a bundle.

Categories

Resources