I am trying to create an XML file that will store the variable T1 or the TextOne EditText but I am unsure if I am doing it correctly in this code below. I am also trying to figure out how I can read the created xml file and display the T1 variable into another EditText.
package com.example.treasurehunt;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Xml;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CreateTreasure extends Activity {
//variables
EditText TextOne, TextTwo, TextThree, TextFour, TextFive;
Button SaveTreasure;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_treasure);
TextOne = (EditText) findViewById(R.id.EditTextOne);
final String T1 = TextOne.getText().toString();
SaveTreasure = (Button) findViewById(R.id.SaveTreasuresButton);
//onclick
SaveTreasure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String xmlFile="TreasureList";
FileOutputStream fileos;
try {
fileos = getApplicationContext().openFileOutput(xmlFile, Context.MODE_APPEND);
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8",true);
xmlSerializer.startTag(null, "TreasureList");
xmlSerializer.startTag(null, "TreasureOne");
xmlSerializer.text(T1);
xmlSerializer.endTag(null,"TreasureOne");
xmlSerializer.endTag(null, "TreasureList");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite=writer.toString();
fileos.write(dataWrite.getBytes());
fileos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_treasure, menu);
return true;
}
}
Related
I am trying to call execute method of a GetMethodExample class which has extended AsyncTask, but it is showing me the error that the method execute is undefined for the GetMethodExapmle. Here is my code.
GetMethodExample.java:
package com.shehryar.httpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class GetMethodExample extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website= new URI(params[0]);
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
return data;
} catch (Exception e) {
{
e.printStackTrace();
}
}
}
}
return null;
}
}
//MainActivity
HttpExample.java:
package com.shehryar.httpclient;
import java.util.concurrent.ExecutionException;
import com.shehryar.httpclient.R.layout;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HttpExample extends Activity {
TextView httpstuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpstuff=(TextView) findViewById(R.id.tvhttp);
String data;
String website="http://www.google.com";
String extra="";
try {
GetMethodExample obj= new GetMethodExample();
data=obj.execute(website).get(); //Here is the error
httpstuff.setText(data);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
httpstuff.setText("Error:" + e.toString());
} catch (ExecutionException e) {
// TODO Auto-generated catch block
httpstuff.setText("Error:" + e.toString());
}
}
}
data=obj.execute(website).get(); //Here is the error
You are trying to get the data synchronously from an AsyncTask.
First, you start the task:
obj.execute(website);
Then you override onPostExecute() in your AsyncTask to handle the finish:
#Override
public void onPostExecute(String data) {
httpstuff.setText(data);
}
Now somehow you have to give the AsyncTask a reference to your Activity or your TextView so that you can update the UI in onPostExecute().
Go read the reference docs on AsyncTask to understand how the threads interact and which methods run on which thread.
AsyncTask | Android Developers
Thanks to Kris Larson for reply but I got my code working just after restarting eclipse. My code was fine but it was eclipse that was making problems
here is my Code
package com.example.messenger;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {
Button Send;
EditText IPAdresse;
EditText TEXT;
TextView RXtext,tstep,rstep;
private static final int TIMEOUT_MS = 1000;
private static final int server_port = 13011;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
IPAdresse = (EditText) findViewById(R.id.etIPAdresse);
IPAdresse.setText("192.168.2.32");
TEXT = (EditText) findViewById(R.id.etTEXT);
Send = (Button) findViewById(R.id.bSendaa);
RXtext = (TextView) findViewById(R.id.tvRXtext);
tstep = (TextView) findViewById(R.id.tvTstep);
rstep = (TextView) findViewById(R.id.tvRstep);
Send.setOnClickListener(this);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String text;
byte[] message = new byte[1500];
DatagramSocket s;
while(true){
try {
s= new DatagramSocket(server_port);
rstep.setText("1");
s.setBroadcast(true);
rstep.setText("2");
s.setSoTimeout(TIMEOUT_MS);
rstep.setText("3");
while(true){
DatagramPacket p = new DatagramPacket(message, message.length);
rstep.setText("4");
//InetAddress test = InetAddress.getByName("192.168.1.101");
//rstep.setText("5");
//s.connect(test,12345);
//rstep.setText("6");
s.receive(p);
rstep.setText("xxx");
text = new String(message, 0, p.getLength());
RXtext.setText(text);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
rstep.setText("fail socket create");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
rstep.setText("fail receive");
}
}
}
});
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bSendaa:
tstep.setText("1");
String messageStr= TEXT.getText().toString();
tstep.setText("2");
DatagramSocket s;
try {
s = new DatagramSocket();
tstep.setText("3");
s.setBroadcast(true);
tstep.setText("4");
s.setSoTimeout(TIMEOUT_MS);
tstep.setText("5");
InetAddress local = InetAddress.getByName(IPAdresse.getText().toString());
tstep.setText("6");
int msg_length=messageStr.length();
tstep.setText("7");
byte[] message = messageStr.getBytes();
tstep.setText("8");
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
tstep.setText("9");
s.connect(local,server_port);
tstep.setText("10");
s.send(p);
tstep.setText("sending complete");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tstep.setText("sending failed");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
My android phone's Ip is 192.168.2.32 , I saw it in wifi settings. So when I debug it row by row , I saw that my virtual device sent the packet , but I don't know why my phone can't get it. Can anybody help me?
Thanks
Regards
now it works , I didn't call start() function for thread , and I should change the UI from runOnUiThread , but it worked only from device to device, not from Virtual Device to Device, so here is the working code
package com.example.messenger;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {
Button Send;
EditText IPAdresse;
EditText TEXT;
TextView RXtext,tstep,rstep;
private static final int TIMEOUT_MS = 10000;
private static final int server_port = 13011;
String mMessage;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
IPAdresse = (EditText) findViewById(R.id.etIPAdresse);
IPAdresse.setText("192.168.2.32");
TEXT = (EditText) findViewById(R.id.etTEXT);
Send = (Button) findViewById(R.id.bSendaa);
RXtext = (TextView) findViewById(R.id.tvRXtext);
tstep = (TextView) findViewById(R.id.tvTstep);
rstep = (TextView) findViewById(R.id.tvRstep);
Send.setOnClickListener(this);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String text;
byte[] message = new byte[4];
DatagramSocket s;
try {
s= new DatagramSocket(server_port);
s.setSoTimeout(TIMEOUT_MS);
while(true){
try {
DatagramPacket p = new DatagramPacket(message, message.length);
s.receive(p);
mMessage = new String(message, 0, p.getLength());
runOnUiThread(new Runnable() {
#Override
public void run() {
RXtext.setText(mMessage);
}
});
}
catch(Exception e) {
e.printStackTrace();
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//rstep.setText("fail socket create");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//rstep.setText("fail receive");
}
}
}).start();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bSendaa:
String messageStr= TEXT.getText().toString();
DatagramSocket s;
try {
s = new DatagramSocket();
s.setBroadcast(true);
s.setSoTimeout(TIMEOUT_MS);
InetAddress local = InetAddress.getByName(IPAdresse.getText().toString());
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
//s.connect(local,server_port);
s.send(p);
tstep.setText("sending complete");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tstep.setText("sending failed");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Hi guys im trying to create a application that uses a socket connection i was going across some examples, the piece of code below works fine when i run it on 2.3.3 and the same crashes in 3.0.
package com.simple.client;
import android.app.Activity;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Bundle;
public class SimpleClientActivity extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("172.16.2.172", 8899);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
I have tried all but not able to figure out what is happening,
My guess is, the error caused by StrictMode.ThreadPolicy. In android 3.0, you can't access network in the same UI thread.
Do you have multiple resource folders for your layouts? if yes, maybe you do not have its related layout.
I'm trying to permanently store three strings as user preferences for my Android application. These three strings are a url, username, and password. I don't really understand SharedPreferences, so I tried to use internal file storage. I'm not able to retrieve the three strings from the file, and I get a runtime error. I know I probably coded something wrong, but I'm just not proficient enough in Android to understand data storage. Could somebody help me out?
Preferences activity:
package com.amritayalur.mypowerschool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
FileOutputStream fos;
String url = "";
String FILENAME = "InternalStrings";
String str;
String username;
String password;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
textViewTitle = (TextView) findViewById(R.id.textViewTitle);
textViewDesc = (TextView) findViewById(R.id.textViewDesc);
editTextURL = (EditText) findViewById(R.id.editTextURL);
editTextUser = (EditText) findViewById(R.id.editTextUser);
editTextPass = (EditText) findViewById(R.id.editTextPass);
//Start TextView
textViewTitle.setText("MyPowerSchool");
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//button listener
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if ( ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) )
{
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
//Saving data via File
/* File f = new File(FILENAME);
try {
fos = new FileOutputStream(f);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(url.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(username.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(password.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);
//i.putExtra("pschoolurl", editTextURL.getText().toString());
//i.putExtra("pschooluser", editTextUser.getText().toString());
//i.putExtra("pschoolpass", editTextPass.getText().toString());
// get the text here
final int result = 1;
startActivityForResult(i, result);
}
};
});}}
Activity in which I am trying to retrieve credentials:
package com.amritayalur.mypowerschool;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class creds extends Activity {
String url;
String username;
String password;
TextView TextViewTest;
String FILENAME = "InternalStrings";
;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent intent = getIntent();
//String url = intent.getExtras().getString("pschoolurl");
//String username = intent.getExtras().getString("pschooluser");
//String password = intent.getExtras().getString("pschoolpass");
String collected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1 ){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
TextViewTest.setText(collected);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The commented text is a result of me trying to mess around with different aspects of the code.
SharedPreferences is not too difficult.
To add something to the preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
Editor edit = prefs.edit(); //Needed to edit the preferences
edit.putString("name", "myname"); //add a String
edit.putBoolean("rememberCredentials", true); //add a boolean
edit.commit(); // save the edits.
To read something:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
String name = prefs.getString("name", "defaultName"); //get a String
boolean rememberCredentials = prefs.getBoolean("rememberCredentials", true); //get a boolean.
//When the key "rememberCredentials" is not present, true is returned.
parse .ics Calendar file using Ical4J in android.i saw the http://ical4j.sourceforge.net/introduction.html. How to use that ical4j-1.0-rc3.jar file in my project.I need help related to this plz ?
Hey , Just config list of jar files in your project as below :
ical4j-1.0.3.jar
commons-logging-1.1.1.jar
commons-lang-2.6.jar
commons-io-2.1.jar
commons-codec-1.5.jar
backport-util-concurrent-3.1.jar
Hope that's help you ..!
Here is Sample Code for you :
package com.example.caltest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.util.GregorianCalendar;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.model.ParameterList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.TimeZone;
import net.fortuna.ical4j.model.TimeZoneRegistry;
import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.Encoding;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.Attach;
import net.fortuna.ical4j.model.property.Attendee;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.util.UidGenerator;
import org.apache.commons.io.output.ByteArrayOutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file = new File(Environment.getExternalStorageDirectory()+"/1.ics");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = null;
try {
calendar = builder.build(fin);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (calendar != null) {
System.out.println("value :"+calendar);
PropertyList plist = calendar.getProperties();
for (Object object : plist.toArray()) {
System.out.println("oj :"+object);
}
}
// Generate Event of Christmas Day
Calendar mycalendar = new Calendar();
mycalendar.getProperties().add(new ProdId("-//James Bond//iCal4j 1.0//EN"));
mycalendar.getProperties().add(Version.VERSION_2_0);
mycalendar.getProperties().add(CalScale.GREGORIAN);
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TimeZone timezone = registry.getTimeZone("Asia/Calcutta");
VTimeZone tz = timezone.getVTimeZone();
java.util.Calendar startEvent = new GregorianCalendar();
startEvent.setTimeZone(timezone);
startEvent.set(java.util.Calendar.MONTH, java.util.Calendar.JULY);
startEvent.set(java.util.Calendar.DAY_OF_MONTH, 21);
startEvent.set(java.util.Calendar.YEAR, 2012);
startEvent.set(java.util.Calendar.HOUR, 9);
startEvent.set(java.util.Calendar.MINUTE, 15);
startEvent.set(java.util.Calendar.SECOND, 12);
java.util.Calendar entEvent = new GregorianCalendar();
entEvent.setTimeZone(timezone);
entEvent.set(java.util.Calendar.YEAR, 2012);
entEvent.set(java.util.Calendar.MONTH, java.util.Calendar.JULY);
entEvent.set(java.util.Calendar.DAY_OF_MONTH, 21);
entEvent.set(java.util.Calendar.HOUR, 16);
entEvent.set(java.util.Calendar.MINUTE, 10);
entEvent.set(java.util.Calendar.SECOND, 10);
// initialise as an all-day event..
VEvent christmas = new VEvent(new Date(startEvent.getTime()),new Date(entEvent.getTime()), "Shravan Mahino");
christmas.getProperties().add(tz.getTimeZoneId());
// Generate a UID for the event..
UidGenerator ug = null;
try {
ug = new UidGenerator("2");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
christmas.getProperties().add(ug.generateUid());
mycalendar.getComponents().add(christmas);
Attendee dev1 = new Attendee(URI.create("mailto:ashok#vervesys.local"));
dev1.getParameters().add(Role.REQ_PARTICIPANT);
dev1.getParameters().add(new Cn("For Ashok"));
christmas.getProperties().add(dev1);
Attendee dev2 = new Attendee(URI.create("mailto:jigarp#vervesys.com"));
dev2.getParameters().add(Role.OPT_PARTICIPANT);
dev2.getParameters().add(new Cn("For Jigar P"));
christmas.getProperties().add(dev2);
FileInputStream fileattach = null;
try {
fileattach = new FileInputStream(Environment.getExternalStorageDirectory()+"ic_launcher_home.png");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
for (int i = fileattach.read(); i >= 0;) {
bout.write(i);
i = fileattach.read();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParameterList params = new ParameterList();
params.add(Value.BINARY);
params.add(Encoding.BASE64);
Attach attach = new Attach(params, bout.toByteArray());
VEvent eout = (VEvent) calendar.getComponent(Component.VEVENT);
Attach aout = (Attach) eout.getProperty(Property.ATTACH);
System.out.println("Result : "+GenerateICAL("Ashok.ics", mycalendar));
}
public Boolean GenerateICAL(String fileNameWithExtenion,Calendar calendar){
FileOutputStream fout = null;
try {
fout = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+fileNameWithExtenion);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
CalendarOutputter outputter;
try {
outputter = new CalendarOutputter();
outputter.output(calendar, fout);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (ValidationException e) {
e.printStackTrace();
return false;
}
}
}