I am very new in Android, doing code using google only, plz help.
Here is my code from custom adapter, which is for custom view which is having list of text and buttons, on button click event i want to start new activity, like for example, if user press button which is in front of "Geometry" text, then new activity should get start, what should I pass to intent in above code:
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(txtListChild.getText().toString()=="Geometry")
{
Toast.makeText(_context, txtListChild.getText().toString(),
Toast.LENGTH_LONG).show();
**Intent i=new Intent();**
_context.startActivity(i);
}
}
});
return convertView;
}
Make intent like
Intent i=new Intent(_context,secondActivity.class);
_context.startActivity(i);
Remember you must register secondActivity in manifest.xml
and also you should change
if(txtListChild.getText().toString()=="Geometry")
to
if(txtListChild.getText().toString().equals("Geometry"))
always used .equals() method for string comparison.
-By passing context from activity to the adapter like
Youadapter obj=new Youradapter(Youactivity.this);
-In you adapter class set you Context con;
-and using con.startactivity;
How to start new activity on button click event in custom adapter?
First, use String.equals for comparing strings:
if(txtListChild.getText().toString().equals("Geometry"))
Second, to start Activity using string class name use Class.forName to get class:
Class<?> c = Class.forName(txtListChild.getText().toString());
Intent i=new Intent(v.getContext(),c);
And make sure all activities are declared in AndroidManifest.xml
NOTE: if txtListChild.getText() return Activity name then no need to use if-else just use Class.forName to get class and pass it as last parameter of Intent constructor :
Related
The following code returns a null value. Can anyone please tell me why? I'm looking to use the returned value to send it to another activity in an intent the Choice string is declared in the class this code belongs to:
public String SetupBreakfastSpinner()
{
Choice = "";
SpinnerSelector= ArrayAdapter.createFromResource(HomeActivity.this, R.array.breakfastArray, android.R.layout.simple_spinner_item);
SpinnerSelector.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Breakfast.setAdapter(SpinnerSelector);
Breakfast.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Choice= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return Choice;
}
In method SetupBreakfastSpinner you are initializing Choice to empty string. When you call this method you are setting adapter to spinner correctly but immediately returning Choice which is still empty.
As you have to send Choice value to another activity, you have two options:
Approach 1: When user choose an Item in spinner, onItemSelected callback gets called:
void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Choice= parent.getItemAtPosition(position).toString();
//start your activity here, pass Choice value in the Intent
}
Approach 2: Assuming that you have some button, which when clicked you start activity, in onClick of button you can start activity
void onClick(View v){
//Start activity, pass Choice in Intent
}
Keep in mind that values that changes on certain event, for example
here Choice variable gets updated when user choose values, you need
to be careful before using such variables, such variable might be
null.
There is an Activity that displays listItems (through a cursorAdapter).
The listItem's XML contains some buttons. In the Cursor Adapter's newView() method, these buttons get the onClickListener, not by an anonymous declaration, there's a class that implements the listener. If there's a click on a certain button, the activity where all that happens, should finish.
I'm not surprised that calling finish() in the button class doesn't work. activityContext.finish doesn't work either.
So how can I manage that?
public class DetailActvityActionBtn implements View.OnClickListener {
private Context context;
#Override
public void onClick(View view){
context = view.getContext();
System.out.println("CONTEXT:" + context);
///Itemroot
LinearLayout root =(LinearLayout) view.getRootView().findViewById(R.id.detailRoot);
///Tag that stores data
ItemViewAndDataHolder holder = (ItemViewAndDataHolder) root.getTag();
System.out.println("HOLDER: " + holder.toString());
//Get id of item
int id = holder.getId();
//Get quantity of item
int quantity = Integer.parseInt(holder.getQuantity().getText().toString().replaceAll("[^0-9]",""));
///Append id to URI
Uri updateItemUri = ContentUris.withAppendedId(InventoryDB_Contract.entries.CONTENT_URI, id);
///To determine the clicked button, get ID as String
String btnIDasString = context.getResources().getResourceName(view.getId());
System.out.println(btnIDasString);
ContentValues values = new ContentValues();
int updatedRow;
switch (btnIDasString){
case "com.example.android.inventoryapp:id/plusBtn":
System.out.println("plus");
values.put(InventoryDB_Contract.entries.COLUMN_PRODUCT_QUANTITY_IN_STOCK, quantity + 1);
context.getContentResolver().update(updateItemUri, values, null, null);
//CRcaller.saleItem(1);
break;
case "com.example.android.inventoryapp:id/minusBtn":
System.out.println("mins");
values.put(InventoryDB_Contract.entries.COLUMN_PRODUCT_QUANTITY_IN_STOCK, quantity - 1);
updatedRow = context.getContentResolver().update(updateItemUri, values, null, null);
break;
case "com.example.android.inventoryapp:id/deleteItemBtn":
System.out.println("delete");
context.getContentResolver().delete(updateItemUri, null, null);
context.finish();
break;
}
}
}
Typecast your activity context into an activity. And then call finish method
Activity act=(Activity)context;
act.finish();
public class DetailActvityActionBtn implements View.OnClickListener
You are not extending Activity or Fragment or anything along those lines, you have no context to execute context.finish(); from because finish() is a method from Activity.
If this class is utilized from an Activity then pass in that activity's reference to the class constructor, like so:
public MainActivity extends Activity{
//You standard onCreate() blah...
DetailActvityActionBtn yourHandlerClass = new DetailActvityActionBtn(this);
}
public class DetailActvityActionBtn implements View.OnClickListener {
private Activity activity;
public DetailActvityActionBtn(Activity activity){
this.activity = activity;
}
#Override
public void onClick(View view){
//You can now call activity.finish() to close the calling activity...
activity.finish();
}
Personally, I would suggest decoupling the button's reliance upon the existence of an activity. Rather than setting the functionality of onClick within the Button class, why not define the functionality within your controller (Activity)? You can define one onClick method and use your listview logic to determine which buttons should have this functionality.
If you were simply controlling business logic that would be one thing, but I personally think it's convoluted to have the view define the controller life cycle. The controller can give permission to the button to dismiss itself, but any other way and the button starts talking to things it probably shouldn't. Maybe you're following a different paradigm than MVC, so I could be wrong!
I was thinking something along the lines of:
#Override
public View getView(int position, View v, ViewGroup parent) {
if(condition1){
v.button.setOnClickListener(locallyDefinedOnClickForCondition1);
}
else if(condition2){
v.button.setOnClickListener(locallyDefinedOnClickForCondition2);
}
}
Would definitely not say it's the best solution, but maybe this could put you in the right direction. Anyone have any criticism?
I am working on a project where I am showing multiple image in SwipeView with a button. So whenever the button is clicked a new activity will start according to the position of the image in the array. How to do this?
With each item in your list, you need a Class reference on which Activity you want to start, then assign the click listener to pass that Class to an Intent and then startActivity
Assuming you have some ArrayList<Class> list or an ArrayAdapter<SomeObject> adapter, you could do
public void onClick(View v) {
Class activityClass = list.get(clickPosition);
// Class activityClass = adapter.getItem(clickPosition).getActivityToStart();
Intent intent = new Intent(this, activityClass);
startActivity(intent);
}
You could also use a String tag on the View with the name of a class, but you'll need to catch the ClassNotFoundException.
public void onClick(View v) {
String className = (String) v.getTag();
Class activityClass = Class.forName(className);
Intent intent = new Intent(this, activityClass);
startActivity(intent);
}
Set a tag (relevant to the activity being launched) to each ImageView while inflating, using setTag method.
In the onClick handler retrive the tag using the getTag method. Use this information to launch the required activity, using a simple switch case .
The tag can be anything like activity name, array index etc.
More info: What is the main purpose of setTag() getTag() methods of View?
I'm developing a Androidapplication and I want to be able to start an activity through a spinner value the user have selected.
As an example: In the main activity you'll see a spinner with the values "Color", "Animals". If you choose "Color" and click on a button called "Proceed", you will come to an activity that list different colors in a listview, but if you choose "Animal" from the spinner, you will come to the same activity, but this time it shows a listview of animals instead.
Can anybody give me a hint on how to do this?
(PS this is an example on how I want it to work, I actually need to call everything from a Web Service)
you can implement android.widget.AdapterView.OnItemSelectedListener and override the method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
// Call the following method to get the selected value of the spinner and perform your
//task to start your desired activity
String selectedValue=parent.getItemAtPosition(pos).toString();
if(selectedValue.equals("Colors"))
{
//do your task using color
}
else if(selectedValue.equals("Animal"))
{
//do your task using animal
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
//Do Nothing
}
The simplest Solution would be for example:
Spinner yourSpinner = (Spinner)view.findViewById(R.id.your_spinner);
String value = yourSpinner.getSelectedItem().toString();
if(value.equalsIgnoreCase("ANIMAL")){
Intent intent = new Intent(yourActivity.this, yourNextActivity.class);
intent.putExtra("VALUE", value);
startActivity(intent)
}
Then in that Activity that You want to start:
Intent intent = getIntent();
String value= intent.getStringExtra("VALUE");
if(value.equalsIgnoreCase("ANIMAL")){
//start the part with animals
}
Its really simple just use bundle and send the appropriate data to your next activity. A small sample would look like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String spinnerText = spinner.getSelectedItem().toString();
Intent intent = new Intent(A.this,B.class);
intent.putExtra("selection",spinnerText);
}
});
Then in your next activity get the sent text and manipulate accordingly.
Heres my first class
public void onClick(View view) {
Intent i = new Intent(First.this,second.class);
startActivity(i);
cat=(EditText) findViewById(R.id.textView_cat);
String s = getIntent().getStringExtra("myString");
cat.setText(s);
Heres my second class
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
String selectedFromList = o.get("name");//(String) (lv.getItemAtPosition(position));
Intent i = new Intent(second.this, First.class);
i.putExtra("myString", selectedFromList);
startActivity(i);
}
I want to go to the second class (second screen) after clicking button of first(on first screen). Then i want to access the value of listitem selected in second class(screen) in first(screen). But having problem in doing that. Help would be appreciated..!!
I am enabled to pass the value from first.class to second.class but i want to take value in second.class and access it in first.class.. !! Theres the problem...!!!
Thanx.
There are two ways to pass variables.
1) Use the extra value of your intent:
myIntent.putExtra(String name, Bundle value);
Here is the android documentaton on that.
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String, android.os.Bundle)
2) Use an application class.
http://developer.android.com/reference/android/app/Application.html
The application class creates a singleon that you can use to make data avaible to any activity. The activity references the application through
activity.getApplication();
http://developer.android.com/reference/android/app/Activity.html#getApplication()