New activity on List Click - android

I have created a list. Now when I click on the list item I want to run a Java class which is another list of names.
Here is my code:
public class SecondAct extends ListActivity {
private String[] items = { "Pending Retailers", "Ordered Retailers",
"No Order Retailers", "Today's Plan", "Messages", "Daily Sales",
"Pending Invoices", "Day Close", "Tools and Updates", "Exit" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, items);
// Get the activity's ListView and set its choice mode as multiple choice
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String selectionValue = "";
selectionValue = (String) getListView().getItemAtPosition(position);
Log.i("List Selection Value: ",
(String) getListView().getItemAtPosition(position));
if (selectionValue.equalsIgnoreCase("Pending Retailers")) {
Intent intent = new Intent("my.com.npi.List");
startActivity(intent);
AlertDialog alertDialog = new AlertDialog.Builder(SecondAct.this)
.create();
alertDialog.setTitle("Pending Retailers Selected");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here we i add functions
}
});
// alertDialog.setIcon(R.drawable.icon);
alertDialog.show();
}
else if (selectionValue.equalsIgnoreCase("Exit")) {
finish();
}
}
}
Now when I click on the first item, the application is forcefully closed. I used intent to start the new activity but it isn't working. Hopelessly stuck! Please help.
Thanks.

if you have Activity in your own Application then use:
Intent electIntent = new Intent();
electIntent.setClass(SecondAct.this, List.class);
startActivity(electIntent);
and in AndroidManifest
<activity
android:name = ".List" />
use this intent for starting another app Activity from your appliction:
Intent intent25 = new Intent(Intent.ACTION_MAIN).addCategory(
Intent.CATEGORY_LAUNCHER).setClassName("APP_PACKAGE_NAME",
"APP_PACKAGE_NAME.TestActivity").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_FROM_BACKGROUND).setComponent(new ComponentName("APP_PACKAGE_NAME",
"APP_PACKAGE_NAME.TestActivity"));
getApplicationContext().startActivity(intent25);

First Register The New Activity in Manifest as
Before the application tag in manifest declare package like
<package name="my.com.npi">
<activity android:name = ".List" />
then
give Correct Correct Class name in the Intent.don't use like my.com.npi
just import those package give the plain name as List.class
Intent intent = new Intent(this,List.class);
startActivity(intent);

Related

Updating cursor after returning from intent to mainactivity

So i am having this listview in my MainActivity, which is updated every time the main activity is started or resumed.
The code for that is
#Override
public void onResume()
{
super.onResume();
Cursor array_list_patients = mydb.getAllPatientsDetails();
PatientAdapter arrayAdapter = new n
PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
}
Now for the listview in the MainActivity i have a setOnItemClickListener as shown below, which basically displays the data in another activity "ModifyPatient". Code for that is:
Cursor array_list_patients = mydb.getAllPatientsDetails();
final PatientAdapter arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Cursor cur = (Cursor) arrayAdapter.getItem(arg2);
cur.moveToPosition(arg2);
int id_To_Search = cur.getInt(cur.getColumnIndexOrThrow("id"));
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),ModifyPatient.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
Now in the ModifyPatient class.. i can do Upate/Delete operations on the database entry. Now the problem is, when i do a delete operation and return back to the MainActivity, and click on any item in the listview, i get an OutOfBounds exception for the cursor. The current code for delete button in the ModifyPatient class is as follows:
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ModifyPatient.this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deletePatient(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
ModifyPatient.this.finish();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
}
});
This deletes the entry and returns to the mainactivity, but clicking on any of the items in the listview throws the error which i mentioned before.
I have done a small workaround, where i have replaced the below line:
ModifyPatient.this.finish();
with
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
But the problem with this is, the original activity remains in the background and a new MainActivity is forked. So pressing the back button, goes back to the original activity with the stale listview.
If somebody can help me out, with how to update the cursor, because i could not implement the swapcursor in my case. I am not sure what i am doing wrong.
Thank you in advance.
i set my variable "arrayAdapter" present in the onResume and onItemClickListener in the MainActivity from local to global, and that did the trick.
New code, where arrayAdapter is global:
public void onResume()
{
super.onResume();
Cursor array_list_patients = mydb.getAllPatientsDetails();
arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
}
and
arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Cursor cur = (Cursor) arrayAdapter.getItem(arg2);
cur.moveToPosition(arg2);
int id_To_Search = cur.getInt(cur.getColumnIndexOrThrow("id"));
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),ModifyPatient.class);
intent.putExtras(dataBundle);
startActivity(intent);
arrayAdapter.notifyDataSetChanged();
}
});

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
}

Have a Search Activity return a result?

Hi I was wondering how I can get my Search Activity to return a result back to the Activity that started it.
I currently have a Search Dialog implemented (meaning the search Activity starts once the Search button on the phone is clicked).
Here is my code for the Search activity which is a list view.
public class ItemFinder extends ListActivity {
public static final int REQUEST_CODE = 1; // get it?
Vector<String> upcCodes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
upcCodes = new Vector<String>();
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String upc = upcCodes.elementAt(position);
setResult(RESULT_OK);
}
});
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
ProgressDialog dialog = ProgressDialog.show(ItemFinder.this, "Searching",
"Searching. Please wait...", true);
performSearch(query);
dialog.hide();
dialog.dismiss();
}
}
public void performSearch(String query){
String result = new SmartShopClient().SearchItems(query);
List<String> dataList = new ArrayList<String>();
String _parsedResult[] = result.split("\\n");
for( int i = 0; i<_parsedResult.length; i++){
String _splitData[] = _parsedResult[i].split("\\|");
String itemName = _splitData[0];
String itemUPC = _splitData[1];
dataList.add(itemName);
upcCodes.add(itemUPC);
}
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
this.setListAdapter(arr);
}
}
So the search is working all fine and dandy, but I want it so when I click one of the results in the ListView, for it to return data back to the main activity with some data, say the name of the clicked searched result.
Thanks.
What you want to do is launch the search using startActivityForResult. See an explanation here.
This way, you can pass your search results back to the activity which launched it.
That would happen in your setOnItemClickListener method, where you could launch an explicit intent naming the desired activity with extra data.
Edit : I'm not quite sure of how startActivityForResult() would be implemented since we're talking about the search activity of the application, meaning it's launched by the Android search specific module ; that's why i suggested the above solution.
I ended up doing this:
public boolean onSearchRequested() {
askSearchQuery();
return true;
}
public void sendSearchRequest(String query){
Intent mIntent = new Intent(this, ItemFinder.class);
mIntent.setAction(Intent.ACTION_SEARCH);
mIntent.putExtra(SearchManager.QUERY, query);
startActivityForResult(mIntent, ItemFinder.REQUEST_CODE);
}
public void askSearchQuery() {
final EditText input = new EditText(SmartShop.this);
AlertDialog.Builder adb = new AlertDialog.Builder(SmartShop.this);
adb.setTitle("Search Items");
adb.setMessage("Please input the name of the item you are looking for.");
adb.setView(input);
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable upc = input.getText();
sendSearchRequest(upc.toString());
dialog.cancel();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
adb.create().show();
}
And then I hooked the
protected void onActivityResult (int requestCode, int resultCode, Intent data) {

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.

Android - Change View when alertdialog button is clicked

I have a listview with a couple of strings in at the moment. when a user selects one it brings up an alertdialog box which gives the option to book(this is going to be a taxi app) or cancel. What i cant work out is how to get it so that when the user clicks "Book" it takes the information they've selected and loads up a new view with more contact information.
My Code is currently this -
public class ListTaxi extends ListActivity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You have chosen = "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", null);
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
Any help or pointers with this would be immensely appreciated as its the last bit i need to get working before its almost done.
Thanks everyone
Oli
You need to put an onClickListener onto your positive button, which will launch the new activity and pass the data to it. Your code would become something like:
public class ListTaxi extends ListActivity{ /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You have chosen = "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("booking", taxi[selectedPosition];
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
In your target activity, have something like this:
Intent intent = getIntent();
String booking = "";
if (intent != null) {
Bundle extras = intent.getExtras();
if (extras != null) {
booking = extras.getString("booking");
}
}
One way could be to get your item out of your taxi list:
taxi.get(position);
and pass it through an intent to a next activity:
Intent intent = new Intent(this, YOUR_NEXT_ACTIVITY.class);
intent.putExtra("booking", taxi.get(position);
on the next activity you can get it with:
intent = getIntent();
inten.getExtra("booking");
// could be (not sure): inten.getExtraString("booking");
You can use this method from alertDialog class
public void setButton (int whichButton, CharSequence text, DialogInterface.OnClickListener listener)
Refer link
http://developer.android.com/reference/android/app/AlertDialog.html
depending on positive response, say book is positive response then start another activity which shows details contact info, pass the select item from list as Bundle or extra with intent while starting another activity.

Categories

Resources