I want to call MainActivity class to another activity. This is my code for the MainActivity.java:
package com.blinkedup.geolocationchat;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.Service;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView;
LocationManager locationManager;
MyLocationListener locationListener = new MyLocationListener();
Criteria criteria;
String bestProvider;
String listOfBestProviders;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
criteria = new Criteria();
textView = (TextView) findViewById(R.id.textView1);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
bestProvider = locationManager.getBestProvider(criteria, true);
Toast.makeText(getApplicationContext(), bestProvider, 3).show();
}
protected void onPause(){
super.onPause();
locationManager.removeUpdates(locationListener);
}
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
textView.setText("Latitude: " + location.getLatitude() +
"Longitude: " + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
In another activity I wanted to call the lat and long of the above code but don't want to rewrite the code to the activity. I just want to call it and display the result in another activity. please help. thanks
make your variable static and define it before onCreate() method use that variable in another activity by call like this.
YourMainActivity.yourstaticvariable
Related
I want to edit the tree viewer element based on my context menu option. Basically i need to update the element value which is displayed. If i double click on tree viewer element i was able to update the value, but through context menu also i should be able to do.
Sample code for adding the context menu:
protected def void createContextMenu(Viewer viewer) {
val MenuManager contextMenu = new MenuManager("Menu"); // $NON-NLS-1$
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(new IMenuListener() {
public override void menuAboutToShow(IMenuManager mgr) {
fillContextMenu(mgr);
}
});
val Menu menu = contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
}
/**
* Fill dynamic context menu
*
* #param contextMenu
*/
protected def void fillContextMenu(IMenuManager contextMenu) {
contextMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
contextMenu.add(new Action("Rename") {
public override void run() {
val selectedElement = (treeViewer.selection as IStructuredSelection).firstElement
}
});
}
See if this helps or let me know otherwise
package myFolder;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.MenuListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TreeItem;
public class trying {
public static void main(String[] args){
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setSize(300,300);
TreeViewer viewer = new TreeViewer(shell);
viewer.getTree().setHeaderVisible(true);
viewer.getTree().setLinesVisible(true);
viewer.setContentProvider(new ITreeContentProvider () {
#Override
public void dispose() {
// TODO Auto-generated method stub
}
#Override
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
// TODO Auto-generated method stub
}
#Override
public Object[] getChildren(Object arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public Object[] getElements(Object arg0) {
// TODO Auto-generated method stub
return new String[]{"Hoshe","Irani"};
}
#Override
public Object getParent(Object arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean hasChildren(Object arg0) {
// TODO Auto-generated method stub
return false;
}
});
viewer.setLabelProvider(new ILabelProvider(){
#Override
public void addListener(ILabelProviderListener arg0) {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
#Override
public boolean isLabelProperty(Object arg0, String arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void removeListener(ILabelProviderListener arg0) {
// TODO Auto-generated method stub
}
#Override
public Image getImage(Object arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public String getText(Object arg0) {
// TODO Auto-generated method stub
return "hoshe";
}
});
viewer.setInput("Hoshe");
Menu popupMenu = new Menu(viewer.getControl());
MenuItem newItem = new MenuItem(popupMenu, SWT.CHECK);
newItem.setText("New");
MenuItem refreshItem = new MenuItem(popupMenu, SWT.CHECK);
refreshItem.setText("Refresh");
MenuItem deleteItem = new MenuItem(popupMenu, SWT.CHECK);
deleteItem.setText("Delete");
popupMenu.addMenuListener(new MenuListener() {
#Override
public void menuShown(MenuEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void menuHidden(MenuEvent arg0) {
// TODO Auto-generated method stub
display.asyncExec(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
TreeItem [] arr = viewer.getTree().getSelection();
for(MenuItem item2 : popupMenu.getItems()){
boolean bool1 = item2.getSelection();
if(bool1){
arr[0].setText(item2.getText());
item2.setSelection(false);
}
}
}
});
}
});
viewer.getTree().setMenu(popupMenu);
shell.open();
while(!shell.isDisposed()){
if(!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
I struggle with Editor framework of gwt. Mostly because the documentation is lame- no hurt feelings- just saying.
Now I have problem that I cannot execute button event on editor. This is my error:
Uncaught com.google.gwt.event.shared.UmbrellaException: Exception caught: (TypeError) : Cannot read property 'onLoginButtonClick_3_g$' of undefined
I am not sure what I am doing wrong. I didn't found any good example of that. I hope someone will help.
Here is my code:
Editor
public class LoginEditor extends ViewWithUiHandlers<LoginEditorUiHandlers> implements Editor<LoginModel> {
private VerticalPanel widget = new VerticalPanel();
MaterialTextBox email = new MaterialTextBox();
MaterialTextBox password = new MaterialTextBox();
MaterialButton btnLogin = new MaterialButton();
public LoginEditor() {
initWidget(widget);
email.setPlaceholder("E-mail");
password.setPlaceholder("Password");
btnLogin.setText("Login");
btnLogin.addClickHandler(new ClickHandler() {
#Override public void onClick(ClickEvent event) {
onLoginButtonClick(event);
}
});
widget.add(email);
widget.add(password);
widget.add(btnLogin);
}
void onLoginButtonClick(ClickEvent e){
getUiHandlers().onLoginButtonClick();
Window.alert("TEST");
}
}
Presenter
public class LoginPresenter extends Presenter<LoginPresenter.MyView, LoginPresenter.MyProxy> implements LoginEditorUiHandlers {
public interface MyView extends View , HasUiHandlers<LoginEditorUiHandlers> {}
public static final Type<RevealContentHandler<?>> SLOT_Login = new Type<RevealContentHandler<?>>();
#ProxyStandard
#NameToken(NameTokens.login)
public interface MyProxy extends ProxyPlace<LoginPresenter> {}
// Editor
interface Driver extends SimpleBeanEditorDriver<LoginModel, LoginEditor> {}
private static final LoginService service = GWT.create(LoginService.class);
Driver editorDriver = GWT.create(Driver.class);
private LoginModel model = new LoginModel("email","pass");
private LoginEditor editor = new LoginEditor();
#Override
public void onLoginButtonClick() {
MaterialToast.fireToast("TEST");
try{
System.out.println(editorDriver == null);
System.out.println(editorDriver.isDirty());
editorDriver.isDirty();
} catch (NullPointerException e) {
MaterialToast.fireToast("Null: " + e.getLocalizedMessage());
}
if (editorDriver.isDirty()) {
model = editorDriver.flush();
if (editorDriver.hasErrors()) {
StringBuilder errorBuilder = new StringBuilder();
for (EditorError error : editorDriver.getErrors()) {
errorBuilder.append(error.getMessage() + "\n");
}
MaterialToast.fireToast(errorBuilder.toString());
} else {
service.login(
model, new MethodCallback<Integer>() {
#Override
public void onSuccess(Method method, Integer response) {
MaterialToast.fireToast("Succefully set info. status code: " + response);
}
#Override
public void onFailure(Method method, Throwable exception) {
MaterialToast.fireToast("Error setting");
}
});
}
} else {
MaterialToast.fireToast("Data has not changed");
}
}
#Inject
LoginPresenter(
EventBus eventBus,
MyView view,
MyProxy proxy) {
super(eventBus, view, proxy, RevealType.Root);
editorDriver.initialize(editor);
editorDriver.edit(model);
getView().setUiHandlers(this);
}
}
View
public class LoginView extends ViewWithUiHandlers<LoginEditorUiHandlers> implements LoginPresenter.MyView {
interface Binder extends UiBinder<Widget, LoginView> {
}
#Inject
LoginView(Binder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
}
}
View.ui.xml
<m:MaterialRow ui:field="loginWidget">
<m:MaterialColumn grid="s12 m4 l4" offset="l4" >
<m:MaterialTitle title="Login" description="Please provide your account credentials."/>
<m:MaterialPanel padding="5" shadow="1" addStyleNames="{style.panel}">
<m:MaterialPanel addStyleNames="{style.fieldPanel}">
<e:LoginEditor></e:LoginEditor>
</m:MaterialPanel>
</m:MaterialPanel>
</m:MaterialColumn>
</m:MaterialRow>
UiHandlers
interface LoginEditorUiHandlers extends UiHandlers {
void onLoginButtonClick();
}
interface LoginUiHandlers extends UiHandlers {
}
Here is working solution:
Presenter
package pl.korbeldaniel.cms.client.login;
import java.util.ArrayList;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import gwt.material.design.client.ui.MaterialToast;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import com.gwtplatform.mvp.client.HasUiHandlers;
import pl.korbeldaniel.cms.client.editor.BeanEditView;
import pl.korbeldaniel.cms.client.model.LoginModel;
import pl.korbeldaniel.cms.client.place.NameTokens;
import pl.korbeldaniel.cms.client.service.LoginService;
public class LoginPresenter extends Presenter<LoginPresenter.MyView, LoginPresenter.MyProxy> implements LoginUiHandlers {
public interface MyView extends BeanEditView<LoginModel>, HasUiHandlers<LoginUiHandlers> {}
public static final Type<RevealContentHandler<?>> SLOT_Login = new Type<RevealContentHandler<?>>();
#ProxyStandard
#NameToken(NameTokens.login)
public interface MyProxy extends ProxyPlace<LoginPresenter> {}
// Editor
private SimpleBeanEditorDriver<LoginModel, ?> editorDriver;
private static final LoginService service = GWT.create(LoginService.class);
private LoginModel model = new LoginModel("","");
#Override
public void onLoginButtonClick() {
String msg = "User Pressed a button.";
GWT.log(msg);
if (editorDriver.isDirty()) {
model = editorDriver.flush();
validateModel();
GWT.log(String.valueOf(editorDriver.hasErrors()));
if (editorDriver.hasErrors()) {
MaterialToast.fireToast("Errors occur");
StringBuilder errorBuilder = new StringBuilder();
for (EditorError error : editorDriver.getErrors()) {
GWT.log(error.getMessage());
errorBuilder.append(error.getMessage() + "\n");
}
//MaterialToast.fireToast(errorBuilder.toString());
RootPanel.get().add(new Label(errorBuilder.toString()));
} else {
service.login(
model, new MethodCallback<Integer>() {
#Override
public void onSuccess(Method method, Integer response) {
MaterialToast.fireToast("Succefully set info. status code: " + response);
}
#Override
public void onFailure(Method method, Throwable exception) {
MaterialToast.fireToast("Error setting");
}
});
}
} else {
MaterialToast.fireToast("Data has not changed");
}
}
private void validateModel() {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<LoginModel>> violations = validator.validate(model);
GWT.log(String.valueOf(violations.size()));
if (violations.size() > 0) {
editorDriver.setConstraintViolations(new ArrayList<ConstraintViolation<?>>(violations));
}
}
#Inject
LoginPresenter(EventBus eventBus,MyView view, MyProxy proxy) {
super(eventBus, view, proxy, RevealType.Root);
getView().setUiHandlers(this);
editorDriver = getView().createEditorDriver();
editorDriver.edit(model);
}
}
View/Editor
package pl.korbeldaniel.cms.client.login;
import gwt.material.design.client.ui.MaterialButton;
import gwt.material.design.client.ui.MaterialCheckBox;
import gwt.material.design.client.ui.MaterialTextBox;
import javax.inject.Inject;
import pl.korbeldaniel.cms.client.model.LoginModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
public class LoginView extends ViewWithUiHandlers<LoginUiHandlers> implements LoginPresenter.MyView {
interface Binder extends UiBinder<Widget, LoginView> {}
/** The driver to link the proxy bean with the view. */
public interface EditorDriver extends SimpleBeanEditorDriver<LoginModel, LoginView> { }
#UiField MaterialTextBox email;
#UiField MaterialTextBox password;
#UiField MaterialButton loginButton;
#UiField MaterialCheckBox keepMeLoggedInCheckbox;
#Inject
LoginView(Binder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
addClickHandlerToLoginButton();
}
//#UiHandler("loginButton")
private void onLoginButtonClick(ClickEvent e){
getUiHandlers().onLoginButtonClick();
}
private void addClickHandlerToLoginButton() {
loginButton.addClickHandler(new ClickHandler() {
#Override public void onClick(ClickEvent event) {
onLoginButtonClick(event);
}
});
}
#Override
public SimpleBeanEditorDriver<LoginModel, ?> createEditorDriver() {
EditorDriver driver = GWT.create(EditorDriver.class);
driver.initialize(this);
return driver;
}
}
ValidatorFactory
package pl.korbeldaniel.cms.client.login;
import javax.validation.Validator;
import pl.korbeldaniel.cms.client.model.LoginModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.validation.client.AbstractGwtValidatorFactory;
import com.google.gwt.validation.client.GwtValidation;
import com.google.gwt.validation.client.impl.AbstractGwtValidator;
public final class SampleValidatorFactory extends AbstractGwtValidatorFactory {
/**
* Validator marker for the Validation Sample project. Only the classes and
* groups listed in the {#link GwtValidation} annotation can be validated.
*/
#GwtValidation(LoginModel.class)
public interface GwtValidator extends Validator {
}
#Override
public AbstractGwtValidator createValidator() {
return GWT.create(GwtValidator.class);
}
}
UiHandlers
package pl.korbeldaniel.cms.client.login;
import com.gwtplatform.mvp.client.UiHandlers;
interface LoginUiHandlers extends UiHandlers {
void onLoginButtonClick();
}
Bean edit view interface
package pl.korbeldaniel.cms.client.editor;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.gwtplatform.mvp.client.View;
/**
* Implemented by views that edit beans.
*
* #param <B> the type of the bean
*/
public interface BeanEditView<B> extends View, Editor<B> {
/**
* #return a new {#link SimpleBeanEditorDriver} initialized to run this editor
*/
SimpleBeanEditorDriver<B, ?> createEditorDriver();
}
I hope it will help some one.
I need to start a javafx Application from another "container" class and call functions on the Application, but there doesn't seem to be any way of getting hold of a reference to the Application started using the Application.launch() method. Is this possible?
Thanks
Suppose this is our JavaFX class:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class OKButton extends Application {
#Override
public void start(Stage stage) {
Button btn = new Button("OK");
Scene scene = new Scene(btn, 200, 250);
stage.setTitle("OK");
stage.setScene(scene);
stage.show();
}
}
Then we may launch it from another class like this:
import javafx.application.Application;
public class Main {
public static void main(String[] args) {
Application.launch(OKButton.class, args);
}
}
I had the same problem as this and got round it using this hack:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.concurrent.CountDownLatch;
public class StartUpTest extends Application {
public static final CountDownLatch latch = new CountDownLatch(1);
public static StartUpTest startUpTest = null;
public static StartUpTest waitForStartUpTest() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return startUpTest;
}
public static void setStartUpTest(StartUpTest startUpTest0) {
startUpTest = startUpTest0;
latch.countDown();
}
public StartUpTest() {
setStartUpTest(this);
}
public void printSomething() {
System.out.println("You called a method on the application");
}
#Override
public void start(Stage stage) throws Exception {
BorderPane pane = new BorderPane();
Scene scene = new Scene(pane, 500, 500);
stage.setScene(scene);
Label label = new Label("Hello");
pane.setCenter(label);
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
and then the class you are launching the application from:
public class StartUpStartUpTest {
public static void main(String[] args) {
new Thread() {
#Override
public void run() {
javafx.application.Application.launch(StartUpTest.class);
}
}.start();
StartUpTest startUpTest = StartUpTest.waitForStartUpTest();
startUpTest.printSomething();
}
}
Hope that helps you.
Launch JavaFX in other Class using Button:
class Main extends Application{
public void start(Stage s)throws Exception{
event();
s.show();
}
public void event(){
btn.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent ae){
Stage s = new Stage();
new SubClassName().start(s);
}
});
}
public static void main(String[] args) {
launch(args);
}
}
class SubClassName{
public void start(Stage s){
Pane pane = new Pane();
Scene addFrame = new Scene(pane,280,450);
s.setScene(addFrame);
s.show();
}
}
I'm not sure what you're trying to achieve, but note that you can e.g call from another class Application.launch to start the JavaFX Application thread and Platform.exit to stop it.
The above ways of invoking other javafx class from another sometimes work. Struggling to find an ultimate way to do this brought me to the following walk around:
Suppose this is the javafx class that exteds Application we wish to show from a different class, then we should add the following lines
class ClassToCall extends Application{
//Create a class field of type Shape preferably static...
static Stage classStage = new Stage();
#Override
public void start(Stage primaryStage){
// Assign the class's stage object to
// the method's local Stage object:
classStage = primaryStage ;
// Here comes some more code that creates a nice GUI.....
// ......
}
}
And now from the other place in the project, in order to open the window
that the above class creates do the following:
// Suppose we want to do it with a button clicked:
btn1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
//create an object of the class you wish to invoke its
//start() method:
ClassToCall ctc = new ClassToCall();
// Then call its start() method in the following way:
ctc.start(ClassToCall.classStage);
}// End handle(ActionEvent event)
});// End anonymous class
I've been trying to import a very simple project I've started on a differnt laptop but for some reson the project now is full of errors.
Eclipse does not recognize imports being made and thus refuse to recognize simple classes as ActionBarActivity and methods like onCreate.
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Button bEnter=(Button) getActivity().findViewById(R.id.bEnter);
Button bSignup=(Button) getActivity().findViewById(R.id.bSignup);
bEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String toastText="It's Working!!!";
int toastDuration=Toast.LENGTH_SHORT;
Toast toast=Toast.makeText(getActivity(), toastText, toastDuration);
toast.show();
}
});
}
}
}
What am I missing here??
What errors are you getting ?
Trick1:
If the appcompat_v7 project(library) is causing the problem, remove it from the project properties, then perform the following steps.
1) Right click on the main.
2) Hover over Android Tools.
3) Click 'Add Support Library'.
It will download the required library and the clean the project. It should work.
if doesn't work, let me know.
Trick2: Update to the latest Revisions ( Tools and SDKs using SDK manager)
Happy Coding.
I am bran new to this but I have successfully created a functional button.
I am attempting to pass user input (editText1 on activity_main) to Recipe (my second activity) The first code is my functional button. What am I doing wrong in the second round of code in my attempt at passing information to be displayed on the second activity layout?
package com.example.andrew;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v){
startActivity(new Intent(MainActivity.this, Recipe.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Second round of code: My attempt at passing information. First activity
package com.example.andrew;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Edit Text et = (Edit Text) findViewById(R.id.editText1);
String theText = et.getText().toString();
Intent i = new Intent(this, Recipe.class);//Recipe is my second class
i.putExtra("text_label", theText);//what is "text_label"? Where should it be?
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v){
startActivity(new Intent(MainActivity.this, Recipe.class));
}
});
}
}
And in my second activity I have:
public class Recipe extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe_layout);
Intent i = getIntent();
uriStringi = i.getStringExtra("text_label");//is text_label on actv. 1?
startActivity(i);
}
You are adding data in the intent but while starting the activity you are not using it. Instead creating new intent.
Solution:
In your current Activity, create a new Intent:
Intent i = new Intent(this, Recipe.class);
i.putExtra("text_label", theText);
startActivity(i); // Write this in onClick()
Then in the Recipe, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("text_label");
}