Friday 8 May 2015

Numerical Analysis Gauss Seidal

Gauss Seidal

#include<stdio.h>
#include<conio.h>
#include<math.h>

void main(void)
{
   double x1 = 1, x2 = 0, x3 = 1;
   double e1, e2, e3;
   double a, b, c, x, y, z;
   int iteration;
   printf("\nEnter the number of iteration=\n ");
//    iteration = int.Parse(Console.ReadLine());
   scanf("%d",&iteration);
   for (int i = 0; i < 6; i++)
   {
printf("\nIteration= %d" + i);
a = x1;
x1 = (1 - 3 * x2 + 5 * x3) / 12;
e1 = ((x1 - a) / x1) * 100;
//x = Math.Abs(e1);
if (e1 < 0)
{
   e1 = e1 * -1;
}
x = e1;
b = x2;
x2 = (28 - x1 - 3 * x3) / 5;
e2 = ((x2 - b) / x2) * 100;
//y = Math.Abs(e2);
if (e2 < 0)
{
   e2 = e2 * -1;
}
y = e2;
c = x3;
x3 = (76 - 3 * x1 - 7 * x2) / 13;
e3 = ((x3 - c) / x3) * 100;
//z = Math.Abs(e3);
if (e3 < 0)
{
   e3 = e3 * -1;
}
z = e3;
printf("\nx1= %f" , x1);
printf("\nx2= %f" , x2);
printf("\nx3=%f ",x3);
printf("\ne1=%f " , x);
printf("\ne2=%f " , y);
printf("\ne3=%f " , z);

if (x > y)
{
   if (x > z)
   {printf("\nMax error %f" , x);}
   else
   {   printf("\nMax error %f" , z);}
}
else
{
   if (y > z)
   {printf("\nMax error %f" , y);}
   else { printf("\nMax error %f" , z); }
}
   }
   getche();
}


Numerical Analysis Bisection Method



 Bisection Method

#include<stdio.h>
#include<conio.h>
#include<math.h>

void main(void)
{
//clrscr();
float xl,xu,xu_n,xl_n,xm,f_xm,xm_old,xm_new;
float f_xl,f_xu;
float condition,error;
printf("Enter value of xl:\n");
scanf("%f",&xl);
printf("Enter value of xu:\n");
scanf("%f",&xu);
f_xl=(xl*xl*xl)-20;
f_xu=(xu*xu*xu)-20;
printf("f(xl)=%.3f\nf(xu)=%.3f\n",f_xl,f_xu);
condition=f_xu*f_xl;
printf("product of f(xl) and f(xu): %f\n",condition);
for(int i=0;i<=4;i++)
{
//cout<<"";
xm_old=(xl+xu)/2;
printf("xm_old=%f\n",xm_old);
xm=xm_old;
//xu=xm_old;
f_xl=(xl*xl*xl)-20;
f_xm=(xm*xm*xm)-20;
printf("f(xl)=%.3f\nf(xm)=%.3f\n",f_xl,f_xm);
condition=f_xm*f_xl;
printf("product of f(xl) and f(xm): %f\n",condition);

if(condition<0){xl=xl;xu=xm_old;}
if(condition>0){xl=xm_old;xu=xu;}
//xm_new=(xl+xu)/2;
//printf("xm_new=%f\n",xm_new);
//error=((xm_new-xm_old)/xm_new)*100;
//printf("Error=%f\n",error);
}


getch();
}

Numerical Analysis Newton Rapson

Newton Rapson


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
   double x = 3;
   double fact1, fact2,ans;
   double new_value,old,error=1;
   for (int i = 0; i <= 10; i++)
   {
ans = ((x * x * x) - 20) / 3 * (x * x);
if (error <= 0.009)
{
   printf("\nCompleted");
   break;
}
else
{
   fact1 = (x * x * x) - 20;
   fact2 = 3 * (x * x);
   ans = fact1 / fact2;
   ans = x - ans;
   old = x;
   x = ans;
   new_value = ans;
   printf("\nans: %f\n", ans);
   error = ((new_value - old) / new_value) * 100;
   error = abs(error);
   printf("\npercentage:%f\n", error);
}

   }
   getche();
}


Numerical Analysis EULER

Euler Method

#include<conio.h>
#include<stdio.h>
#include<math.h>
void main(void)
{
clrscr();
float y=5.0,h=1.0;
float x=0.0,error,z=2.763;
for(int i=0;i<3;i++)
{
double fact1=3*(exp(-x));
double fact2=0.4*y;
y=y+(fact1-fact2)*(h);
x++;
printf("ans: %f\n",y);
}
error=((z-y)/z)*100;
if(error<1)
error*=-1;
printf("percentage: %f\n",error);
getch();
}

Numerical Analysis

Taylor Series Code

#include<conio.h>
#include<stdio.h>
void main(void)
{
clrscr();
float x=4.0,h=2.0;
float a=125.0,b=74.0,c=30,d=6.0;
float f;
printf("\n Find Talyor Series: ");
f=(a)+(b*h)+((c*h*h)/2.0)+((d*h*h*h)/6.0);
printf("\nAns %f",f);
getch();
}

JF-17 Thunder

JF-17 Thunder

Pakistan Air Force Chengdu JF-17 Gu.jpg

Presentation

http://www.slideshare.net/owatheowais/jf-thunder-17



INTRODUCTION
The PAC JF17 THUNDER also designated CAC FC-1 XIALONG is a light weight single engine , multiple combat aircraft developed jointly by the CHENGDAU AIRCRAFT INDUSTRIES ICORPORATION OF CHINA , the PAKISTAN AIRFORCE and the PAKISTAN AERONAUTICAL COMPLEX..
The JF17 was primarily developed to meet the requirements of PAKISTAN AIRFORCE for a cost effective , modern , multi role combat aircraft as an inexpensive replacement for its large fleet of NANCHANG A-5 bombers, CHENGDU F-7 inceptors and DISSAULT MIRAGE 111/5 fighters
Pakistan and China signed the contract to jointly develop the FC-1 / Super 7 in 1999. Pace of design was very slow.The maiden test flight of the first prototype took place during 2003 in China, the Pakistani designation Super 7 being replaced with JF-17, and later test flights with a modified design occurred in 2006. The Pakistan Air Force officially inducted its first JF-17 squadron on 18 February 2010 with 14 aircraft.
The JF-17 is expected to cost approximately US$15 million per unit[and the Pakistan Air Force has a confirmed order for 150 JF-17's, which may increase to 250 aircraft.t was reported in 2008 that Azerbaijan and Zimbabwe had placed orders for the aircraft and nine other countries, including Bangladesh, Myanmer, Egypt , Iran , Lebanon, Malaysia, Morroco ,Nigeria , SriLanka and were showing interest.


HISTORY OF JF17
China and Grumman (USA) signed a $550 million agreement to modernize 55 J-7 Fighters under the project called “Super-7″. However the project was cancelled due to political problems and significant increases in the cost.
As substitute to Super-7, China started the FC-1 project. In February 1992, CATIC (China Aero Technology Import and Export Corporation) invited the Pakistan to invest in the project in return for huge Transfer of Technology and participation in R&D of the project. Pakistan Accepted. The First Flight was planned in 1996, but it got delayed because Pakistan wished to upgrade the characteristics in response to India’s acquisitions of Su-30MKI. The project began to Stagnate.  But in 1998, Pakistani PM’s visit to China resulted in the continuation of the Programme.  In 1999, sanctions on Pakistan led to serious setbacks on the programme. Pakistan hoped to install Western Avionics on the plane, which was now not possible. Year 2001 saw the changes in approach to develop the fighter plane. The development of airframe was de-linked from the development of Avionics. The Comprehensive design was completed in September 2002 while the development of different aircraft systems progressed. The First Aircraft was assembled by May 2003.
After the completion of design work in 2001, JF-17 did its maiden flight in 2003. Airframe was then redesigned according to modern standards and implemented in Prototype 4 of the JF-17 which included DSI air intakes, New Landing Gear, modified rudder and tail compartment etc. First delivery to the PAF took place in 2007 when 2 fighters landed at Kamra , AFB which later took part in 23rd March parade of 2007. In the three years, PAF received 14 more jets and on 18th of February, 2010, PAF inducted JF-17 in its No. 26 fighter Squadron known as “Spiders” which was based at Peshawar AFB replacing the A-5C Fantans. Following the induction, PAF added two locally manufactured JF-17s to its fleet and now the serial local manufacturing of JF-17 is underway.


FEATURES
The avionics software of JF-17 is based on civilian C++ Language which makes its Motorolla 88000 microprocessor functional which then powers the avionics of JF-17 Thunder. The aircraft’s glass cockpit incorporates an Electronic Flight Instrument System (EFIS) and a wide-angle holographic Heads-Up Display (HUD), which has a minimum total field view of 25 degrees. The EFIS is made up of three color multi-function displays (MFD) providing basic flight information, tactical information and information on the engine, fuel, electrical, hydraulics, flight control and environment control systems. The aircraft is also equipped with Fly by Wire [FBW] control system which controls the movement through its own computer.
For primary means on communication, the JF-17 is equipped with VHF/UHF radios.. For defensive purposes, the JF-17 is equipped with Radar Warning Receiver which warns the pilot for any incoming Radar guided missile or even any missile lock. Furthermore, Chaff and Flares are also to be used as the last line of defense against the incoming missiles.
Air Weapons Complex has also designed the Air Combat Maneuvering Instrument [ACMI] which records and simulates the actions taken by the aircraft during combat and training exercises. 
The JF-17 is equipped with single Russian made RD-93 Turbofan engine which produces 19000lb of thrust enabling the aircraft to achieve the 0.99 Thrust to Weight Ratio [TWR]. RD-93 will soon be replaced with Chinese made WS-13 which generates more power and has relatively low operational costs


WEAPONS
JF-17 is expected to perform all the roles which currently PAFs collective fleet of A-5s, F-7s and Mirages perform. For this purpose, Jf-17 is equipped with 7 external hard points, 2 on wing tips for air to air missiles, 4 under wings and a single center-line hard point. These hard points can carry state of the art weapons both Air-to-Air and Air-to-Surface.
The primary air to air Beyond Visual Range [BVR] missile of JF-17 is Chinese made SD-10 which has maximum range of 100kms. It is the latest missile which the Peoples Republic of China Air Force is using on their latest J-10 Vanguards, which are sought to be the most lethal fighters in Chinese inventory. For With-in-Visual Range [WVR] or short range missiles, JF-17 can carry Chinese made PL-5C, PL-7, American origin AIM-9L/M Sidewinder, South African A darter, French made MICA air to air missile and Russian made Aspide air to air missiles. They have a operational ranges ranging from 1km to 18km except for A darter which has an operational range of 60km.


SPECIFICATIONS
General
Crew ONE
Maiden Flight AUGUST 2003
Type MULTI ROLE
Cost $15M - $25M
Dimensions
Length 14.9 m 49 FT
Height 4.77 m 15.6 ft
Wing Area 24.4 m² 263 ft²
Weights
Empty Weight 6,411 kg 14,134 lb
MaxTake-Off Weight 12,474 kg 27,500 lb
Max, Landing Weight 7,802 kg 17,200 lb
Fuel Weight 2,268 kg 5000 lb


THE FUTURE
PAF intends to induct JF-17 in mass number. Order for 250 jets has already taken place which includes the batch of first 50 fighters equipped with Chinese avionics and radar system. Whereas the rest of the batches will be integrated with non-Chinese hardware. Being an infant platform, JF-17 has a lot of room for improvement which includes equipping of JF-17 with Advanced Electronically Scanned Array (AESA) radar system, advance armament like American made AIM-120C AMRAAMs, AIM-9X Sidewinder, Joint Direct Attack Munitions (JDAM), South African R-Darter etc.
Several nations have expressed their interest in JF-17 which includes Azerbaijan, Egypt, Malaysia, Indonesia, Turkey, Bangladesh and Philippines. China is also reported to have plans regarding the induction of JF-17 in their front line Squadro

Wednesday 6 May 2015

Lesson 10 Using Android Intents Tutorial ---- 5

Using Android Intents Tutorial

A Little Manifest Destiny

I’ve re-written the createAdapter method in our main activity to automatically populate the list with the other activities.
protected ListAdapter createAdapter()
    {
 
     List<String> tempList = new ArrayList<String>();
 
     Intent listIntent = new Intent("com.learnandroid.intents.VIEW_SAMPLE_CODE");
        listIntent.addCategory("com.learnandroid.intents.SAMPLE_CODE");
 
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activityList = pm.queryIntentActivities(listIntent, 0);
 
        for (int i = 0; i < activityList.size(); i++) {
         ResolveInfo info = activityList.get(i);
         CharSequence labelChars = info.loadLabel(pm);
         String displayName = labelChars != null ? labelChars.toString() : info.activityInfo.name;
         tempList.add(displayName);
        }
 
     String[] listValues = tempList.toArray(new String[0]);
 
     // Create a simple array adapter (of type string) with the test values
     ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1
       , listValues);
 
     return adapter;
    }
First I create an Intent using the action we specified. Next I add a category to the Intent. So at this point the intent will only use activities which have both that action and that category in their intent-filter.
Next I get an instance of PackageManager. We use this to call queryIntentActivities. This handy method will return a list of all of the activities that could be activated by the intent you pass in as a parameter. Now that we have this list, we loop through the list and get the label for each activity. I went ahead and put in some logic to get the activity name if the label isn’t present, since the label is optional. Finally, we save the results to a string array and viola! We have a dynamic list.
Dynamic List
You might have noticed that this list is shorter than the previous one. That’s because we have one more activity to create. Let’s go ahead and create a class named FinalActivity and put an entry into the Android Manifest for it.
        <activity android:name="FinalActivity" android:label="When You Just Don't Know">
            <intent-filter >
                <action android:name="com.learnandroid.intents.VIEW_SAMPLE_CODE" />
                <category android:name="com.learnandroid.intents.SAMPLE_CODE"/>                
            </intent-filter>
        </activity>
Now when you run you should see the same menu as before.
Final Dynamic List
Finally, we need to rewrite our onListItemClick method to also be dynamic. I am just going to use the same method used to list our activities.
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
     Intent listIntent = new Intent("com.learnandroid.intents.VIEW_SAMPLE_CODE");
        listIntent.addCategory("com.learnandroid.intents.SAMPLE_CODE");
 
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activityList = pm.queryIntentActivities(listIntent, 0);
 
        ResolveInfo info = activityList.get(position);
        Intent dynamicIntent = new Intent();
        dynamicIntent.setClassName(info.activityInfo.applicationInfo.packageName
            , info.activityInfo.name);
        startActivityForResult(dynamicIntent, 1700 + position);
    }
Instead of looping through all of the activities, we just use the position integer to get the selected activity. We create an empty Intent, and then use the setClassName that accepts String values to identify the class. We are just going to call all of the activities using startActivityForResult. Since we are checking for the result code RESULT_OK an activity that isn’t setup to return anything should just fail this if statement and skip our popup code.
This should be enough to get your started with a foundation for working with Intents. If you want, you can download the source code for this entire project here.
As always, please leave comments with any questions you have on the subject, or anything you would like to see elaborated on in a future article. Thank you for reading.

Lesson 10 Using Android Intents Tutorial ---- 4

Using Android Intents Tutorial

Categorically Speaking

We have added each of our activities to the Android Manifest. At this point I want to look at what we currently have in the manifest.
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.learnandroid.intents"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="3" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".UsingIntentsActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="GetName"></activity>
        <activity android:name="UriActivity"></activity>
    </application>
 
</manifest>
You’ll notice two of our activities are simple tags with just a name.
        <activity android:name="GetName"></activity>
        <activity android:name="UriActivity"></activity>
But one of our activities has a section named intent-filter
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
We saw actions in the last section (and this is how you tell android what actions your activity can perform), but the category is new. This combination of the action “android.intent.action.MAIN” and the category “android.intent.category.LAUNCHER” tells android that this is the main activity that should be launched when the user touches the application icon in the launcher. We can use the action and category to limit what is affected by our intent. So let’s add a category and action to our other two activities now.
We can use whatever we want for our action and our category. The Android developers recommend that if you use your own action or your own category that you prefix it with your package name, to prevent accidentally using the same action as another application on the phone. Here is our Manifest file now.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.learnandroid.intents"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="3" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".UsingIntentsActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="GetName" android:label="The Activity You Know">
            <intent-filter >
                <action android:name="com.learnandroid.intents.VIEW_SAMPLE_CODE" />
                <category android:name="com.learnandroid.intents.SAMPLE_CODE"/>                
            </intent-filter>
        </activity>
        <activity android:name="UriActivity" android:label="The URI You Know">
            <intent-filter >
                <action android:name="com.learnandroid.intents.VIEW_SAMPLE_CODE" />
                <category android:name="com.learnandroid.intents.SAMPLE_CODE"/>                
            </intent-filter>
        </activity>
    </application>
 
</manifest>
You might have noticed that I also added labels for our Activities. We’re going to use the actions, categories, and labels in the Android Manifest to automatically update the list in our main activity, replacing the hard coded array we have been using.

Lesson 10 Using Android Intents Tutorial ---- 3

Using Android Intents Tutorial

The Action You Know

So far we have been opening activities with Intents using the Activity name. Intents, however, are very powerful in that they can determine what activity should be run based on the criteria you provide. If there is a case where more than one activity can use that type of content, Android with ask the user which app they would prefer to use. I’m going to create a new class that gives some examples of common actions.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 xmlns:android="http://schemas.android.com/apk/res/android">
 <TableRow>
  <TextView
      android:text="Latitude"
      android:layout_width="150dp"
      android:layout_height="wrap_content"
      android:layout_column="0" />
  <TextView
      android:text="Longitude"
      android:layout_width="150dp"
      android:layout_height="wrap_content"
      android:layout_column="1" />      
 </TableRow>
 <TableRow>
     <EditText
      android:id="@+id/txtLatitude"
      android:width="100px"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="35.696471" />
      <EditText
      android:id="@+id/txtLongitude"
      android:width="100px"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="139.570472" /> 
 </TableRow>
 <TableRow>
  <Button 
      android:id="@+id/btnShowLocation"
      android:text="Show Location"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
 </TableRow>
 <TableRow>
     <TextView      
      android:width="100px"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Phone Number" />
      <EditText
      android:id="@+id/txtPhoneNumber"
      android:width="100px"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:inputType="phone"
      android:text="555-1212" /> 
 </TableRow>
 <TableRow>
  <Button 
      android:id="@+id/btnDial"
      android:text="Dial Number"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
  <Button 
      android:id="@+id/btnCall"
      android:text="Call Number"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
 </TableRow>
 <TableRow>
  <Button 
      android:id="@+id/btnContact"
      android:text="Pick Contact"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
 </TableRow>
</TableLayout>
package com.learnandroid.intents;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class UriActivity extends Activity {
 
 private EditText txtLatitude;
 private EditText txtLongitude;
 private EditText txtPhoneNumber;
 
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.uri_layout);
 
        //Show Location Example
        txtLatitude = (EditText) findViewById(R.id.txtLatitude);
        txtLongitude = (EditText) findViewById(R.id.txtLongitude);
        Button btnShow = (Button) findViewById(R.id.btnShowLocation);
        btnShow.setOnClickListener(new Button.OnClickListener() {
 
        @Override
  public void onClick(View v) {
   Uri location = Uri.parse("http://maps.google.com/maps?q=" 
     + txtLatitude.getText().toString() 
     + "," 
     + txtLongitude.getText().toString());
   startActivity(new Intent(Intent.ACTION_VIEW, location));
  } });
 
        //Dial Phone Example
        txtPhoneNumber = (EditText) findViewById(R.id.txtPhoneNumber);
        Button btnDial = (Button) findViewById(R.id.btnDial);
        btnDial.setOnClickListener(new Button.OnClickListener() {
 
        @Override
  public void onClick(View v) {    
   Uri phoneNum = Uri.parse("tel:" + txtPhoneNumber.getText().toString());
   startActivity(new Intent(Intent.ACTION_DIAL, phoneNum));
  } });
 
        //Make Call Example
        Button btnCall = (Button) findViewById(R.id.btnCall);
        btnCall.setOnClickListener(new Button.OnClickListener() {
 
        @Override
  public void onClick(View v) {    
   Uri phoneNum = Uri.parse("tel:" + txtPhoneNumber.getText().toString());
   startActivity(new Intent(Intent.ACTION_CALL, phoneNum));
  } });
 
        //Select from Contacts Example
        Button btnContact = (Button) findViewById(R.id.btnContact);
        btnContact.setOnClickListener(new Button.OnClickListener() {
 
        @Override
  public void onClick(View v) {    
   Uri content = Uri.parse("content://contacts/people");
   startActivity(new Intent(Intent.ACTION_PICK, content));
  } });
    }
}
We have a couple of EditText widgets that allow the user to enter in Latitude and Longitude (I went ahead a pre-populated them with the location of the Studio Ghibli museum in Japan). We have a button that when clicked shows the location on the map. We pass a URI to the startActivity method, instead of a class name, and Android uses the most appropriate app. We could have also passed in a URI like this, which would have launched the Google Maps app
Uri location = Uri.parse("geo:" + txtLatitude.getText().toString() + "," + txtLongitude.getText().toString());
The only reason I didn’t do it this way is I don’t have the Maps app on my emulator and so I didn’t want to assume you did either.
The next part of this page is another EditText widget where the user can enter a phone number, along with a button that will dial the number. You can see we used the ACTION_DIAL action this time, and passed in a tel: format URI. This will bring up the dialer with the number pre-populated. The next button demonstrates using ACTION_CALL in order to just place the call. Remember, though, when the user installs you app they will have to grant your app permission to make calls.
Finally, we show the action that allows us to have the user pick a person from their contacts. ACTION_PICK can be used for any collection, not just the contact list.

Lesson 10 Using Android Intents Tutorial ---- 2

Using Android Intents Tutorial

The Activity You Know

While we already discussed opening a specific activity in a previous article we also need to look at how to interact with an activity we open. So previously, we used this line of code when opening our activity.
startActivity(new Intent(this, Hello1.class));
This is a call to the startActivity method which expects an Intent to be passed in as a parameter. This method opens a new Activity and then forgets about it completely. That fine if this is the behavior you want, but what if you want to know what the user did with the new activity? To accomplish this, we are going to use startActivityForResult. Let’s go ahead and implement our onListItemClick method to handle when the user clicks on a list item.
@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
     if (position == 0) {
      startActivityForResult(new Intent(this, GetName.class), 1701); 
     } 
     if (position == 1) {
      //Item 2
     }
     if (position == 2) {
      //Item 3
     }
    }
The line of code we are interested in here is this one:
startActivityForResult(new Intent(this, GetName.class), 1701);
We are starting a new activity, but this time we are telling Android that we expect to get a result back. As we did with startActivity in this article we are passing in an Intent with the class of our Activity. We also pass in a request code. This can be any integer and can be used to determine which request is being examined. For now I’m just going to use 1701 because I’m a Sci-Fi fan. Don’t worry about this for now, just put whatever positive integer you want here (Android will only return codes >= 0).
So far, this isn’t any harder than just calling an activity. Okay, let’s go ahead and create the new class we are going to open like so:
package com.learnandroid.intents;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 
public class GetName extends Activity implements OnClickListener {
 
 private EditText txtName;
 
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_you_know);
        txtName = (EditText) findViewById(R.id.txtName);
        Button btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);
    }
 
 @Override
 public void onClick(View v) {
  Intent data = new Intent();
  data.putExtra("Name", txtName.getText().toString());
  setResult(RESULT_OK, data);
  finish();
 }
}
The only thing that should be new to you here is the contents of our onClick method.
Intent data = new Intent();
data.putExtra("Name", txtName.getText().toString());
setResult(RESULT_OK, data);
finish();
First we create a new Intent to use for passing data back in our response. The intent provides “Extras” as a way of passing extra information we need. We put an extra in the intent, in our case whatever string the user has provided. Then we call setResult in order to tell Android what result the calling activity should be sent. Finally we call finish, which destroys our current activity and takes us back to the previous activity. One thing to note is that each extra is given a name. I just used “Name” as the name of my extra since that’s what it represents, but it can be any string. We will use the name to retrieve the extra data.
When the activity that was called using startActivityForResult finishes it sends its result back to the calling activity by calling the onActivityResult method. So let’s override that method and do something with our result.
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     if (resultCode == RESULT_OK) {
      Toast helloToast = Toast.makeText(this, "You Entered: " + data.getStringExtra("Name") 
                    , Toast.LENGTH_LONG);
         helloToast.setGravity(Gravity.CENTER, 0, 0);
         helloToast.show();
     }
    }
Just to keep things simple, I am just going to use a popup (covered in this article) to display the value that was in the EditText. The Intent variable named data is the same intent we placed into our result. I retrieve the name we put into an extra by calling getStringExtra here. Our final result should look like this.
Result