How do I start another activity when a button defined in main.xml is clicked

Go To StackoverFlow.com

0

I have two classes. One is Main and the other is HelloWorld. When I click a button which is defined in main.xml I want it to display a message defined in HelloWorld class to start. When i click the button it does not do anything.Code is given below. If anything else is required to put up let me know. Thanks

Main.java

public class Main extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView map;
long start;
long stop;
int x, y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat ;
int longi; 





@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button orderButton = (Button)findViewById(R.id.button1);

    orderButton.setOnClickListener(new View.OnClickListener() {

      public void onClick(View view) {
        Intent intent = new Intent(Main.this, HelloWorld.class);
        startActivity(intent);
      };
    });

    map = (MapView)findViewById(R.id.mv);
    map.setBuiltInZoomControls(true);

    Touchy t = new Touchy();
    overlayList = map.getOverlays();
    overlayList.add(t);



    d = getResources().getDrawable(R.drawable.pinn);



    //Placing pintpoint
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();

    towers = lm.getBestProvider(crit, false);
    Location location = lm.getLastKnownLocation(towers);

    if (location != null){
        lat = (int) (location.getLatitude() *1E6);
        longi= (int) (location.getLongitude() *1E6);



        GeoPoint ourLocation = new GeoPoint(lat,longi);
        OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
        CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
        custom.insertPinpoint(overlayItem);
        overlayList.add(custom);
    }else{
       Toast.makeText(Main.this, "Couldnt get provider", Toast.LENGTH_SHORT).show();
    }





}

@Override
protected void onPause() {
    // TODO Auto-generated method stub

    super.onPause();
    lm.removeUpdates(this);
}


     @Override
protected void onResume() {
    // TODO Auto-generated method stub

    super.onResume();
    lm.requestLocationUpdates(towers, 500, 1, this );
}


    @Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}



class Touchy extends Overlay{
    public boolean onTouchEvent(MotionEvent e, MapView m){
    if (e.getAction() == MotionEvent.ACTION_DOWN){
        start = e.getEventTime();

    }
    if (e.getAction() == MotionEvent.ACTION_UP){
        stop = e.getEventTime();
        x = (int) e.getX();
        y = (int) e.getY();
        touchedPoint = map.getProjection().fromPixels(x, y);

    }
    if (stop - start > 1500){
        AlertDialog alert = new AlertDialog.Builder(Main.this).create();
        alert.setTitle("Pick Option");


        alert.setButton("Hello", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

    OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
        CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
                custom.insertPinpoint(overlayItem);
                overlayList.add(custom);



        }
        });
    alert.setButton3("Get Address", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
    Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
    try{
    List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() /      1E6, touchedPoint.getLongitudeE6() / 1E6 , 1);
                if (address.size() > 0){
                    String display = "";
        for (int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){

                display += address.get(0).getAddressLine(i) + "\n";
                    }
    Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
                    t.show();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
            }
        }});
    alert.setButton2("Toggle View", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                if (map.isSatellite()){
                    map.setSatellite(false);
                    map.setStreetView(true);
                }else{
                    map.setStreetView(false);
                    map.setSatellite(true);
                }
            }
});


    alert.setButton("Place a Pin", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

    OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
           CustomPinPoint custom = new CustomPinPoint(d,Main.this); 
                custom.insertPinpoint(overlayItem);
                overlayList.add(custom);

            }


        });
        alert.show();
        return true;
    }

        return false;
    }

}



public void onLocationChanged(Location l) {
    // TODO Auto-generated method stub
    lat = (int) (l.getLatitude() *1E6);
    longi = (int) (l.getLongitude() *1E6);
    GeoPoint ourLocation = new GeoPoint(lat,longi);
    OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
    CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
    custom.insertPinpoint(overlayItem);
    overlayList.add(custom);

}




public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}




public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}




public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

    }

HelloWorld.java

import com.google.android.maps.OverlayItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class HelloWorld extends Activity
{

        protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v)
            {
                Toast.makeText(HelloWorld.this, "you clicked on button![enter image description here][3]", Toast.LENGTH_LONG).show();
            }
});

} }

I have also written

  <activity android:name=".HelloWorld" /> 

in my manifest

2012-04-04 07:59
by Mehul Rastogi
post your error log - Padma Kumar 2012-04-04 08:04


0

simple way

inlude android:onClick="onClickMyButton" as a attribute of Button in main.xml

remove onClickListener from this Button

now define this mathod in your Main Activity

public void onClickMyButton(View view){

Intent intent = new Intent(Main.this, HelloWorld.class);
        startActivity(intent);


}

now start your application it should work fine

2012-04-12 12:04
by Ravi1187342


2

Your second activity HelloWorld doesn't have set a content view so it doesn't find the Button and you throw a NullPointerException. You have to set a contentView with setContentView containing the Button with the id R.id.button1 like you did in the MainActivity.

Your HelloWorld activity:

public class HelloWorld<AlertDialogActivity> extends Activity{

             protected void onCreate(Bundle icicle) {
             super.onCreate(icicle);
             setContentView(R.layout.layout_hello);

             final Button button = (Button) findViewById(R.id.button1);
             button.setOnClickListener(new View.OnClickListener() {
                 public void onClick(View view) {
      Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
                 }
             });
    }
}

Where R.layout.layout_hello represents a xml file in the res/layout folder (named layout_hello.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button1" />
</LinearLayout>

It's the same thing like you did in the MainActivity.

2012-04-04 08:05
by Luksprog
I have created a button in main.xml so when i click that button the HelloWorld activity should work. how do i do this. sorry to bother you - Mehul Rastogi 2012-04-04 10:13
@MehulRastogi I've edited my answer - Luksprog 2012-04-04 10:24
Thank you so much! - Mehul Rastogi 2012-04-04 10:29
Bro i think you didn't get what I am trying to say. See I made a button in the main.xml so when I click this button my HelloWorld activity should start. cos I tried what you said. Not working - Mehul Rastogi 2012-04-04 11:11
@MehulRastogi If you don't have a content view in the second activity HelloWorld then the app will Force Close. Also the name of your second class should be HelloWorld without the generic parameter <AlertDialogActivity>, like this public class HelloWorld extends Activity. If this doesn't work please post the exception you get in the Logcat - Luksprog 2012-04-04 11:36
04-04 17:10:34.583: E/MapActivity(312): Couldn't get connection factory clien - Mehul Rastogi 2012-04-04 11:41
@MehulRastogi That seems to be an error related to the MapActivity. I don't know what could be causing that but there are some questions about this issue, at a quick search I found http://stackoverflow.com/questions/5848544/couldnt-get-connection-factory-client and http://stackoverflow.com/questions/2199403/couldnt-get-connection-factory-client but there are more - Luksprog 2012-04-04 11:49
Now when i click the button nothing happens. sorry i know i might be irritating you. - Mehul Rastogi 2012-04-04 12:03
@MehulRastogi Just to be clear: Right now you have the Main activity with a Button(this is working well?!). When you press the Button from Main you want to open HelloWorld(this gave you a Force Close but now you solved that exception? Do you get other exceptions?). Nothing happens when you click the button meaning what?(Do you get a blank screen(if yes add a content view to the activity HelloWorld like in my answer) - Luksprog 2012-04-04 12:21
I have a Main activity which has a button defined in main.xml I have another activity named HelloWorld which just displays a message as shown in my code above. What i am trying is when i click the button defined in main.xml the HelloWorld activity should start. By nothing happens i mean is no blank screen no force close. But i can run other things in the ap - Mehul Rastogi 2012-04-04 12:34
@MehulRastogi Sorry but I can't see what you're doing wrong. Edit your question and add more details. If you solved the Couldn't get connection factory client error and added a layout to HelloWorld activity, when you click the button from HelloWorld the toast should appear - Luksprog 2012-04-04 12:56


0

Why did you comment that line? //setContentView(R.layout.content_layout_id);

The activity is looking for the button R.id.button1 is a null view.

2012-04-04 08:06
by Manitoba


0

ya you must need to use setContentView()

un comment that code and try again

2012-04-04 09:36
by MAC
Ads