Monday, June 6, 2011

Flickr api, random image example

Introduction

SDK Version:  M3
Lately we have been doing all kinds of demo projects, and tests, where we did not want to use constant data to present our products. Having a demo of your application is only nice, if it has relevant data in it. It could be top class technology, but if it is using the same image 20 times in a list, well that does not look very good.
SDK Version:  M3

Lately we have been doing all kinds of demo projects, and tests, where we did not want to use constant data to present our products. Having a demo of your application is only nice, if it has relevant data in it. It could be top class technology, but if it is using the same image 20 times in a list, well that does not look very good.

flickr_logo


Using the Flickr API

The Flickr api has a lot of useful methods, but I only needed one, which is search. I choose the json response, because that's the easiest to work with. It has support for several other protocols/formats.
One problem that I encountered is, that the flickr api does not send a valid json response:

1
2
3
4
jsonFlickrApi({"photos":{"page":1, "pages":73442, "perpage":1, 
"total":"73442", "photo":[{"id":"5138524515", "owner":"12766047@N06", 
"secret":"e000d9791e", "server":"4045", "farm":5, "title":"Gifts under $15 CAD",
"ispublic":1, "isfriend":0, "isfamily":0}]}, "stat":"ok"})

As you can see, it has some junk at the beginning "jsonFlickrApi(" and at the end ")" which needs to be cut off.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//you also need your own api key
private static final String FLICKRAPIKEY = "http://www.flickr.com/services/api/keys/ INSERT YOUR OWN API KEY";
 
private String flickrApi(String searchPattern, int limit) throws IOException, JSONException {
        URL url = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&text=" + searchPattern + "&api_key=" + FLICKRAPIKEY + "&per_page="+ limit + "&format=json");
        URLConnection connection = url.openConnection();
        String line;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
        while ((line = reader.readLine()) != null) {
                builder.append(line);
        }
 
        Log.d("not good",builder.toString());
        //no, this is not yet a valid json response :)
 
        int start = builder.toString().indexOf("(") + 1;
        int end = builder.toString().length() - 1;
        String jSONString = builder.toString().substring( start, end);
        //after cutting off the junk, its ok
 
        JSONObject jSONObject = new JSONObject(jSONString); //whole json object
        JSONObject jSONObjectInner = jSONObject.getJSONObject("photos"); //inner Json object
        JSONArray photoArray = jSONObjectInner.getJSONArray("photo"); // inner array of photos
        JSONObject photo = photoArray.getJSONObject((int) (limit*Math.random())); //get one random photo from array
 
        return constructFlickrImgUrl(photo, size._t);
}
 
// source: flickr.com/services/api/misc.urls.html
enum size {
        _s , _t ,_m
};
 
//helper method, to construct the url from the json object. You can define the size of the image that you want, with the size parameter. 
Be aware that not all images on flickr are available in all sizes.
private String constructFlickrImgUrl(JSONObject input, Enum size) throws JSONException {
        String FARMID = input.getString("farm");
        String SERVERID = input.getString("server");
        String SECRET = input.getString("secret");
        String ID = input.getString("id");
 
        StringBuilder sb = new StringBuilder();
 
        sb.append("http://farm");
        sb.append(FARMID);
        sb.append(".static.flickr.com/");
        sb.append(SERVERID);
        sb.append("/");
        sb.append(ID);
        sb.append("_");
        sb.append(SECRET);
        sb.append(size.toString());                    
        sb.append(".jpg");
 
        return sb.toString();
}
 
/**
 * Word randomizer for fun
 * @param length
 * @return
 */
private String randomizer(int length){
        char i[] = new char[length];
        for (int j = 0; j < length; j++) {
                i[j] =(char)((int)5*Math.random()+(int)'a');
        }
        return new String(i);
}
 
//Usage:
flickrApi(randomizer(3) , 1));

Facebook Integration in your Android Application

Introduction

The goal of this article is to get Facebook integration up & running from your Android app in 30 minutes. The guide will show you how to
setup a Faceook test account
register a Facebook application
authenticate the user in your Android application.
have the user update his Facebook wall from your Android application.
This guide is accompanied  by a sample application that’s available in Github in the AndroidFacebookSample repository. To import this project in Eclipse, I suggest using the EGit plugin that can be installed via the Main P2 Repository located at http://download.eclipse.org/egit/updates.
Before running this project, make sure you change the com.ecs.android.facebook.Sample.AndroidFacebookSample file to include your Facebook API key (see subsequent section).
Once you have sample application up & running, you can copy the relevant classes into your projects to have Facebook up & running from your Android application.
First things first … In order to integrate with Facebook, you need 2 things:
A Facebook test account, used in our Android application to login to Facebook and make status updates.
A Facebook application, used to inform the user in your Android application that this application is requesting you to login to Facebook.
The goal of this article is to get Facebook integration up & running from your Android app in 30 minutes. The guide will show you how to
  • setup a Faceook test account.
  • register a Facebook application.
  • authenticate the user in your Android application.
  • have the user update his Facebook wall from your Android application.
integrate_facebook_android_app_01

This guide is accompanied  by a sample application that’s available in Github in the AndroidFacebookSample repository. To import this project in Eclipse, I suggest using the EGit plugin that can be installed via the Main P2 Repository located at http://download.eclipse.org/egit/updates.

Before running this project, make sure you change the com.ecs.android.facebook.Sample.AndroidFacebookSample file to include your Facebook API key (see subsequent section). Once you have sample application up & running, you can copy the relevant classes into your projects to have Facebook up & running from your Android application.

First things first … In order to integrate with Facebook, you need 2 things:
  • A Facebook test account, used in our Android application to login to Facebook and make status updates.
  • A Facebook application, used to inform the user in your Android application that this application is requesting you to login to Facebook.


Facebook Test Account

We’ll start by creating a test account that we’ll use in our Android application. Signup for a new user account at Facebook. If you already have an account, sign up for a new account using your existing name but specify a different email address. Once the account has been created, we’ll convert it into a Facebook test account.

Note: The following step should not be done on your real facebook account. Converting an existing Facebook account into a test account is irreversible, so please ensure that you do the following step with your newly created “dummy” account.

When logged into Facebook, goto the Facebook Become Test Account page  to convert your newly created account into a Facebook test account. Again, do not execute these steps on your “real” user account.

integrate_facebook_android_app_02

After confirming that you want to convert your account into a test account, you should see the following message:

integrate_facebook_android_app_03



Facebook Application

Next step is to create a Facebook application. Integration with facebook is based on OAuth 2.0 and requires your to register a Facebook application. Visit the Facebook Developers Authentication page for more information on its OAuth 2.0 implementation.

The Facebook application that we’ll create will have it’s own Application ID that we’ll use in our Android application.

Creating an application cannot be done on the Facebook test account, so you’ll need to have a proper Facebook account in order to create the application. Using your “real” Facebook account, goto the Facebook Create Application page  and create your application.

integrate_facebook_android_app_04

Give it a name, and complete the registration. You should land on a page like this:

integrate_facebook_android_app_05

So far so good, everything is setup on the Facebook front, now it’s time to start coding our Android application.

On the Android front, we’ll use the Facebook Android SDK located at Github: https://github.com/facebook/facebook-android-sdk.

The Facebook Android SDK is licensed under the Apache License and is completely open source.

integrate_facebook_android_app_06

The project contains several samples in the examples folder, but the core SDK is located in the facebook folder. The sample application included in the facebook sdk repository provides the user the ability to post a message on the wall using a custom dialog, allowing the user to enter some text. The goal of the sample application that we’ll be creating here is to send an automated message to the wall, without any human interaction. Our application will generate a piece of text and post it on the wall without showing a dialog to the user. The user simply presses a button, and the generated message will appear on his/her wall.

But to get started, we’ll begin by importing the facebook project (containing the actual facebook sdk) into Eclipse. Once this is done, you should have the following Eclipse Project in your workspace:

integrate_facebook_android_app_07

As this is the library project that our sample application will use to do the actual  Facebook integration, we’ll  need to create a reference in our own project to this Facebook Android SDK project. This is done by going to our project properties, select Android on the left, go to the library section and click Add.

integrate_facebook_android_app_08

On the following screen, you can select the Facebook Android SDK library project

integrate_facebook_android_app_09

When selected, it will be made available to your own project.

integrate_facebook_android_app_10

As you can see in the Eclipse Package explorer, our sample project now also contains a reference to the Facebook Android SDK project

integrate_facebook_android_app_11

The Facebook SDK project revolves around a central com.facebook.android.Facebook.Facebook class, allowing you to perform various calls to Facebook.  It provides basic login/logoff functionality (by leveraging single sign on capabilities if you have the official facebook app installed), handles the OAuth integration, and provides you with a generic API to perform requests to the various Facebook APIs.

In our own sample application
, we’ll encapsulate all the Facebook interactions in a FacebookConnector object. The object is constructed like this:

1
2
3
4
5
6
7
8
9
10
11
12
public FacebookConnector(String appId,Activity activity,Context context,String[] permissions) {
 this.facebook = new Facebook(appId);
 
 SessionStore.restore(facebook, context);
       SessionEvents.addAuthListener(mSessionListener);
       SessionEvents.addLogoutListener(mSessionListener);
 
 this.context=context;
 this.permissions=permissions;
 this.mHandler = new Handler();
 this.activity=activity;
}

As you can, under the hook, our FacebookConnector class uses the Facebook class provided by the Facebook SDK project.

Our FacebookConnector will provide a more coarse-grained API than the Facebook class. The Facebook class is designed in a very generic way, allowing you to do a lot of different calls to Facebook. This design results in a fairly fine-grained API, where some knowledge is expected from the application using this API. For example, you’ll need to know the specific endpoints for post a message on a wall, or to retrieve a user profile. In addition to that, you’ll also need to know what parameters you need to send for each request.

Our FacebookConnector exposes a coarse-grained method called postMessageOnWall that’s the main logic behind our Post button. The only thing we need to provide is the actual message we want to post. The FacebookConnector will do the necessary plumbing towards the more generic Facebook class.

The postMessageOnWall method checks if we have a valid Facebook session (meaning we have authenticated properly against Facebook). If this is the case, it setups up the necessary parameters, and does a call through the Facebook class to post a message on the wall. (using the me/feed endpoint)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void postMessageOnWall(String msg) {
 if (facebook.isSessionValid()) {
     Bundle parameters = new Bundle();
     parameters.putString("message", msg);
     try {
   String response = facebook.request("me/feed", parameters,"POST");
   System.out.println(response);
  } catch (IOException e) {
   e.printStackTrace();
  }
 } else {
  login();
 }
}

But we’ll start by explaining what happens if the user doesn’t have a valid Facebook session.

If the user hasn’t authenticated to Facebook yet we need to perform a login. The login() is defined like this:

1
2
3
4
5
public void login() {
       if (!facebook.isSessionValid()) {
           facebook.authorize(this.activity, this.permissions,Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
       }
   }

The login method is implemented in such a way that when we don’t have a logged in user, we call the facebook.authorize to start the Facebook OAuth flow. Although the Facebook SDK has a single-sign-on option, allowing you to leverage your existing facebook session you may have with the official Facebook Android application, we’ll add the Facebook.FORCE_DIALOG_AUTH parameter to have the Facebook SDK pop the login dialog.

The first thing that will happen when executing this method, is that the Facebook login dialog will be shown. Notice how the login dialog mentions the Facebook app we created earlier. By passing on our Application ID to the Facebook object, the user is now informed that the TestAndroidIntegration application is initiating the Facebook login. The user can decide at this point if he wants to login to his Facebook account.

integrate_facebook_android_app_12

When the user does a login, he’ll be presented with yet another dialog. Keep in mind that at this point, although the user is logged in, he didn’t give any permissions yet for this application to post messages on his wall. This particular dialog will now request the user for certain permission.

It basically allows the user to authorize the TestAndroidIntegration application to access basic information and Post to my Wall.  Accessing basic information is the default permission that is given when a user logs in this way. Here, an additional permission is requested (Post to my Wall).

In order to post something on the wall, the publish_stream permission is required, hence we pass this on to our FacebookConnector:

1
2
3
4
private static final String FACEBOOK_APPID = "PUT YOUR FACEBOOK APPID HERE";
private static final String FACEBOOK_PERMISSION = "publish_stream";
 
facebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});

Note: ensure that you provide a proper Facebook APPID here.

integrate_facebook_android_app_13

When the user allows this request for permission (authorization), the Facebook API can begin executing requests on behalf of the user (like posting something on his wall).



Posting a message on the Facebook wall

In order to post a message on the wall, we basically construct a message (Bundle) that we pass on to the facebook request method. We use the “me/feed” ID on the Facebook Graph API to indicate that we’ll be posting something to the Profile feed (Wall in Facebook terminlogy).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private FacebookConnector facebookConnector;
 
private void postMessageInThread() {
 Thread t = new Thread() {
  public void run() {
 
      try {
       facebookConnector.postMessageOnWall(getFacebookMsg());
    mFacebookHandler.post(mUpdateFacebookNotification);
   } catch (Exception ex) {
    Log.e(TAG, "Error sending msg",ex);
   }
     }
 };
 t.start();
}

The postMethodOnWall() method is called from our main Activity in a background thread. Although we don’t want to interrupt the main UI thread while posting the message (hence the background thread), we do want to send a notification to the user that his message was posted. We use a handler for this in order to show a Toast message on the main UI thread once the background processing has been done.

1
2
3
4
5
6
7
private FacebookConnector facebookConnector;
 
   final Runnable mUpdateFacebookNotification = new Runnable() {
       public void run() {
        Toast.makeText(getBaseContext(), "Facebook updated !", Toast.LENGTH_LONG).show();
       }
   };

An importing thing to note is that when the user clicks the Post Message button, besides logging just logging in, we also want to send the message to the Facebook wall. Performing the login, immediately followed by an action (in this case sending a message) can be done by adding a AuthenticationListener (SessionEvents.AuthListener) to the SessionEvents.

The following code (wrapper method) illustrates this :
  • in case of logged in user simply post the message in the background thread.
  • in case of an anonymous user, we wait for the authentication to succeed, and then continue on to posting the message in the background thread.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void postMessage() {
 if (facebookConnector.getFacebook().isSessionValid()) {
  postMessageInThread();
 } else {
  SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {
 
   @Override
   public void onAuthSucceed() {
    postMessageInThread();
   }
 
   @Override
   public void onAuthFail(String error) {
 
   }
  };
  SessionEvents.addAuthListener(listener);
  facebookConnector.login();
 }
}

The clearCredentials() method is responsible for logoff functionality. All credentials are cleared from the system, and each interaction with Facebook will again trigger a login().

1
2
3
4
5
6
7
8
9
private void clearCredentials() {
 try {
  facebookConnector.getFacebook().logout(getApplicationContext());
 } catch (MalformedURLException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }
}

Wednesday, April 13, 2011

Adding PayPal payment in Android Application

Hi everyone

We all know PayPal is mostly using for transaction in recent days. The following is explain you how to add PayPal payment from your android application

Ready to get started with a simple payment? These steps will walk you through integrating the PayPal library and submitting it to x.com
Step 1 – Set up your sandbox accounts if you haven't already. You can create sandbox accounts by going to developer.paypal.com.
Step 2 – Add the PayPal library (a .jar file) into your Eclipse project, and then add the jar file to the build path. You can right click on the jar file to do this.
Step 3 – Update the AndroidManifest. The manifest will need to include the new activity "com.paypal.android.MEP.PayPalActivity". It will also need to declare the two permissions for Internet and Read-Phone-State.

Code:



<activity android:name="com.paypal.android.MEP.PayPalActivity"

 android:theme="@android:style/Theme.Translucent.NoTitleBar"

 android:configChanges="keyboardHidden|orientation/>

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>




Step 4 – Import the classes. Open the java file where you are adding the PayPal functionality. You will need to declare the various PayPal classes to use in your project.
Import com.paypal.android.CheckoutButton

Code:



import com.paypal.android.MEP.PayPal;

import com.paypal.android.MEP.PayPalActivity;

import com.paypal.android.MEP.PayPalPayment;

import com.paypal.android.MEP.PayPalAdvancedPayment;

import com.paypal.android.MEP.PayPalInvoiceData;

import com.paypal.android.MEP.PayPalInvoiceItem;

import com.paypal.android.MEP.PayPalReceiverDetails;




Step 5 – Initialize the library by using the initWithAppId method. You'll pass in your App ID and the environment. The environment can either point to Live, Sandbox, or None. The "None" environment puts the library in a demo mode which makes no server calls so that you can continue coding even if you don't have a connection. You can also set the language here.

Code:

PayPal pp = PayPal.initWithAppID(this, "APP-80W284485P519543T", PayPal.ENV_SANDBOX); 




Step 6 – Place a PayPal button on the screen. You can choose from several different button sizes in the integration guide. You'll also pass the type of payment (hard goods, service, donation, personal payment). Then set the onClick listener for the button.
Code:



LinearLayout layoutSimplePayment = new LinearLayout(this);

layoutSimplePayment.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,

    LayoutParams.WRAP_CONTENT));

layoutSimplePayment.setOrientation(LinearLayout.VERTICAL);

CheckoutButton launchSimplePayment = pp.getCheckoutButton(this, PayPal.BUTTON_194x37, CheckoutButton.TEXT_PAY);

launchSimplePayment.setOnClickListener(this);

layoutSimplePayment.addView(launchSimplePayment);

content.addView(layoutSimplePayment);



Step 7 – Implement the onClick function. This is where the actual checkout call happens. You'll specify all of the payment parameters (amount, currency, tax, shipping, recipient's email). You can also use some optional methods to recalculate the amount based on an address. You'll then create a new intent based on the PayPalActivity class and add the payment you just created.
Code:


Public void onClick (View v) {

PayPalPayment payment = new PayPalPayment();

payment.setSubtotal(new BigDecimal("8.25"));

payment.setCurrencyType("USD");

payment.setRecipient("bike-store-sandbox@gmail.com");

payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);

Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);

startActivityForResult(checkoutIntent, 1);




Step 8 – Handle the response. You will receive the results through the onActivityResult method. It will either return OK, Cancelled, or Failure based on how the payment ended. When you receive these calls, you can continue in your app by thanking the buyer or asking them to try later.

Code:


@Override

public void onActivityResults(int requestCode, int resultCode, Intent data) {

   switch(resultCode) {

      case Activity.RESULT_OK:

          break;

       case Activity.RESULT_CANCELED:

           break;

       case PayPalActivity.RESULT_FAILURE:

  }

}



Step 9 – Complete your project. Once you've finished your application, you can submit it to x.com (under the "My Apps" tab). In order for us to test it, you will need to attach a .zip file containing your .apk. PayPal will review the app in 1 business day (for apps using simple payments) and send you a valid App ID for the live environment. You"ll just need to update init method to point to Live with this new ID. (Don't forget to update the recipient to your live email address).



To read more click Here

Monday, February 7, 2011

Android: How to switch between Activities

I had trouble adjusting to what an “Activity” was and how to handle it. Here is a quick and dirty way to create an Activity, and to switch to another Activity (think of it as another screen) on the click of a button.
1. Create a new Android project – or you might already have one created.
01 new project
2. Add a new Class that extends android.app.Activity. You need a total of two classes that extend Activity. You will switch from one Activity to another.
02 new class
03 new class 2
3. Now, we’ll create two XML files to store the layout of each Activity. Under the res/layouts directory create a copy of main.xml
04 xml files
4. Each XML file will contain 1 button. On the click of the button, the Activities will switch.
main.xml will contain:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"  >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:text="This is Activity 1" />

       <Button android:text="Next"
        android:id="@+id/Button01"
        android:layout_width="250px"
            android:textSize="18px"
        android:layout_height="55px">
    </Button>    

</LinearLayout>
main2.xml will contain:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"  >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:text="This is Activity 2" />

       <Button android:text="Previous"
        android:id="@+id/Button02"
        android:layout_width="250px"
            android:textSize="18px"
        android:layout_height="55px">
    </Button>    

</LinearLayout>
So each Activity will have a text that says “This is Activity x” and
a button to switch the Activity.
5. Add the second Activity to the main manifest file. Open AndroidManifest.xml and add:
<activity android:name=".Activity2"></activity>
The final result will look similar to this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.warriorpoint.taxman2"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Activity1"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Activity2"></activity>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>
If you forget to do this, then the you will get a Null Pointer exception because “Activity2” will not be found at runtime. It took me some time to find out how to find what Exception was getting thrown as well. I will include how to debug and look at Exceptions in another future post.
5. Open Activity1.java and enter the following code:
package com.warriorpoint.taxman2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity1 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button next = (Button) findViewById(R.id.Button01);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), Activity2.class);
                startActivityForResult(myIntent, 0);
            }

        });
    }
}
Here’s a quick explanation of what this does:
- setContentView(R.layout.main) makes sure that main.xml is used as the layout for this Activity.
- Gets a reference to the button with ID Button01 on the layout using (Button) findViewById(R.id.Button01).
- Create san OnClick listener for the button – a quick and dirty way.
- And the most important part, creates an “Intent” to start another Activity. The intent needs two parameters: a context and the name of the Activity that we want to start (Activity2.class)
- Finally, the Activity is started with a code of “0”. The “0” is your own code for whatever you want it to mean. Activity2 will get a chance to read this code and use it. startActivityForResult means that Activity1 can expect info back from Activity2. The result from Activity2 will be gathered in a separate method which I will not include here.
6. Open Activity2.java and enter the code below:
package com.warriorpoint.taxman2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity2 extends Activity {

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        Button next = (Button) findViewById(R.id.Button02);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

        });
    }
This code does the following:
- Sets main2 as the layout for this Activity
- Gets a reference to Button02 and creates an OnClick listener
- In the OnClick listener, the Activity finishes with finish(). setResult() returns information back to Activity 1. In this example, it returns no information; and Activity1 doesn’t even have the listener to receive this information anyway.
That’s it! Run it!
05 run
The app will load in Activity 1:
06 activity 1
When you click the button you will see Activity 2. There are no animations, no tweens, etc, so the screen will just “change”. I’ll talk about animations in future posts.
07 activity 2
And clicking on the button “Previous” here will go back to Activity1.

Thursday, January 20, 2011

Creating a jar File in Eclipse


To create a new JAR file in the workbench:
  1. Either from the context menu or from the menu bar's File menu, select Export.



     
  2. Expand the Java node and select JAR file. Click Next.



     
  3. In the JAR File Specification page, select the resources that you want to export in the Select the resources to export field.




     
  4. Select the appropriate checkbox to specify whether you want to Export generated class files and resources or Export Java source files and resources(Note: Selected resources are exported in both cases.

    IMPORTANT: In this example the project keeps the source code in a folder named src. Your project may have a different set up. Be sure you expand the tree to show the default package and that the .java files are checked on the right. Alternatively deselect the option that says Export generated class files and resources and select the option that says Export Java source files and resources. For CS307 we want the .java files. We do not want or need the .class files. If you do not turn in your source files, the .java files, your assignment grade will be 0.



    If there are other files or resources you want to include they must be in a an open project. Browse to their location via the directory tree on the left and ensure the file or resource is checked in the window on the right. In the example below we are including a file named  OtherFile.txt which is located in the A3 directory.



     
  5. In the Select the export destination field, either type or click Browse to select a location for the JAR file.






     
  6. Select or clear the Compress the contents of the JAR file checkbox. (This option is unimportant for CS307.)
  7. Select or clear the Overwrite existing files without warning checkbox. If you clear this checkbox, then you will be prompted to confirm the replacement of each file that will be overwritten. (This option is unimportant for CS307.)
  8. You have two options:
  9. Now, navigate to the location you specified for the jar. The icon you see and the behavior you get if you double click it will vary depending on how your computer is set up.



    One easy way of checking if the jar has the correct files is to rename it with a .zip extension. Then use whatever you zip program is to look at the files inside. (This may not work depending on how your system is set up.)

    Rename to .zip extension:



    Open up with zip program / utility.



    In the above image you can see that A3.jar (renamed to A3.zip) contains 2 files MathMatrix.java and MathMatrixTester.java. Realize you may have multiple copies of those files on your computer. You can unzip the file (in a location different from where the files were originally located!!) and open the .java files to ensure they are correct or compare the size of the files to the size of the originals. Alternatively you can unjar the jar file, again in a different location that the original .java files, and check the files.

    If you changed the extension to .zip you must change it back to .jar before submitting your file via turnin.