Sunday, February 24, 2008
The movie is over. Motor Cycle diary. This movie is the early life of (23-24) Che Guevara. Che and his friend start to travel with their bike "The Mighty One". The journey moved che and me(while watching).I was thinking of my friends while watching the movie. Some of the faces started to move around in my mind while i was watching. I was starting to map some of them's life style with those and found some. I was wondered that people like che live around us. I wanted to call those friends and say that "You are great". But didnt do that, as i found no match of me with che. My thinkings are only around me. My mappings are all with me. My mind is a selfcentered mind. I lead a monotonous life without any variations and always avoid any kind of problems coming on my way. I like to live a life alone in a shell.Even in this whole post i'm telling about me.
whatever if you ever get a chance to watch the movie watch it. Here is a wiki of Ernesto Guevara de la Serna
Che was a great leader i think :)
Saturday, February 23, 2008
A song from "Taare Zameen Par". It moved me, You can have the song here
Full album
Song By ADNAN SAMI,AURIEL CORDO,ANANYA WADKAR
A Little Sweet, A Little Sour
A Little Close Not Too Far
All I Need, All I Need
All I Need Is To Be Free
(Repeat)
Chhoo Loon Main
Itna Kareeb
Chal Padun
To Kitna Door
A Little Sweet, A Little Sour...
Chhoo Loon Main Itna Kareeb
Chal Padun To Kitne Door
Sapna Ka Buna Sweater Sa Warm
Safed Baadalon Ke Paar
Mera Jahan
Let Me In Without A Shout
Le Me In I Have A Doubt
Let Me In Without A Shout
Let Me In I Have A Doubt
There Are More,Many More
Many Many Many More Like Me
Akela Nahin Main
Khuli Aankhon Se Neend Mein Chalta
Girta Zyada Kam Sambhalta
Akela Nahin Main
Khuli Aankhon Se Neend Mein Chalta
Girta Zyada Kam Sambhalta
Phir Bhi Na Koi Shaq Na Subha
Nikalega Phir Se Sooraj Jo Dooba
Hairat Ho Sabko Aisa
Ajooba Hai Mera Jahan
Open Eyed How I Run
How I Run To The Other Side
Open Eyed How I Run
How I Run To The Other Side
Then I Glide Like A Bird
I Just Want To Be
Udne Ko Sau Pankh Diye Hain
Chadne Ko Khula Aasmaan
Udne Ko Sau Pankh Diye Hain
Chadne Ko Khula Aasmaan
Mudne Ko Hai Karwat Karwat
Aur Badhne Ko Mera Jahan
Bachpan Ke Din Chaar
Na Aayenge Baar Baar
Jee Le Jee Le Mere Yaar
Jeib Khaali To Udhaar
Jee Zindagi
Thursday, February 14, 2008
I am a newbie in applet programming and very bad at programming. A google programmer ;). Recently i was trying to make an applet which could upload file to a php server, i started to googling and found that there are a lot of this kind of applet and none of them are not free :(. So i wanted to write one of my own and failed immediately as i didn't know how to run an applet. Again googling and learned to write applets.
Then i started to google how to show the file system in an applet, againg googling and found a code which can show your file system in a good tree way. But it was a normal java application not an applet, but i found it was easy to add to an applet. This is the code how you can show your file system in an applet. Thanks goes to Kirill Grouchnikov.
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
/**
* @author Kirill Grouchnikov
*/
public class FileTreePanel extends JPanel implements TreeSelectionListener,InterfaceHttpResponse{
String serverAddress = "http://www.smdprogramming.com/shimul/fup3/";
//String serverAddress = "http://localhost/fup3/";
/**
* File system view.
*/
protected static FileSystemView fsv = FileSystemView.getFileSystemView();
/**
* Renderer for the file tree.
*
* @author Kirill Grouchnikov
*/
private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {
/**
* Icon cache to speed the rendering.
*/
private Map
/**
* Root name cache to speed the rendering.
*/
private Map
/*
* (non-Javadoc)
*
* @see javax.swing.tree.DefaultTreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree,
* java.lang.Object, boolean, boolean, boolean, int, boolean)
*/
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
FileTreeNode ftn = (FileTreeNode) value;
File file = ftn.file;
String filename = "";
if (file != null) {
if (ftn.isFileSystemRoot) {
// long start = System.currentTimeMillis();
filename = this.rootNameCache.get(file);
if (filename == null) {
filename = fsv.getSystemDisplayName(file);
this.rootNameCache.put(file, filename);
}
// long end = System.currentTimeMillis();
// System.out.println(filename + ":" + (end - start));
} else {
filename = file.getName();
}
}
JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,
filename, sel, expanded, leaf, row, hasFocus);
if (file != null) {
Icon icon = this.iconCache.get(filename);
if (icon == null) {
// System.out.println("Getting icon of " + filename);
icon = fsv.getSystemIcon(file);
this.iconCache.put(filename, icon);
}
result.setIcon(icon);
}
return result;
}
}
/**
* A node in the file tree.
*
* @author Kirill Grouchnikov
*/
private static class FileTreeNode implements TreeNode {
/**
* Node file.
*/
public File file;
/**
* Children of the node file.
*/
private File[] children;
/**
* Parent node.
*/
private TreeNode parent;
/**
* Indication whether this node corresponds to a file system root.
*/
private boolean isFileSystemRoot;
/**
* Creates a new file tree node.
*
* @param file
* Node file
* @param isFileSystemRoot
* Indicates whether the file is a file system root.
* @param parent
* Parent node.
*/
public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent) {
this.file = file;
this.isFileSystemRoot = isFileSystemRoot;
this.parent = parent;
this.children = this.file.listFiles();
if (this.children == null)
this.children = new File[0];
}
/**
* Creates a new file tree node.
*
* @param children
* Children files.
*/
public FileTreeNode(File[] children) {
this.file = null;
this.parent = null;
this.children = children;
}
/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#children()
*/
public Enumeration children() {
final int elementCount = this.children.length;
return new Enumeration
int count = 0;
/*
* (non-Javadoc)
*
* @see java.util.Enumeration#hasMoreElements()
*/
public boolean hasMoreElements() {
return this.count < elementCount;
}
/*
* (non-Javadoc)
*
* @see java.util.Enumeration#nextElement()
*/
public File nextElement() {
if (this.count < elementCount) {
return FileTreeNode.this.children[this.count++];
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getAllowsChildren()
*/
public boolean getAllowsChildren() {
return true;
}
/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getChildAt(int)
*/
public TreeNode getChildAt(int childIndex) {
return new FileTreeNode(this.children[childIndex],
this.parent == null, this);
}
/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getChildCount()
*/
public int getChildCount() {
return this.children.length;
}
/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getIndex(javax.swing.tree.TreeNode)
*/
public int getIndex(TreeNode node) {
FileTreeNode ftn = (FileTreeNode) node;
for (int i = 0; i < this.children.length; i++) {
if (ftn.file.equals(this.children[i]))
return i;
}
return -1;
}
/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getParent()
*/
public TreeNode getParent() {
return this.parent;
}
/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#isLeaf()
*/
public boolean isLeaf() {
return (this.getChildCount() == 0);
}
}
/**
* The file tree.
*/
private JTree tree;
/**
* Creates the file tree panel.
*/
public FileTreePanel() {
this.setLayout(new BorderLayout());
File[] roots = File.listRoots();
FileTreeNode rootTreeNode = new FileTreeNode(roots);
this.tree = new JTree(rootTreeNode);
this.tree.setCellRenderer(new FileTreeCellRenderer());
this.tree.setRootVisible(false);
final JScrollPane jsp = new JScrollPane(this.tree);
jsp.setBorder(new EmptyBorder(0, 0, 0, 0));
this.add(jsp, BorderLayout.CENTER);
tree.addTreeSelectionListener(this);
}
testapp ta;
/**
* Creates the file tree panel.
*/
public FileTreePanel(testapp ta) {
this.ta = ta;
this.setLayout(new BorderLayout());
File[] roots = File.listRoots();
FileTreeNode rootTreeNode = new FileTreeNode(roots);
this.tree = new JTree(rootTreeNode);
this.tree.setCellRenderer(new FileTreeCellRenderer());
this.tree.setRootVisible(false);
final JScrollPane jsp = new JScrollPane(this.tree);
jsp.setBorder(new EmptyBorder(0, 0, 0, 0));
this.add(jsp, BorderLayout.CENTER);
tree.addTreeSelectionListener(this);
}
File currentFile= null;
public void valueChanged(TreeSelectionEvent e) {
// TODO Auto-generated method stub
FileTreeNode node = (FileTreeNode)
tree.getLastSelectedPathComponent();
System.out.println("slecte asldf "+node.isLeaf());
if(node.isLeaf())
{
currentFile = node.file;
System.out.println("File name "+currentFile.getName());
}
else
currentFile = null;
}
// public static void main(String[] args) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// JFrame frame = new JFrame("File tree");
// frame.setSize(500, 400);
// frame.setLocationRelativeTo(null);
// frame.add(new FileTreePanel());
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setVisible(true);
// }
// });
// }
}
Now to add it to my applet this was the code
import java.applet.Applet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import org.omg.CORBA.FREE_MEM;
public class testapp extends Applet{
JTextField field;
JButton jb;
FileTreePanel ftreePanel;
public void init() {
//Execute a job on the event-dispatching thread:
//creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't successfully complete");
}
addItem(false, "initializing... ");
}
private void createGUI() {
ftreePanel = new FileTreePanel(this);
add(ftreePanel);
// File[] roots = File.listRoots();
// FileTreeNode rootTreeNode = new FileTreeNode(roots);
// this.tree = new JTree(rootTreeNode);
// this.tree.setCellRenderer(new FileTreeCellRenderer());
// this.tree.setRootVisible(false);
// add(tree);
//Create the text field and make it uneditable.
field = new JTextField();
field.setEditable(false);
field.setAutoscrolls(true);
jb= new JButton("Upload");
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
uploadJob();
}
});
jb.setSize(50, 50);
//add(jb);
JPanel jp = new JPanel();
jp.add(jb);
add(jp);
//Set the layout manager so that the text field will be
//as wide as possible.
setLayout(new java.awt.GridLayout(1,0));
//Add the text field to the applet.
add(field);
//new FileTreePanel();
}
public void start() {
addItem(false, "starting... ");
}
public void stop() {
addItem(false, "stopping... ");
}
public void destroy() {
addItem(false, "preparing for unloading...");
cleanUp();
}
private void cleanUp() {
//Execute a job on the event-dispatching thread:
//taking the text field out of this applet.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
remove(field);
}
});
} catch (Exception e) {
System.err.println("cleanUp didn't successfully complete");
}
field = null;
}
private void addItem(boolean alreadyInEDT, String newWord) {
if (alreadyInEDT) {
addItem(newWord);
} else {
final String word = newWord;
//Execute a job on the event-dispatching thread:
//invoking addItem(newWord).
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
addItem(word);
}
});
} catch (Exception e) {
System.err.println("addItem didn't successfully complete");
}
}
}
//Invoke this method ONLY from the event-dispatching thread.
private void addItem(String newWord) {
String t = field.getText();
System.out.println(newWord);
field.setText(t + newWord);
}
void uploadJob(){
addItem("Upload button clicked");
ftreePanel.uploadFile();
}
void showMessage(String message)
{
field.setText(message);
}
}
you will some code are missing in previous FileTreePanel which will be added later on. The next thing came to my mind is how to get the node which is clicked in the file tree. It was very easy,u have to just implement the addTreeSelectionListener. For uploading part i used the java code which was posted previously during android file upload time. This function was added with FileTreePanel.java
public void uploadFile()
{
if(currentFile!= null)
{
ta.showMessage("Uploading file"+currentFile.getAbsolutePath());
System.out.println("Current file"+currentFile.getAbsolutePath());
String fileName = null;
try {
FileInputStream fis = new FileInputStream(currentFile);
fileName = currentFile.getName();
HttpFileUploader htfu = new HttpFileUploader(serverAddress+"test2.php","pngData", "", null,this);
System.out.println("File Name "+serverAddress+"test2.php");
htfu.doStart(fis,fileName);
ta.showMessage("Please wait");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ta.showMessage("File not found exception");
}
//ta.showMessage("Done Uploading file u can check at "+serverAddress+"uploads/"+fileName);
}
else
ta.showMessage("Not a file");
}
Now after completing everything the applet was running smoothly through Eclipse ide. But when i tried to run in browser the applet was not showing the file tree. I was in a problem then , I found that to access client pc resources you need to sign your applet with lengthy process. This link came great great help to me.
How to sign an applet
So after signing the applet it started to show it's face in the browser. The whole process took me 3 long days,damn i'm the slowest learner. You can check it here I don't know how long it will be available here. Whatever i am a happy monkey now. :D. You can find uploaded files here
[edited later]
The quest was not over yet, i was using jdk6 with jre6, so my applet was not showing into my friends pc whose jre was jre5.0. So i had to chnage the settings in eclipse and then remake the jar and the whole process.
Labels: Applet, file upload, Java, PHP
Saturday, January 26, 2008
I needed to load remote images to my application and bind this image to an ImageView object. HttpURLConnection is used to download the image data and BitmapFactory is used to produce the bitmap which will be used as imageview resources.
Here is the layout file
XML:
< ?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"
>
< TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HTTPImage load test"
/>
< Button id="@+id/get_imagebt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get an image"
android:layout_gravity="center"
/>
< ImageView id="@+id/imview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
< /LinearLayout>
The java code goes like it
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class HTTPTest extends Activity {
ImageView imView;
String imageUrl="http://11.0.6.23/";
Random r;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
r= new Random();
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView = (ImageView)findViewById(R.id.imview);
}
View.OnClickListener getImgListener = new View.OnClickListener()
{
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
//i tried to randomize the file download, in my server i put 4 files with name like
//png0.png, png1.png, png2.png so different file is downloaded in button press
int i =r.nextInt()%4;
downloadFile(imageUrl+"png"+i+".png");
Log.i("im url",imageUrl+"png"+i+".png");
}
};
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The code is pretty simple and easy, most of you might already have done this, i am a slow learner, i tried different ways first, i tried to read the whole bytes of image data, do other trial and error method. I was confused about the Bitmap tranformation technology. Then i found that there is a built in class known as BitmapFactory, it can produce bitmap directly from stream. This saved a lot of my efforts. Hope it will come useful to you.
Happy andcoding :)
Labels: Android, http image download, imageview
Friday, January 25, 2008
Yesterday, the whole day i was trying to post a file to a php server. The whole day and evening i tried and failed. I googled, searched in forum and did a lot of other stuffs. I couldn't succed, at last when i was frustrated on me, then i found another tutorial in a forum, this time it worked. mu ha ha :) (Copy paste rulllzz, so i should never try myself anything :(). The code simulates file posting to a php server. So it will work with servers where file upload from a server is supported. Here goes the code
The php code used in server
< ?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
? >
The android code goes here
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.ByteArrayBuffer;
import android.util.Log;
public class HttpFileUploader implements Runnable{
URL connectURL;
String params;
String responseString;
InterfaceHttpUtil ifPostBack;
String fileName;
byte[] dataToServer;
HttpFileUploader(String urlString, String params, String fileName ){
try{
connectURL = new URL(urlString);
}catch(Exception ex){
Log.i("URL FORMATION","MALFORMATED URL");
}
this.params = params+"=";
this.fileName = fileName;
}
void doStart(FileInputStream stream){
fileInputStream = stream;
thirdTry();
}
FileInputStream fileInputStream = null;
void thirdTry(){
String exsistingFileName = "asdf.png";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="3rd";
try
{
//------------------ CLIENT REQUEST
Log.e(Tag,"Starting to bad things");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e(Tag,"File is written");
fileInputStream.close();
dos.flush();
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){
b.append( (char)ch );
}
String s=b.toString();
Log.i("Response",s);
dos.close();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
}
}
Many of the headers included in the above file is not required, i was trying and failing :).
Now to upload file here is the java code from my activity class
public void uploadFile(){
try {
FileInputStream fis =this.openFileInput(NAME_OF_FILE);
HttpFileUploader htfu = new HttpFileUploader("http://11.0.6.23/test2.php","noparamshere", NAME_OF_FILE);
htfu.doStart(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The main advantage is that the way it posts data to the server is similar to a Html Form posting data to a php server. Hope it might be useful for me in future, so i blogged it, if others are helped then that would be great.You can visit www.anddev.org for more and more tutorials. Thanks for reading my bad post :)
Labels: Android, file upload, php server
Tuesday, January 22, 2008
Did you ever fall in loop when traversing through activities, like one activity launching another and the other launching the previous one, then back pressing returns to that activity. This can be prevented very easily, when you think that the second activity is no more required, you just can call finish() function of that activity. This will solve some problems, though this looping happens only to bad programmers like me :D. Here is an interesting thing, when a subactivity finishes it's job it can send data back to the main activity who started it, for this the main activity has to override a function like this
@Override
protected void onActivityResult(int requestCode, int resultCode,
String data, Bundle extras) {
// TODO Auto-generated method stub
//super.onActivityResult(requestCode, resultCode, data, extras);
if(requestCode == SOME_INTEGER_WHICH_WAS_USED_DURING_CREATION_OF_ACTIVITY_AS_INTEGER_PARAM+OF_INTENT){
String text = "";
// This is a standard resultCode that is sent back if the
// activity doesn't supply an explicit result. It will also
// be returned if the activity failed to launch.
if (resultCode == RESULT_CANCELED) {
text ="Canceled";
// Our protocol with the sending activity is that it will send
// text in 'data' as its result.
} else {
if (data != null) {
text = data;
}
}
}
}
So when finish() function is called from subactivity, this function is called in mainActivity. This code is executed during returning from subactivity class.
setResult(RESULT_OK, "SOMETEXT");
finish();
Most of the codes are copied from APIDemos.
Labels: Activity return, Android
Launching an activity is not all. After launching another subactivity/activity you might want to send some data/parameter to that activity. This is done in a new way known as Bundle. To launch an activity we create an intent. Suppose our intent name is "intent". We can put data with the intent like this
intent.putExtra("keyName", "somevalue");
We can add multiple entries here. This is a key,value pair. So to receive this data from the receiving activity we have to write this code
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}
This is how we can send data to another activity, here simple string is sent, complex structures like array can be also sent through bundle. Didn't use those as i am a bad bad programmmer and very bad at reading documentations ;).
