How do I call the Activity to start again? - android

I am creating a quiz to practice Android programming. I am able to run the Android program and it works fine. But now, I have added a ContextMenu. If I click any item, the Activity should restart with a new value. But it does not.
TextView Qsn;
Button TopicTitle;
Button Ybtn;
Button Nbtn;
String check;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
Qsn = (TextView) findViewById(R.id.Question);
TopicTitle = (Button)findViewById(R.id.Topictxt);
Ybtn = (Button)findViewById(R.id.Yesbtn);
Nbtn = (Button)findViewById(R.id.Nobtn);
Intent intent = getIntent();
Bundle bundle =intent.getExtras();
check=bundle.getString("Bundlekey") ;
TopicTitle.setText(check);
Toast.makeText(getApplicationContext(), check, Toast.LENGTH_SHORT) .show();
registerForContextMenu(TopicTitle);
if (check.matches("History")) {
....
}
}
The code check what topic has been selected and it works fine till here. But now I've added a ContextMenu so if the user wants to change the topic he can long-press on the button and select the topic and change his new topic for a new question.
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.topic_selection_in_question, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
String Value_from_item ;
Value_from_item = (String) item.getTitle();
check = Value_from_item;
Intent intent = getIntent(); finish(); startActivity(intent);
return super.onContextItemSelected(item);
}
Where did I make the mistake? Is there an error in the logic? I do not get a runtime error. Everything works fine. I would be glad if you can help me out. Thanks in advance.

Instead of this code
Intent intent = getIntent(); finish(); startActivity(intent);
Use
Intent intent = new Intent(youractivity.this, Youractivity.class);
finish();
startActivity(intent);

Related

Unable to start intent from within ListActivity OnItemListClick

I am trying to use the OnItemListClick method of ListActivity to launch a new activity with more specific information about the list item. To do this I am using a bundle as advised by the top answer of How do I pass an object from one activity to another on Android? but no matter what I try the OnItemListClick doesn't seem to do anything. I also tried without passing the bundle thinking that was causing a problem as advised here Using an intent to start new activity from ListActivity and that also does nothing onClick. How am I supposed to make it so when an item in the listview is clicked it returns the object associated with that row and passes it to a new activity?
public class TaskList extends ListActivity {
private ArrayList<Task> stuffToDo, completed;
private TaskAdapter t_adapter;
public Button add;
private File saveFile;
private Bundle clickBundle = new Bundle();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_list);
stuffToDo = new ArrayList<Task>();
completed = new ArrayList<Task>();
t_adapter = new TaskAdapter(this, R.layout.row_rl, stuffToDo);
setListAdapter(t_adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Make a bundle and put the Task selected in it then pass this to the
// intent to start the new activity
Intent launchIntent = new Intent(getApplicationContext(), TaskDisplay.class);
Log.d("Debug", "Intent made");
clickBundle.clear();
clickBundle.putSerializable("Task", stuffToDo.get(position));
Log.d("Debug", "Task put in bundle");
launchIntent.putExtras(clickBundle);
this.startActivity(launchIntent);
Log.d("Debug", "launched");
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.addtaskbutton:
promptUserForInfo();
t_adapter.notifyDataSetChanged();
// added for debug
saveInfo();
return true;
case R.id.cleartasks:
clearTasks();
t_adapter.notifyDataSetChanged();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
and my code that is in the more specific activity
// Set the bundle equal to the extra put with the intent
input = this.getIntent().getExtras();
// If there are extras(a task) then assign it to the empty task variable
if (input != null){
task = (Task) input.getSerializable("Task");
}
here this mean you are pointing towards list.
change Intent launchIntent = new Intent(this, TaskDisplay.class);
to Intent launchIntent = new Intent(youractivityname.this, TaskDisplay.class);
or to Intent launchIntent = new Intent(getApplicationContext(), TaskDisplay.class);
and make this super.onListItemClick(l, v, position, id); first line of list item click method.
Try this...
this.startActivity(launchIntent);

Android finishing activity not working

Once the user chooses a product from my ListView, it then puts the selected text from that ListView into an EditText. The problem I am having is when the user selects a product from the list, and then presses back, it comes up with the list again instead of returning to the EditText activity.
I have tried using "finish();" after the activity starts but nothing seems to be working.
Activity that holds the EditText that launches the List activity:
EditText CPU = (EditText) findViewById(R.id.autoCompleteTextView4);
CPU.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CPUList = new Intent(getApplicationContext(),
CPUList.class);
startActivityForResult(CPUList, 1);
Intent i = getIntent();
String product = i.getStringExtra("key");
EditText CPU = ((EditText) findViewById(R.id.autoCompleteTextView4));
CPU.setText(product);
}
});
List view class
#Override
public void onCreate(Bundle OnsaveInstanceState) {
super.onCreate(OnsaveInstanceState);
setContentView(R.layout.activity_cpulist);
ListView listViewCPU = (ListView) findViewById(R.id.listViewCPU);
listViewCPU.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
String CPUList[] = {
"CPU's go here", "CPU's go here", "CPU's go here", "CPU's go here" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, CPUList);
listViewCPU.setAdapter(adapter);
listViewCPU.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View myView,
int pos, long mylng) {
String CPU = (String) listview.getAdapter().getItem(pos);
Intent i = new Intent();
i.putExtra("key", CPU);
setResult(1, i);
finish();
}
});
You need to launch your activity in a way that it doesn't get added to back stack.
Here's how you do that: https://stackoverflow.com/a/12358563/375929
If I understand you correctly, you are calling finish() on the wrong Activity. If you want the list Activity to finish then that's where you need to call finish()
#Override
public void onItemClick(AdapterView<?> listview, View myView,
int pos, long mylng) {
String CPU = (String) listview.getAdapter().getItem(pos);
Intent i = new Intent(getApplicationContext(),
ListmenuActivity.class);
i.putExtra("key", CPU);
startActivity(getIntent());
startActivity(i);
finish(); // finish here
}
and remove finish() from your EditText Activity
Another issue I see is it looks like you are starting that second bit of code with the first using startActivityForResult() but you aren't sending back a result in your second code. Instead, you seem to be starting another Activity. It seems that second bit should be more like
#Override
public void onItemClick(AdapterView<?> listview, View myView,
int pos, long mylng) {
String CPU = (String) listview.getAdapter().getItem(pos);
Intent i = new Intent();
i.putExtra("key", CPU);
setResult(1, i);
finish(); // finish here
}

Can't delete database item after page first loads

I have a task reminder that allows you to store info in a database and then edit or retrieve them later (like a notepad). Whenever starting the app and then going to the activity it will display the saved items but will crash if you try to select and delete one.
You can even click on it to review it, just not delete. If you first add another item then you can delete any and all of them. If I switch to another app and come back to it, it's fine. Only if the app completely shuts down before coming back to delete does it cause a problem.
I'm utterly stumped.
Here is the beginning that displays the items
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
mDbHelper.open();
fillData();
setContentView(R.layout.meds);
registerForContextMenu(getListView());
}
private void fillData() {
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
String[] from = new String[] { RemindersDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter reminders = new SimpleCursorAdapter(this,
R.layout.reminder_row, remindersCursor, from, to);
setListAdapter(reminders);
}
And the Context Menu for deleting
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu_item_longpress, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_delete) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
long mRowId = info.id;
cancelReminder();
mDbHelper.deleteReminder(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
I don't think it's in the database because it will delete just fine if the app has already stored something else.
EDIT
I have been trying to debug this problem and found the location of the error in the method cancelReminder
public void cancelReminder() {
alarmid = Integer.parseInt(malarmid);
Log.e(TAG2, "meds screen alarmid " + alarmid);
Intent i = new Intent(ReminderManager.mContext, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(ReminderManager.mContext,
alarmid, i, PendingIntent.FLAG_UPDATE_CURRENT);
ReminderManager.mAlarmManager.cancel(pi);
}
The error is in the Intent for some reason. This is where I am deleting the alarm for the reminder. It is orginally set in another activity and here is where I am removing it. What really gets confusing is if the app has been running and I save another reminder I can delete them. If I start the app and go right to a reminder to delete it, it crashes.
Found the answer to the problem....
Trying to cancel the repeating alarm from this activity wouldn't work because it couldn't get the context. Instead I passed the string info for the alarm to my alarmManager class and removed it there.
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long mRowId = info.id;
Cursor reminder = mDbHelper.fetchReminder(mRowId);
startManagingCursor(reminder);
malarmid = reminder.getString(reminder
.getColumnIndexOrThrow(RemindersDbAdapter.KEY_RANDOM));
Log.e(TAG2, "meds screen malarmid " + malarmid);
mDbHelper.deleteReminder(info.id);
fillData();
new ReminderManager(this).cancelReminder(info.id, malarmid);
return true;
}
return super.onContextItemSelected(item);
}
and the reminderManager class
public void cancelReminder(long mRowId, String malarmid) {
int alarmid = Integer.parseInt(malarmid);
Log.e(TAG2, "Reminder Manager Cancel Reminder convert from malarm to alarmid " + alarmid);
Intent i = new Intent(mContext, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(mContext,
alarmid, i, PendingIntent.FLAG_UPDATE_CURRENT);
ReminderManager.mAlarmManager.cancel(pi);
}

How to get data from listview to context menu?

actually i got a problem while creating my project. I am having one list view in one screen where data comes from database & binds to it. I created one context menu here with two menus (view & delete). The problem i am facing is when i make a long click context menu occur & when i click on anyone of the menu it navigates to another screen. here i want the listview(which was clicked) item data to pass to next screen. By i am not getting it. This is the following code...
Main.java
/*******some code****/
DbHandler dbh=new DbHandler(GroupName.this);
ast=dbh.selectgroupnam(s);
//here "ast" is of ArrayList defined globally
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ast);
lv.setAdapter(adp);
registerForContextMenu(lv);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View v, int p, long arg3) {
// TODO Auto-generated method stub
TextView tv=(TextView)v;
String gnam=tv.getText().toString();
}});
}//on create
//context menu code
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, "View");
menu.add(0, v.getId(), 0, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "group name" + gnam,30).show();
if (item.getTitle() == "Delete") {
Toast.makeText(getApplicationContext(), "selected group" + gnam, 30).show();
startActivity(new Intent(GroupName.this,GroupEdit.class));
}
else
{
startActivity(new Intent(GroupName.this,GroupEdit.class));
}
return super.onContextItemSelected(item);
}
As per the following code how to get the list view data (which was long clicked for context menu) & pass the data to GroupEdit.class.
Waiting for reply......
So you start activity startActivity(new Intent(GroupName.this,GroupEdit.class))
but any data you are adding to intent.
So try it with putExtra(<key>,<data>) or if you want to use Bundle so putExtras(<bundle>)
You should to it like this:
Intent i = new Intent(GroupName.this,GroupEdit.class);
i.putExtra("key", <data>);
startActivity(i);
Then in new Activity GroupEdit you get this data with getIntent() method that return the intent that started this activity and getExtras() with it you retrieve a map of extended data from the intent.
So in GroupEdit String text = getIntent().getExtras().getString("keyOfField")
Of you will use Bundle so
Intent i = new Intent(GroupName.this,GroupEdit.class);
i.putExtras(bundle);
startActivity(i);
in GroupEdit you retrieve data with Bundle data = getIntent().getExtras()
Regards

Android one activity to to popup window

My requirement is : List all sales route & highlight default, It should be first option. If the salesperson select other option(not selected default), then popup window should come. The popup window contain one form, it talk to DB.After submit the popup window form , it return previous screen , It need to allow to go other position.
See my code
This initial list Activity:
ArrayList<Object> routeList = getWmRoute();
ArrayList<String> routhPath = new ArrayList<String>();
for(int i = 0; i<routeList.size();i++){
routhPath.add(((WMRoute) routeList.get(i)).getDescription());
}
ArrayAdapter ad = new ArrayAdapter(this,android.R.layout.simple_list_item_single_choice,routhPath);
setListAdapter(ad);
final ListView list=getListView();
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setItemsCanFocus(true);
list.setTextFilterEnabled(true);
list.setItemChecked(0,true);
list.setSelection(0);
This is listener method
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(position !=0 ){
Bundle bundle = new Bundle();
int postion = position;
String aString = Integer.toString(postion);
bundle.putString("positon", aString);
Intent showContent = new Intent(getApplicationContext(),SalesRouteDevitionActivity.class);
// startActivityForResult(showContent,0);
startActivity(showContent);
}
}
This is my SalesRouteDevitionActivity class
array_spinner=new String[2];
array_spinner[0]="Rain";
array_spinner[1]="Floods";
Bundle bundle = this.getIntent().getExtras();
param1 = bundle.getString("param1");
Spinner s = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, array_spinner);
s.setAdapter(adapter);
final Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(SalesRouteDevitionActivity.this, "Beep Bop", Toast.LENGTH_SHORT).show();
Intent showContent = new Intent(getApplicationContext(),SalesRouteActivity.class);
Bundle bundle = new Bundle();
bundle.putString("position", param1);
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
startActivity(showContent);
}
});
This is my manifest file
<activity android:theme="#android:style/Theme.Dialog" android:name=".SalesRouteDevitionActivity"
android:label="Sales Route Diviation">
</activity>
After finish pop window work , how we can go to previous activity that particular place?
Please help me...
Thanks in advance
from wherever you start the popup window call it using intent throught call this startActivityForResult(your_intent,requestCode)
it will start the activity and in the popup activity do like this way
Bundle bundle = new Bundle();
bundle.putString("position", param1);
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
so the popup will finish his activity and go back to previous activity where it will invoked with the result
and in your activity override the onActivityResult like this way
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==1){
if(resultCode==RESULT_OK)
Toast.makeText(this, "SUCCESS", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
}
}
You could create a global variable for the position of the selected item. Then when you return to the previous activity, you call listView1.smoothScrollToPosition(int position).
Do you want listview focus on a position which is not default?If so, you only need return intent with position and at onActivityForResult() you set focus at that position.If you have any problems, please add my yahoo or skype:fsoft_duonghv and we discuss .
Instead of starting a new activity for a popup window you can create a AlertDialog. You can call dismiss() to return your activity then.

Categories

Resources