In socket programming exe file memory increasing gradually and also socket remain open - sockets

When received sting from multiple client at time some socket remain open so created mis file size increasing gradually so at time exe file become 2 GB from 35 kb so how can i reduce open sockect
private void Server_Load(object sender, EventArgs e)
{
try
{
this.tcpListener = new TcpListener(IPAddress.Any, port);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
catch (Exception ex)
{ }
finally
{
if (this.tcpListener != null)
{
this.tcpListener.Stop();
}
}
}
Mangae Client request by server continuously from load method
private void ListenForClients()
{
TcpClient client = null;
try
{
this.tcpListener.Start();
while (true)
{
client = this.tcpListener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClientComm),
client);
}
}
catch (Exception ex)
{
LogHelperISPL.Logger.Info("ListenForClients: " + ex.Message);
this.tcpListener.Stop();
}
finally
{
if(this.tcpListener != null)
{
this.tcpListener.Stop();
}
if (client != null)
{
client.Close();
}
}
}
Take data from client and insert into table and mange pass tcpclient and networkstream with close connection
private void HandleClientComm(object client)
{
TcpClient tcpClient = null;
NetworkStream clientStream = null;
try
{
tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
string InsertedRecord = string.Empty;
byte[] messageBytes = new byte[4096];
int bytesRead;
bool end = false;
while (!end)
{
bytesRead = 0;
try
{
if (clientStream != null)
{
bytesRead = clientStream.Read(messageBytes, 0,
messageBytes.Length);
}
}
catch (SocketException ex)
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
break;
}
catch (Exception ex)
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
break;
}
if (bytesRead <= 0)
{
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
string Datareceived = encoder.GetString(messageBytes, 0, bytesRead);
if (!string.IsNullOrEmpty(Datareceived))
{
string[] Multistrings = Datareceived.Split('!');
for (int i = 0; i < Multistrings.Length; i++)
{
if (!string.IsNullOrEmpty(Multistrings[i]))
{
if (Multistrings[i].Length >= 90)
{
InsertedRecord = InsertRawData(Multistrings[i]);
}
else
{
InsertedRecord =
InsertRawDataGarbage(Multistrings[i]);
}
}
}
}
}
}
catch (Exception ex)
{
LogHelperISPL.Logger.Info("While loop: " + ex.Message);
}
finally
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
}
}

Related

Whether to use Flowable.create or Flowable.generate to make a file observable?

From https://github.com/ReactiveX/RxJava/wiki/Backpressure-(2.0)
the following snippet is provide to indicate correct usage for RXified file reading.
Flowable<Integer> o = Flowable.generate(
() -> new FileInputStream("data.bin"),
(inputstream, output) -> {
try {
int byte = inputstream.read();
if (byte < 0) {
output.onComplete();
} else {
output.onNext(byte);
}
} catch (IOException ex) {
output.onError(ex);
}
return inputstream;
},
inputstream -> {
try {
inputstream.close();
} catch (IOException ex) {
RxJavaHooks.onError(ex);
}
}
);
I am doing the following
public Flowable<byte[]> createFlowable(File file) {
return Flowable.create(source -> {
try (FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin)) {
while (in.available() > 0) {
byte[] data = getMessageRawData(in);
source.onNext(data);
}
source.onComplete();
}
catch (Exception ex) {
source.onError(ex);
}
}, BackpressureStrategy.BUFFER);
}
Does my code (uses try with resource) suffer from resource leakage if dispose is called mid way or what other side effects can be expected or is it just a different way of doing things?

contacts insert ,app died ,no save state

this is log:
08-28 13:50:47.648: A/libc(1010): ### ABORTING: INVALID HEAP ADDRESS IN dlfree addr=0x2a26bc90
08-28 13:50:47.648: A/libc(1010): Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 1020 (FinalizerDaemon)
08-28 13:50:48.698: W/ActivityManager(149): Scheduling restart of crashed service com.android.KnowingLife/.PushNotification.NotificationService in 5000ms
08-28 13:50:48.698: W/ActivityManager(149): Force removing ActivityRecord{412a2c70 com.android.KnowingLife/.PhoneSynActivity}: app died, no saved state
08-28 13:50:48.807: W/GpsLocationProvider(149): Unneeded remove listener for uid 1000
08-28 13:50:49.257: E/Trace(1064): error opening trace file: No such file or directory (2)
08-28 13:50:50.017: W/GpsLocationProvider(149): Duplicate add listener for uid 10044
08-28 13:50:52.827: W/InputMethodManagerService(149): Got RemoteException sending setActive(false) notification to pid 1010 uid 10044
I run it in my emulator( version 4.1),and I am bulk inserting contacts to local .It works well usual,but I got 600 more contacts to
insert to local ,it doesn't work when insert to about 6%.I don't know
how to show it to you ,this is my code ,look this, you will see the
problem,thank
/**
* insert
*/
class InsertContactsTask extends AsyncTask<Void, Integer, Integer> {
String detail;
public InsertContactsTask(String detail) {
this.detail = detail;
}
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(PROGRESS_DIALOG);
}
#Override
protected Integer doInBackground(Void... params) {
String[] itemRecord = detail.split(ParseData.getInstance()
.getRecordSplitFalg(), -1);
int count = itemRecord.length;
wait_Dialog.setMax(count);
ArrayList<ContentProviderOperation> contentOper = null;
contentOper = new ArrayList<ContentProviderOperation>();
for (int i = 0; i < itemRecord.length; i++) {
int rawContactInsertIndex = contentOper.size();
String[] item = null;
try {
item = itemRecord[i].split(ParseData.getInstance()
.getFiledSplitFlag(), -1);
contentOper.add(ContentProviderOperation
.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
contentOper.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, item[0])
.build());
for (int j = 1; j < item.length; j++) {
if (item[j].startsWith("1")) {
String phoneType = item[j].substring(1, 2);
int iType;
String label = null;
if (phoneType.compareToIgnoreCase("a") >= 0)
iType = phoneType.compareToIgnoreCase("a") + 10;
else
iType = Integer.parseInt(phoneType);
if (iType == 0)
label = item[j + 1];
contentOper
.add(ContentProviderOperation
.newInsert(
android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER,
item[j].substring(2))
// "data1"
.withValue(Phone.TYPE, iType)
.withValue(Phone.LABEL, label)
.build());
if (iType == 0)
j++;
} else {
String emailType = item[j].substring(1, 2);
int iEmailType = Integer.parseInt(emailType);
String emailLabel = null;
if (iEmailType == 0)
emailLabel = item[j + 1];
contentOper
.add(ContentProviderOperation
.newInsert(
android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE,
Email.CONTENT_ITEM_TYPE)
.withValue(Email.DATA,
item[j].substring(2))
.withValue(Email.TYPE, iEmailType)
.withValue(Email.LABEL, emailLabel)
.build());
if (iEmailType == 0)
j++;
}
}
int iUpdate = i + 1;
if (iUpdate % 20 == 0 || iUpdate == itemRecord.length) {
try {
#SuppressWarnings("unused")
ContentProviderResult[] results = PhoneSynActivity.this
.getContentResolver().applyBatch(
ContactsContract.AUTHORITY,
contentOper);
contentOper.clear();
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
publishProgress(i);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return count;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
wait_Dialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer count) {
super.onPostExecute(count);
wait_Dialog.dismiss();
txt_count.setText( count+ "");
Toast.makeText(PhoneSynActivity.this,
R.string.string_download_suc, Toast.LENGTH_LONG).show();
}
}

java.net.UnknownHostException: cs.xfire.com

I am trying to establish a connection from an android xfire client, its a TCP connection I believe. I have googled everywhere and it has been said over and over again to use cs.xfire.com on port 25999 to connect to xfire (a messaging service). But at the end I get an exception saying it doesnt connect. So I would like to know why can I not establish a connection. There is almost no information on the internet that would help me figure out why it won't connect, I have listened to the connection via packet sniffers and they have given me port 25999 aswell right when I click on "connect" from the official xfire windows app. So I am really confused, sorry if this question is not making much sense, here is the code of what I have:
public class Connectionn extends Activity{
private DataInputStream in = null;
private DataOutputStream out = null;
private byte[] buffer;
private String username, password, nickname, statustext = "Online";
private boolean runThread = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connected);
TextView txtView1 = (TextView) findViewById(R.id.tvTest);
Bundle extras = getIntent().getExtras();
String username = extras.getString("username");
String password = extras.getString("password");
try {
Socket s = new Socket("cs.xfire.com", 25999);
txtView1.setText("Connected!");
in = new DataInputStream(s.getInputStream());
out = new DataOutputStream(s.getOutputStream());
login();
} catch (IOException ioe) {
//disconnect();
txtView1.setText(ioe.toString());
}
}
public void run() {
setTitle("Xfire Reader Thread");
while(runThread) {
readBytes();
debug(buffer);
switch(buffer[0] & 0xFF) {
case 0x80: // salt
break;
case 0x81: // auth failed
disconnect();
break;
case 0x82: // loginreply
break;
case 0x83: // friendslist
break;
case 0x84: // friend online
break;
case 0x85: // receive message
/*ReceiveMessagePacket rmp = new ReceiveMessagePacket(buffer);
if (rmp.getMessageType() == ReceiveMessagePacket.MSGTYPE_IM) {
AckImPacket amp =
new AckImPacket(rmp.getSid(), rmp.getImIndex());
write(amp.getBytes());
}*/
break;
case 0x87: // friend in game
break;
case 0x91: // disconnected with reason
disconnect();
break;
case 0x9a: // friend status text
break;
case 0xac:
break;
}
}
}
private void login() {
// TODO Auto-generated method stub
// initialize connection with the 'UA01' packet
write("UA01".getBytes());
// send the version packet
final byte[] p_version_1 = new byte[] {
0x03, 0, 0x01, 0x07,
0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, // version
0x02
};
final int version = 118;
String vp = null;
write(vp.getBytes());
// start the reader thread
onStart();
}
public void disconnect() {
//EventManager.removeObserver(this);
runThread = false;
try {
out.write(new byte[] { 0, 0, 0, 0 }); // sabotage the stream
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
out.close();
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
//FriendManager.getInstance().cleanup();
// EventManager.fireEvent(new DatalessEvent(XfireEvent.XF_OFFLINE));
}
}
private void readBytes() {
try {
byte[] numBytes = new byte[2];
in.read(numBytes, 0, 2);
int low = numBytes[0] & 0xFF, high = numBytes[1] & 0xFF;
int len = (0x00 | low | (high << 8)) - 2;
if (len <= 0) {
buffer = new byte[] { 0 };
return;
}
buffer = new byte[len];
in.read(buffer, 0, len);
} catch (IOException ioe) {
ioe.printStackTrace();
disconnect();
}
}
private static void debug(byte[] bs) {
for (byte b : bs) {
System.out.print(String.format("%02x", b) + " ");
}
System.out.println();
}
public void write(byte[] bs) {
try {
out.write(bs);
} catch (IOException ioe) {
ioe.printStackTrace();
disconnect();
}
}
}
I get an exception saying it doesn't connect
No you don't. Read it again. It's in your title. It says 'unknown host'. That's not a connect failure: it's a lookup failure. Either cs.xfire.com doesn't exist or it isn't known to your DNS.

No login screen in Facebook integration in blackberry

I am working on an blackberry application in which I am using 3rd party application Facebook.
Now, my problem is when i post the message first time i will be redirected to facebook login screen and message posted .But once i logout from my application and login again to post message to facebook it posts message directly without asking for cerdential information.
The below code to login to facebook:
public class FacebookMain implements ActionListener{// extends MainScreen implements ActionListener {
// Constants
public final static String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
public final static String APPLICATION_ID ="261890490596037";
private final static long persistentObjectId = 0x854d1b7fa43e3577L;
//APPLICATION SECRET ID="f7e096af696ef81e72268f49a6381a8d"
static final String ACTION_ENTER = "updateStatus";
static final String ACTION_SUCCESS = "statusUpdated";
static final String ACTION_ERROR = "error";
private ActionScreen actionScreen;
private PersistentObject store;
private LoginScreen loginScreen;
private LogoutScreen logoutScreen;
private HomeScreen homeScreen;
private UpdateStatusScreen updateStatusScreen;
private RecentUpdatesScreen recentUpdatesScreen;
private UploadPhotoScreen uploadPhotoScreen;
private FriendsListScreen friendsListScreen;
private PokeFriendScreen pokeFriendScreen;
private PostWallScreen postWallScreen;
private SendMessageScreen sendMessageScreen;
private String postMessage;
private FacebookContext fbc;
public static boolean isWallPosted=false;
public FacebookMain(String postMessge) {
this.postMessage=postMessge;
checkPermissions();
init();
if ((fbc != null) && fbc.hasValidAccessToken()) {
/*homeScreen = new HomeScreen(fbc);
homeScreen.addActionListener(this);
UiApplication.getUiApplication().pushScreen(homeScreen);*/
try {
new FBUser("me", fbc.getAccessToken()).setStatus(postMessage);
actionScreen=new ActionScreen();
actionScreen.fireAction(ACTION_SUCCESS);
Dialog.alert("Wall Posted ");
isWallPosted=true;
//UiApplication.getUiApplication().popScreen(loginScreen);
} catch (Exception e) {
actionScreen.fireAction(ACTION_ERROR, e.getMessage());
//UiApplication.getUiApplication().popScreen(loginScreen);
}
} else {
loginScreen = new LoginScreen(fbc,postMessge);
loginScreen.addActionListener(this);
UiApplication.getUiApplication().pushScreen(loginScreen);
}
}
private void init() {
store = PersistentStore.getPersistentObject(persistentObjectId);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new FacebookContext(NEXT_URL, APPLICATION_ID));
store.commit();
}
}
fbc = (FacebookContext) store.getContents();
}
private void checkPermissions() {
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if ((original.getPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_INTERNET) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_EMAIL) == ApplicationPermissions.VALUE_ALLOW)) {
return;
}
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_AUTHENTICATOR_API);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_WIFI);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if (acceptance) {
// User has accepted all of the permissions.
return;
} else {
}
}
public void saveContext(FacebookContext pfbc) {
synchronized (store) {
store.setContents(pfbc);
System.out.println(pfbc);
store.commit();
}
}
public void logoutAndExit() {
saveContext(null);
logoutScreen = new LogoutScreen(fbc);
logoutScreen.addActionListener(this);
}
public void saveAndExit() {
saveContext(fbc);
exit();
}
private void exit() {
AppenderFactory.close();
System.exit(0);
}
public void onAction(Action event) {/*
if (event.getSource() == loginScreen) {
if (event.getAction().equals(LoginScreen.ACTION_LOGGED_IN)) {
try {
fbc.setAccessToken((String) event.getData());
try {
new FBUser("me", fbc.getAccessToken()).setStatus(postMessage);
actionScreen=new ActionScreen();
actionScreen.fireAction(ACTION_SUCCESS);
Dialog.alert("Wall Posted ");
} catch (Exception e) {
actionScreen.fireAction(ACTION_ERROR, e.getMessage());
}
try {
if (homeScreen == null) {
homeScreen = new HomeScreen(fbc);
homeScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(homeScreen);
} catch (Exception e) {
e.printStackTrace();
Dialog.alert("Error: " + e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
Dialog.alert("Error: " + t.getMessage());
}
} else if (event.getAction().equals(LoginScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == logoutScreen) {
if (event.getAction().equals(LogoutScreen.ACTION_LOGGED_OUT)) {
exit();
}
} else if (event.getSource() == homeScreen) {
if (event.getAction().equals(UpdateStatusScreen.ACTION_ENTER)) {
if (updateStatusScreen == null) {
updateStatusScreen = new UpdateStatusScreen(fbc);
updateStatusScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(updateStatusScreen);
try {
new FBUser("me", fbc.getAccessToken()).setStatus("");
actionScreen=new ActionScreen();
actionScreen.fireAction(ACTION_SUCCESS);
} catch (Exception e) {
actionScreen.fireAction(ACTION_ERROR, e.getMessage());
}
} else if (event.getAction().equals(RecentUpdatesScreen.ACTION_ENTER)) {
if (recentUpdatesScreen == null) {
recentUpdatesScreen = new RecentUpdatesScreen(fbc);
recentUpdatesScreen.addActionListener(this);
}
recentUpdatesScreen.loadList();
UiApplication.getUiApplication().pushScreen(recentUpdatesScreen);
} else if (event.getAction().equals(UploadPhotoScreen.ACTION_ENTER)) {
if (uploadPhotoScreen == null) {
uploadPhotoScreen = new UploadPhotoScreen(fbc);
uploadPhotoScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(uploadPhotoScreen);
} else if (event.getAction().equals(FriendsListScreen.ACTION_ENTER)) {
if (friendsListScreen == null) {
friendsListScreen = new FriendsListScreen(fbc);
friendsListScreen.addActionListener(this);
}
friendsListScreen.loadList();
UiApplication.getUiApplication().pushScreen(friendsListScreen);
} else if (event.getAction().equals(PokeFriendScreen.ACTION_ENTER)) {
if (pokeFriendScreen == null) {
pokeFriendScreen = new PokeFriendScreen(fbc);
pokeFriendScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(pokeFriendScreen);
} else if (event.getAction().equals(PostWallScreen.ACTION_ENTER)) {
if (postWallScreen == null) {
postWallScreen = new PostWallScreen(fbc);
postWallScreen.addActionListener(this);
}
postWallScreen.loadList();
UiApplication.getUiApplication().pushScreen(postWallScreen);
} else if (event.getAction().equals(SendMessageScreen.ACTION_ENTER)) {
if (sendMessageScreen == null) {
sendMessageScreen = new SendMessageScreen(fbc);
sendMessageScreen.addActionListener(this);
}
UiApplication.getUiApplication().pushScreen(sendMessageScreen);
}
} else if (event.getSource() == updateStatusScreen) {
if (event.getAction().equals(UpdateStatusScreen.ACTION_SUCCESS)) {
Dialog.inform("Status updated");
try {
UiApplication.getUiApplication().popScreen(updateStatusScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(UpdateStatusScreen.ACTION_SUCCESS)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == recentUpdatesScreen) {
if (event.getAction().equals(RecentUpdatesScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(recentUpdatesScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(RecentUpdatesScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == uploadPhotoScreen) {
if (event.getAction().equals(UploadPhotoScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(uploadPhotoScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(UploadPhotoScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == friendsListScreen) {
if (event.getAction().equals(FriendsListScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(friendsListScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(FriendsListScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == pokeFriendScreen) {
if (event.getAction().equals(PokeFriendScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(pokeFriendScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(PokeFriendScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == postWallScreen) {
if (event.getAction().equals(PostWallScreen.ACTION_SUCCESS)) {
Dialog.inform("Wall posted");
try {
UiApplication.getUiApplication().popScreen(postWallScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(PostWallScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
} else if (event.getSource() == sendMessageScreen) {
if (event.getAction().equals(SendMessageScreen.ACTION_SUCCESS)) {
try {
UiApplication.getUiApplication().popScreen(sendMessageScreen);
} catch (IllegalArgumentException e) {
}
} else if (event.getAction().equals(SendMessageScreen.ACTION_ERROR)) {
Dialog.alert("Error: " + event.getData());
}
}
*/}
}
and the below code to clear credential
public void logoutAndExit() {
saveContext(null);
logoutScreen = new LogoutScreen(fbc);
logoutScreen.addActionListener(this);
}

How can i attach multiple images with email in Blackberry?

I want to attach multiple images with email in BB. How can I do this? Does any body have an idea? please help me.Below is my code which works fine when i send only one image with email. so what modification should I make in my code for attaching multiple images.
public static void SendMailAttachment(Bitmap screenshot)
{
String htmlContent = "String" ;
try
{
Multipart mp = new Multipart();
Message msg = new Message();
Address[] addresses = {new Address("","")};
for (int i = 0; i<2 ; i++)
{
PNGEncodedImage img = PNGEncodedImage.encode(screenshot);
SupportedAttachmentPart pt = new SupportedAttachmentPart(mp, img.getMIMEType(),
"Weed.png", img.getData());
mp.addBodyPart(pt);
}
msg.setContent(mp);
msg.setContent(htmlContent);
msg.addRecipients(RecipientType.TO, addresses);
msg.setSubject("Subject");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(msg));
}
catch (AddressException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
catch (MessagingException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
}
Thanx in advance.
following code can be used to attach multiple images or files.
public void upload()
{
Multipart mp = new Multipart();
String fileName = null;
for (int i = 0; i<2 ; i++)
{
// Dialog.alert(image.);
byte[] stream = readStream("file:///SDCard/IMG00001-20110404-1119.JPEG");
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, MIMETypeAssociations.getMIMEType("IMG00001-20110404-1119.JPEG"),"IMG00001-20110404-1119.JPEG", stream);
mp.addBodyPart(sap);
}
TextBodyPart tbp = new TextBodyPart(mp,"test bodyString");
mp.addBodyPart(tbp);
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
Address[] toAdds = new Address[1];
try {
toAdds[0] = new Address("testmailid", null);
message.addRecipients(Message.RecipientType.TO,toAdds);
// message.setFrom(new InternetAddress(_from));
// message.addRecipients(Message.RecipientType.FROM,toAdds);
message.setContent(mp);
message.setSubject("test subject");
Transport.send(message);
Dialog.alert("message send successfully.");
} catch (AddressException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
} catch (MessagingException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
private byte[] readStream(String path)
{
InputStream in = null;
FileConnection fc = null;
byte[] bytes = null;
try
{
fc = (FileConnection) Connector.open(path);
if (fc !=null && fc.exists())
{
in = fc.openInputStream();
if (in !=null)
{
bytes = IOUtilities.streamToBytes(in);
}
}
}
catch(IOException e)
{
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch(IOException e)
{
}
try
{
if (fc !=null)
{
fc.close();
}
}
catch(IOException e)
{
}
}
return bytes;
}
i have used this code. it works fine.
Just create a new SupportedAttachmentPart for each image and add them to the message with the addBodyPart method.
Once the multipart is populated with the body part and the attachment parts, call msg.setContent(mp).