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.
Related
I am trying to integrate Stripe into my app. Once a user is created in my apps onboarding, they need to create an account with stripe to get payments. It keeps getting an error at
try {
accountLink = AccountLink.create(linkParams);
} catch (StripeException e) {
e.printStackTrace();
Log.e("LINK_PARAMS ERROR: ", e.toString());
}
The try{catch} is not catching the error so I am not seeing what exactly is going on. Can anyone shed some light on this for me? I just need to access the onboarding for Stripe, then redirect back to my app. I have read so many articles, I may have my wires crossed.
Android Manifest
<activity
android:name=".ui.stripeTools.ConnectWithStripeActivity"
android:label="#string/title_activity_connect_with_stripe"
android:theme="#style/Theme.Godsvong.NoActionBar"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSER"/>
<data
android:scheme="app"
android:host="godsvognapp.com"/>
</intent-filter>
</activity>
Activity Class:
public class ConnectWithStripeActivity extends AppCompatActivity {
private static final String RETURN_URL = "app://godsvognapp.com";
private OkHttpClient httpClient = new OkHttpClient();
private ActivityConnectWithStripeBinding binding;
private Account account = new Account();
private AccountLink accountLink = new AccountLink();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Stripe.apiKey = MainActivity.STRIPE_KEY;
Address address = new Address();
address.setLine1(MainActivity.mUser.getmAddress());
address.setCity(MainActivity.mUser.getmCity());
address.setState(MainActivity.mUser.getmState());
address.setPostalCode(MainActivity.mUser.getmZipCode());
Person individual = new Person();
individual.setAddress(address);
individual.setFirstName(MainActivity.mUser.getmFirstName());
individual.setLastName(MainActivity.mUser.getmLastName());
individual.setPhone(MainActivity.mUser.getmPhoneNumber());
individual.setEmail(MainActivity.mUser.getmEmailAddress());
account.setIndividual(individual);
AccountLinkCreateParams linkParams = AccountLinkCreateParams
.builder()
.setRefreshUrl(RETURN_URL)
.setReturnUrl(RETURN_URL)
.setType(AccountLinkCreateParams.Type.ACCOUNT_ONBOARDING)
.setCollect(AccountLinkCreateParams.Collect.EVENTUALLY_DUE)
.build();
try {
accountLink = AccountLink.create(linkParams);
} catch (StripeException e) {
e.printStackTrace();
Log.e("LINK_PARAMS ERROR: ", e.toString());
}
AccountCreateParams params = AccountCreateParams
.builder()
.setType(AccountCreateParams.Type.EXPRESS)
.build();
try {
account = Account.create(params);
} catch (StripeException e) {
e.printStackTrace();
Log.e("ACCOUNT ERROR: ", e.toString());
}
binding = ActivityConnectWithStripeBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Button connectWithStripe = (Button) findViewById(R.id.connect_with_stripe);
connectWithStripe.setOnClickListener(view -> {
WeakReference<Activity> weakActivity = new WeakReference<>(this);
Request request = new Request.Builder()
.url(accountLink.getUrl())
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), ""))
.build();
httpClient.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(#NotNull Response response) throws IOException {
final Activity activity = weakActivity.get();
if (activity == null) {
return;
}
if (response.isSuccessful()){
NavController navController = Navigation.findNavController(view);
navController.navigate(R.id.nav_home);
}
if (!response.isSuccessful() || response.body() == null) {
// Request failed
} else {
String body = response.body().string();
try {
JSONObject responseJson = new JSONObject(body);
String url = responseJson.getString(accountLink.getUrl());
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(view.getContext(), Uri.parse(url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
});
}
}
Here is the Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hsquaredtechnologies.godsvong, PID: 12735
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hsquaredtechnologies.godsvong/com.hsquaredtechnologies.godsvong.ui.stripeTools.ConnectWithStripeActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4037)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4203)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2440)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8641)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1133)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1668)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at com.android.okhttp.Dns$1.lookup(Dns.java:41)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:262)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:219)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:30)
at com.stripe.net.HttpURLConnectionClient.createStripeConnection(HttpURLConnectionClient.java:124)
at com.stripe.net.HttpURLConnectionClient.requestStream(HttpURLConnectionClient.java:33)
at com.stripe.net.HttpURLConnectionClient.request(HttpURLConnectionClient.java:68)
at com.stripe.net.HttpClient$$ExternalSyntheticLambda2.apply(Unknown Source:2)
at com.stripe.net.HttpClient.sendWithTelemetry(HttpClient.java:66)
at com.stripe.net.HttpClient.requestWithTelemetry(HttpClient.java:83)
at com.stripe.net.HttpClient.lambda$requestWithRetries$0$com-stripe-net-HttpClient(HttpClient.java:145)
at com.stripe.net.HttpClient$$ExternalSyntheticLambda1.apply(Unknown Source:2)
at com.stripe.net.HttpClient.sendWithRetries(HttpClient.java:109)
at com.stripe.net.HttpClient.requestWithRetries(HttpClient.java:145)
at com.stripe.net.LiveStripeResponseGetter.request(LiveStripeResponseGetter.java:58)
at com.stripe.net.ApiResource.request(ApiResource.java:181)
at com.stripe.net.ApiResource.request(ApiResource.java:171)
at com.stripe.model.AccountLink.create(AccountLink.java:73)
at com.stripe.model.AccountLink.create(AccountLink.java:63)
E/AndroidRuntime: at com.hsquaredtechnologies.godsvong.ui.stripeTools.ConnectWithStripeActivity.onCreate(ConnectWithStripeActivity.java:90)
at android.app.Activity.performCreate(Activity.java:8282)
at android.app.Activity.performCreate(Activity.java:8262)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4011)
... 12 more
I/Process: Sending signal. PID: 12735 SIG: 9
I have already read many similar questions, but I could not find a solution to the problem.
At first glance, I'm doing everything right, but the directory creation does not work for API 17 and low.
Manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
...
Cod
// скачиваем файл
public void downloadWallpaper(String url, String name) {
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String Download_ID = "PREF_DOWNLOAD_ID";
// проверяем наличие подключения
if (activeNetwork != null && activeNetwork.isConnected()) {
for (int z = 0; z < 1; z++) {
// проверяем был ли уже загружен файл
File file = new File(Environment.getExternalStorageDirectory() + "/LiveWallpapers/" + name);
if (!file.exists()) {
// загружаем файл, т.к. его нет
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
// назначаем имя для файла
request.setDestinationInExternalPublicDir("LiveWallpapers", name);
// сохраняем request id
SharedPreferences.Editor PrefEdit = preferenceManager.edit();
long id = downloadManager.enqueue(request);
PrefEdit.putLong(Download_ID, id);
PrefEdit.apply();
} else {
// такой файл уже есть
break;
}
for (int p = 0; p < 30; p++) {
// проверяем был ли уже загружен файл
if (!file.exists()) {
// ожидаем загрузки файла
try {Thread.sleep(1000);} catch (InterruptedException e) {}
} else {
// файл загрузился
try {Thread.sleep(1000);} catch (InterruptedException e) {}
break;
}
}
}
}
}
For API 18 and high its work (/storage/sdcard/LiveWallpapers/...)
For API 17 and low its not work (/mnt/sdcard/LiveWallpapers/...)
I also tried to create a directory manually
File folder = new File(Environment.getExternalStorageDirectory() + "/LiveWallpapers");
if (!folder.exists()) {
folder.mkdirs();
}
if (folder.exists()) {
...
}
The application downloads a file from the Internet and creates a directory LiveWallpapers. For API 14, 15, 16, 17 can not create directory.
LogCat
03-15 15:41:15.411 2059-2059/com.developer.skyline.livewallpapers E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Unable to create directory: /mnt/sdcard/LiveWallpapers
at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:496)
at com.developer.skyline.livewallpapers.LiveWallpaperService$GifEngine.downloadWallpaper(LiveWallpaperService.java:379)
at com.developer.skyline.livewallpapers.LiveWallpaperService$GifEngine.<init>(LiveWallpaperService.java:206)
at com.developer.skyline.livewallpapers.LiveWallpaperService.onCreateEngine(LiveWallpaperService.java:41)
at android.service.wallpaper.WallpaperService$IWallpaperEngineWrapper.executeMessage(WallpaperService.java:1012)
at com.android.internal.os.HandlerCaller$MyHandler.handleMessage(HandlerCaller.java:61)
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)
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>
Thing is my application used to run PERFECTLY but then i wanted to change packages names and classes names so i created another project and copy pasted my code and did the changes there. no error in eclipse but app crashes now !! here's whats my app is about:
public class LocationMobileUser implements LocationListener {
Context gContext;
boolean gps_enabled=false;
boolean network_enabled=false;
public LocationMobileUser(Context gContext){
this.gContext = gContext;
}
public static final String URL =
"http://www.ip2phrase.com/ip2phrase.asp?template=%20%3CISP%3E";
public void XML (View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
public class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
public String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
int x =1;
try {
InputStream stream = getHttpConnection(url);
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(stream));
String line = "";
int lineNo;
for (lineNo = 1; lineNo < 90; lineNo++) {
if (lineNo == x) {
line = lnr.readLine();
//output.append(line);
Pattern p = Pattern.compile(">(.*?)<");
Matcher m = p.matcher(line);
if (m.find()) {
output.append(m.group(1)); // => "isp"
}
} else
lnr.readLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
public InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
public String getSimOperator() {
TelephonyManager telephonyManager = (TelephonyManager)gContext.getSystemService(Context.TELEPHONY_SERVICE);
String operator = telephonyManager.getSimOperatorName();
return operator;
}
public GsmCellLocation getCellLocation() {
//String Context=Context.Telephony_SERVICE;
TelephonyManager telephonyManager = (TelephonyManager)gContext.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation CellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
return CellLocation;
}
public Location getLocation(){
String provider = null;
LocationManager locationManager;
Location gps_loc=null;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)gContext.getSystemService(context);
gps_loc=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
if(gps_enabled && gps_loc != null){
provider = LocationManager.GPS_PROVIDER;
}
else{
provider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
return location;
}
public String getProvider(Location location){
String provider = null;
LocationManager locationManager;
Location gps_loc=null;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)gContext.getSystemService(context);
gps_loc=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
if(gps_enabled && gps_loc != null ){
provider = LocationManager.GPS_PROVIDER;
}
else{
provider = LocationManager.NETWORK_PROVIDER;
}
return provider;
}
public String CellLacLocation(GsmCellLocation CellLocation){
String cidlacString;
if (CellLocation != null) {
int cid = CellLocation.getCid();
int lac = CellLocation.getLac();
cidlacString = "CellID:" + cid + "\nLAC:" + lac;}
else {
cidlacString="No Cell Location Available";
}
return cidlacString;
}
public String updateWithNewLocation(Location location) {
String latLongString;
if (location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Latitude:" + lat + "\nLongitude:" + lng;
}else{
latLongString = "No Location available";
}
return latLongString;
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
this app will be exported into a JAR file and then included into another app as a library using build path; and here's what i wrote in this new app:
public class LocationTheApp extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationMobileUser LMU = new LocationMobileUser (this);
Location location = LMU.getLocation();
GsmCellLocation CellLocation = LMU.getCellLocation();
String URL = LocationMobileUser.URL;
LocationMobileUser.GetXMLTask xmlp = LMU.new GetXMLTask();
String Provider = LMU.getProvider(location);
String isp = xmlp.getOutputFromUrl(URL);
String latLongString = LMU.updateWithNewLocation(location);
String cidlacString = LMU.CellLacLocation(CellLocation);
String operator = LMU.getSimOperator();
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
myLocationText.setText("Your current GPS position is:\n" + latLongString);
TextView myprovider = (TextView)findViewById(R.id.myprovider);
myprovider.setText("\nYour GPS position is provided by:\n" + Provider);
TextView myCellLocation = (TextView)findViewById(R.id.mycelllocation);
myCellLocation.setText("\nYour current Cell position is:\n" + cidlacString);
TextView myOperator = (TextView)findViewById(R.id.myoperator);
myOperator.setText("\nYour GSM operator is:\n" + operator);
TextView myispText = (TextView)findViewById(R.id.myispText);
myispText.setText("\nYour current ISP is:\n" + isp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Code contains no errors !!
if its any use here's my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationmobileuser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.locationtheapp.LocationTheApp"
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>
Tried to toggle the package name in the Manifest between locationmobileuser and locationtheapp but still app crashes !!
As i said used to work like a charm in my previous projects !!
LOG:
06-18 05:36:54.502: E/Trace(992): error opening trace file: No such file or directory (2)
06-18 05:36:54.852: D/dalvikvm(992): newInstance failed: no <init>()
06-18 05:36:54.862: D/AndroidRuntime(992): Shutting down VM
06-18 05:36:54.862: W/dalvikvm(992): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-18 05:36:55.002: E/AndroidRuntime(992): FATAL EXCEPTION: main
06-18 05:36:55.002: E/AndroidRuntime(992): java.lang.RuntimeException: Unable toinstantiate activity ComponentInfo{com.example.locationmobileuser/com.example.locationmobileuser.LocationMobileUser}: java.lang.InstantiationException: can't instantiate class com.example.locationmobileuser.LocationMobileUser; no empty constructor
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.os.Looper.loop(Looper.java:137)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.reflect.Method.invokeNative(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.reflect.Method.invoke(Method.java:511)
06-18 05:36:55.002: E/AndroidRuntime(992): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-18 05:36:55.002: E/AndroidRuntime(992): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-18 05:36:55.002: E/AndroidRuntime(992): at dalvik.system.NativeStart.main(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): Caused by: java.lang.InstantiationException: can't instantiate class com.example.locationmobileuser.LocationMobileUser; no empty constructor
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.Class.newInstanceImpl(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.Class.newInstance(Class.java:1319)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
06-18 05:36:55.002: E/AndroidRuntime(992): ... 11 more
Any help would be really appreciated !!
see the package name of menifest
package="com.example.locationmobileuser
and activity package name both should be same change this package
<activity
android:name="com.example.locationtheapp.LocationTheApp"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
you need to add empty constructor in your locationmobileuser class.
public LocationMobileUser(){
}
don't need to do all these things , just go to old project and right click on the project ->> refactor to rename project name or package name
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.