Connection to xmpp gives Socket Exception (Permission denied) - java

i am trying to connect to openfire server through my android app using smack library. when i am connecting to server it gives me and error of
The following addresses failed: '192.168.0.31:5222' failed because java.net.SocketException: socket failed: EACCES (Permission denied)
However i have given a permission of Internet in my manifest.
The code i am using is..
public void init(String mUsername, String mPassword) {
Log.i(TAG, "connect()");
config = XMPPTCPConnectionConfiguration.builder();
config.setServiceName(mServiceName);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setHost(mServiceName);
config.setPort(5222);
config.setDebuggerEnabled(true);
config.setResource("sender");
// config.setCompressionEnabled(true);
config.setUsernameAndPassword(mUsername, mPassword);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
mConnection = new XMPPTCPConnection(config.build());
mConnection.addConnectionListener(this);
ChatManager.getInstanceFor(mConnection).addChatListener(this);
gson = new Gson();
connectAndLoginAnonymously();
}
public void connectAndLoginAnonymously() {
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
mConnection.connect();
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(mConnection);
dm.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(final String fromid,
final String toid, final String msgid,
final Stanza packet) {
}
});
mConnection.login();
} catch (SmackException | XMPPException | IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
}
};
// execute AsyncTask
mRegisterTask.execute();
}
public void disconnect() {
Log.i(TAG, "disconnect()");
if (mConnection != null) {
mConnection.disconnect();
}
}
//For Creating new User.
public boolean createNewAccount(String username, String newpassword) {
boolean status = false;
if (mConnection == null) {
try {
mConnection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
try {
// String newusername = username + mConnection.getServiceName();
Log.i("service", mConnection.getServiceName());
AccountManager accountManager = AccountManager.getInstance(mConnection);
accountManager.createAccount(username, newpassword);
status = true;
} catch (SmackException.NoResponseException e) {
status = false;
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
status = false;
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
status = false;
}
mConnection.disconnect();
return status;
}
From my login Activity when i am calling smackConnection.init(user,password);
it gives me the error of java.net.SocketException permission denied.
The error log is as below.
04-05 18:28:18.142 9575-9575/dhaval.com.chatdemo I/SMACK: connect()
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err:
org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: '192.168.0.31:5222' failed because java.net.SocketException: socket failed: EACCES (Permission denied)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectUsingConfiguration(XMPPTCPConnection.java:605)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectInternal(XMPPTCPConnection.java:839)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at org.jivesoftware.smack.AbstractXMPPConnection.connect(AbstractXMPPConnection.java:365)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at dhaval.com.chatdemo.SmackConnection$1.doInBackground(SmackConnection.java:104)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at dhaval.com.chatdemo.SmackConnection$1.doInBackground(SmackConnection.java:100)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-05 18:28:18.152 9575-9604/dhaval.com.chatdemo W/System.err: at java.lang.Thread.run(Thread.java:841)
Manifest code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dhaval.com.chatdemo">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CreateAccountPage"></activity>
</application>
am i doing anything wrong here? any help would be much appreciated.

Hopefully, you are missing uses-permission INTERNET in your manifest.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Related

Error in Google Play Services: read failed: EPERM (Operation not permitted)

Here is the LogCat error I am getting:
android java.io.IOException: read failed: EPERM (Operation not permitted)
at libcore.io.IoBridge.read(IoBridge.java:435)
The error is given in the following code, where I am trying to register a device using AsyncTask:
private void registerInBackground(){
mRegisterIdTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regId;
/* TODO : Send regId to backend to store in database so backend can send...
TODO : ...push notification request to GooglePlayMessaging
*/
sendRegistrationIdToBackend();
storeRegistrationId(context, regId);
} catch (IOException e) {
msg = "Error : " + e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i("Google Play", "Status : Finished ");
mRegisterIdTask = null;
}
}.execute(null, null, null);
}
Well now I'm getting this and I haven't changed anything.
05-15 17:33:35.253 16020-16271/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.panicsystems.kyuubi.legalpanicpartner, PID: 16020
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.SecurityException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (has extras) } without permission com.google.android.c2dm.permission.RECEIVE
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1603)
at android.app.ContextImpl.startService(ContextImpl.java:1580)
at android.content.ContextWrapper.startService(ContextWrapper.java:494)
at com.google.android.gms.gcm.GoogleCloudMessaging.zzs(Unknown Source)
at com.google.android.gms.gcm.GoogleCloudMessaging.register(Unknown Source)
at com.kyuubi.MainActivity$2.doInBackground(MainActivity.java:171)
at com.kyuubi.MainActivity$2.doInBackground(MainActivity.java:161)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
If you actually read the logs it is pretty clear what's the problem.
You are missing a required permission needed to use GCM.
Caused by: java.lang.SecurityException: Not allowed to start service
Intent { act=com.google.android.c2dm.intent.REGISTER
pkg=com.google.android.gms (has extras) } without permission
com.google.android.c2dm.permission.RECEIVE
Inside AndroidManifest.xml add:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
And make sure you have a GCM receiver registered
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- support pre-4.4 KitKat devices -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.company.app" />
</intent-filter>
</receiver>
and your service:
<service
android:name="com.company.app.service.GcmRegistrationIntentService"
android:exported="false" >
</service>

Android Handler Chain NullPointerException

I'm trying to create communication between Activity - Service - Thread by Handlers. Activity starts a Service that starts a Thread. Thread sends request to the server, waits answer and resend it to Service by Handler (work fine). But when i have try to send message from Service's Handler to Activity app closed with NullPointerException. What am i do wrong?
Handler code based on Android Handler changing WeakReference
My Activity
public class ActivityLogin extends Activity{
public static LoginHandler loginHandler = null;
public static class LoginHandler extends Handler {
private WeakReference<ActivityLogin> target = null;
LoginHandler(ActivityLogin target) {
this.target = new WeakReference<ActivityLogin>(target);
}
public void setTarget(ActivityLogin target) {
this.target.clear();
this.target = new WeakReference<ActivityLogin>(target);
}
#Override
public void handleMessage(Message msg) {
ActivityLogin activity = this.target.get();
if(activity == null) return;
String response = msg.getData().getString("RESPONSE");
System.err.println("RESPONSE "+response);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("TAG","---------------------APP STARTED---------------------");
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login);
if(loginHandler == null) loginHandler = new LoginHandler(this);
else loginHandler.setTarget(this);
}
public void onLogin(View v){
JsonUser user = new JsonUser();
user.login = "Name";
user.password = "Pazzword";
user.device = "4567-753-5768-2343";
Intent intent = new Intent(this,ComService.class);
intent.putExtra("DATA_KEY", new Gson().toJson(user));
this.startService(intent);
}
}
My Service
public class ComService extends Service {
public static ServiceHandler serviceHandler = null;
public static class ServiceHandler extends Handler {
private WeakReference<ComService> target = null;
ServiceHandler(ComService target) {
this.target = new WeakReference<ComService>(target);
}
public void setTarget(ComService target) {
this.target.clear();
this.target = new WeakReference<ComService>(target);
}
#Override
public void handleMessage(Message msg) {
//ComService service = this.target.get();
//Process message (msg) and resend to activity
ActivityLogin.loginHandler.sendMessage(msg);
}
}
#Override
public void onCreate() {
super.onCreate();
if(serviceHandler == null) serviceHandler = new ServiceHandler(this);
else serviceHandler.setTarget(this);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String message = intent.getStringExtra("DATA_KEY");
new SendData("http://xxx.xxx.xxx.xxx:27019/WebService.svc/login",message);
stopSelf(startId);
return START_REDELIVER_INTENT;
}
}
My Thread
public class SendData extends Thread {
private String requestUrl;
private String message;
public SendData(String requestUrl, String message){
super();
this.requestUrl = requestUrl;
this.message = message;
this.start();
}
public void run(){
String serverResponse = request();
if(serverResponse == null) return;
System.err.println(serverResponse);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("RESPONSE", serverResponse);
msg.setData(bundle);
ComService.serviceHandler.sendMessage(msg);
}
private String request(){...}//if need, i can post request code too
}
UPDATE
04-15 18:36:35.292 24524-24524/com.example.test E/Trace﹕ error opening trace file: No such file or directory (2)
04-15 18:36:35.332 24524-24524/com.example.test D/TAG﹕ ---------------------APP STARTED---------------------
04-15 18:36:35.462 24524-24524/com.example.test D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
04-15 18:36:35.462 24524-24524/com.example.test D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
04-15 18:36:35.462 24524-24524/com.example.test D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
04-15 18:36:35.492 24524-24524/com.example.test D/OpenGLRenderer﹕ Enabling debug mode 0
04-15 18:36:36.442 24554-24554/com.example.test:background E/Trace﹕ error opening trace file: No such file or directory (2)
04-15 18:36:36.682 24554-24567/com.example.test:background W/System.err﹕ {"status":{"success":false,"message":"some_text"},"result":null}
04-15 18:36:36.682 24554-24554/com.example.test:background D/AndroidRuntime﹕ Shutting down VM
04-15 18:36:36.682 24554-24554/com.example.test:background W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41712300)
04-15 18:36:36.682 24554-24554/com.example.test:background E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.test.ComService$ServiceHandler.handleMessage(ComService.java:31)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
AndroidManifext.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="14"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher"
android:theme="#android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
<activity android:name=".ActivityLogin"
android:label="#string/app_name"
android:windowSoftInputMode="stateHidden"
android:theme="#android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".ComService"
android:exported="false"
android:process=":background"
/>
</application>
</manifest>
In conclusion, i deleted Service from my application. Android Service is cancer tumor, threads without benefits. It's just my opinion.

Receive/Read emails in android

I am new to android.I want to build an app to receive & read emails from my own app.I prepared my code with help of these links & some blogs.
Retrieving all unread emails using javamail with POP3 protocol
https://buddhimawijeweera.wordpress.com/2011/02/09/sendreceiveemailsjava/
https://metoojava.wordpress.com/2010/03/21/java-code-to-receive-mail-using-javamailapi/
I have been working nearly for two weeks,but still app doesn't display the received emails.Please help me to find errors.Or else do you know a code to connect Gmail app with my app to receive emails ? Your any help for the app is greatly appreciated.
MailReaderActivity.java (Main Activity)
public class MailReaderActivity extends Activity{
Folder inbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public MailReaderActivity(){
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store;
store = session.getStore("imaps");
store.connect("imap.gmail.com","<user#gmail.com>","<password>");
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try {
printAllMessages(messages);
inbox.close(true);
store.close();
} catch (Exception ex) {
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
public void printAllMessages(Message[] msgs) throws Exception
{
for (int i = 0; i < msgs.length; i++)
{
System.out.println("MESSAGE #" + (i + 1) + ":");
printEnvelope(msgs[i]);
}
}
public void printEnvelope(Message message) throws Exception
{
Address[] a;
// FROM
if ((a = message.getFrom()) != null)
{
for (int j = 0; j < 2; j++)
{
System.out.println("FROM: " + a[j].toString());
}
}
// TO
if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
{
for (int j = 0; j < 2; j++)
{
System.out.println("TO: " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
String content = message.getContent().toString();
System.out.println("Subject : " + subject);
System.out.println("Received Date : " + receivedDate.toString());
System.out.println("Content : " + content);
getContent(message);
}
public void getContent(Message msg)
{
try
{
String contentType = msg.getContentType();
System.out.println("Content Type : " + contentType);
Multipart mp = (Multipart) msg.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
{
dumpPart(mp.getBodyPart(i));
}
}
catch (Exception ex)
{
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
}
public void dumpPart(Part p) throws Exception
{
// Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
{
is = new BufferedInputStream(is);
}
int c;
System.out.println("Message : ");
while ((c = is.read()) != -1)
{
System.out.write(c);
}
}
public static void main(String args[])
{
new MailReaderActivity();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MailReaderActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Logcat
//01-19 13:09:00.554 8487-8487/com.example.dell.frfr E/Trace﹕ error opening trace file: No such file or directory (2)
01-19 13:09:00.812 8487-8487/com.example.dell.frfr E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dell.frfr/com.example.dell.frfr.MailReaderActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getByName(InetAddress.java:289)
at java.net.InetSocketAddress.<init>(InetSocketAddress.java:105)
at java.net.InetSocketAddress.<init>(InetSocketAddress.java:90)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:116)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:115)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:685)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at com.example.dell.frfr.MailReaderActivity.<init>(MailReaderActivity.java:53)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1123)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
            at android.app.ActivityThread.access$600(ActivityThread.java:165)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
            at android.os.Handler.dispatchMessage(Handler.java:107)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5370)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)
//
I don't know if you have already fixed this error or not, but it may help people with a similar issue if i still answer it.
In your LogCat. It says Caused by: android.os.NetworkOnMainThreadException
Android by default will not let any networking on the same thread as the rest of the application. So, to fix this we just have to simply create a new thread to run it in.
Replace:
public static void main(String args[])
{
new MailReaderActivity();
}
with this:
public static void main(String args[])
{
Thread thread = new Thread() {
#Override
public void run() {
new MailReaderActivity();
}
};
thread.start();
}
You should execute network threads asynchronously using AsyncTask. For further information read the docs.

KitKat Connection from URL get NullPointerException in AsyncTask

i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
             at java.lang.Thread.run(Thread.java:841)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}

how to send an email?

I'm trying to develop an application to send an email from a specific email id. it won't execute and force close, why so ? And Is there any way to send email please have a look on my code.
public class MainActivity extends Activity {
Button send = null;
EditText mailid = null
String emailId = null;
ConnectivityManager conMan = null;
NetworkInfo Info = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button)findViewById(R.id.button1);
mailid = (EditText)findViewById(R.id.editText1);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
conMan = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Info = conMan.getActiveNetworkInfo();
emailId = mailid.getText().toString();
if (Info == null) {
Toast.makeText(getApplicationContext(), "no net connection ", Toast.LENGTH_LONG).show();
} else {
try {
GmailSender sender = new GmailSender("karuna.java#gmail.com", "heohiby");
sender.sendMail("This is Subject",
"This is Body how r u ..",
"karuna.java#gmail.com",
emailId);
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
}
});
}
}
here the GmailSender
public class GmailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new com.provider.JSSEProvider());
}
public GmailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients)throws Exception {
try {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
} catch (Exception e) {}
}
public class ByteArrayDataSource implements DataSource {
private byte[]data;
private String type;
public ByteArrayDataSource(byte[]data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[]data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream()throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream()throws IOException {
throw new IOException("Not Supported");
}
}
}
and the provider
public final class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction < Void > () {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
log file
12-19 11:07:43.363: E/AndroidRuntime(977): at dalvik.system.NativeStart.main(Native Method)
12-19 11:10:55.453: D/AndroidRuntime(1035): Shutting down VM
12-19 11:10:55.453: W/dalvikvm(1035): threadid=1: thread exiting with uncaught exception (group=0x40015578)
12-19 11:10:55.464: E/AndroidRuntime(1035): FATAL EXCEPTION: main
12-19 11:10:55.464: E/AndroidRuntime(1035): java.lang.NoClassDefFoundError: com.yakshna.mail.GmailSender
12-19 11:10:55.464: E/AndroidRuntime(1035): at com.yakshna.mail.MainActivity$1.onClick(MainActivity.java:42)
12-19 11:10:55.464: E/AndroidRuntime(1035): at android.view.View.performClick(View.java:2538)
12-19 11:10:55.464: E/AndroidRuntime(1035): at android.view.View$PerformClick.run(View.java:9152)
12-19 11:10:55.464: E/AndroidRuntime(1035): at android.os.Handler.handleCallback(Handler.java:587)
12-19 11:10:55.464: E/AndroidRuntime(1035): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 11:10:55.464: E/AndroidRuntime(1035): at android.os.Looper.loop(Looper.java:123)
12-19 11:10:55.464: E/AndroidRuntime(1035): at android.app.ActivityThread.main(ActivityThread.java:3687)
12-19 11:10:55.464: E/AndroidRuntime(1035): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 11:10:55.464: E/AndroidRuntime(1035): at java.lang.reflect.Method.invoke(Method.java:507)
12-19 11:10:55.464: E/AndroidRuntime(1035): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
12-19 11:10:55.464: E/AndroidRuntime(1035): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
12-19 11:10:55.464: E/AndroidRuntime(1035): at dalvik.system.NativeStart.main(Native Method)
12-19 11:11:02.570: I/Process(1035): Sending signal. PID: 1035 SIG: 9
shows error here:
GmailSender sender = new GmailSender("karuna.java#gmail.com", "heohiby");
Your problem at the moment is that you haven't declared a <uses-permission> in the Android.manifest.
The method getActiveNetworkInfo() requieres ACCESS_NETWORK_STATE permission.
You need to put this in your Android.manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Are the correct permissions in the manifest?
also be sure to read this:
http://productforums.google.com/forum/#!msg/gmail/XD0C4sw9K7U/LpNXxFNnfgc
the permissions used to be:
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="googlecode.email.to.sms" android:versionCode="2"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Email2SMSActivity" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="5"
android:maxSdkVersion="8"
android:targetSdkVersion="7" />
<uses-permission
android:name="com.google.android.providers.gmail.permission.READ_GMAIL" />
<uses-permission
android:name="com.google.android.gm.permission.READ_GMAIL" />
<uses-permission
android:name="android.permission.GET_ACCOUNTS" />
</manifest>
I haven't worked with Gmail in a few in Android but hopefully this will help.

Categories