how to send an email? - java

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.

Related

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.

Unable to instantiate application java.lang.RuntimeException:...BackupDB cannot be cast to android.app.Application

MANIFEST:(partial view)
MainActivity, program immediately terminates and issues the messages in the Log.
It should have started showing the buttons to select options to continue execution.
After days of researching this forum, I found postings that suggest to place the BackupDb inside the application in the Manifest.
After doing that, I ended up with the message in the log.
Having exhausted my research venues, I'd like to know what could be the problem and how to solve it.
MANIFEST:(partial view)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.peter.databasetest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<supports-screens
android:xlargeScreens="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="false"
/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
**android:name="com.peter.databasetest.BackupDB">**
<activity
android:name="com.peter.databasetest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CheckDatabase"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CHECKDATABASE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".CheckSDcard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CHECKSDCARD" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.peter.databasetest.Insert"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.peter.databasetest.INSERT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity: Calls checkSDcard and CheckDatabase. Checks if there is SDCard present and the database in main, exists.
public class MainActivity extends Activity implements OnClickListener {
DBAdapter db;
Button insertButton; //ADD A NEW RECORD
Button listAllButton; //LIST ALL
Button cancelButton; //CANCEL PGM
Button backupDbButton; //REQUEST BACKUP DB TO SDCARD
Button restoreButton; //RESTORE DB FROM SDCARD TO MAIN
Button memsizeButton; //SHOW MEMORY SIZES ON DEVICE
int retcode;
int chk;
String message;
public Context context;
public static final String NO_DB ="Database does not exist. Backup is not possible";
public static final String DB_PB ="ERROR- Check log";
public static final String UNWR_SDCARD ="Your SDCard must be set to writable. Check the card lock";
public static final String NO_SDCARD ="No SDcard detected. No backup is possible";
public static final String BKP_OK = "Backup was SUCCESSFUL.";
public static final String BKP_NOK = "Backup FAILED. ";
static final int SD_CHECK = 1;
static final int DB_CHECK = 2;
static final int BK_CHECK = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insertButton = (Button) findViewById(R.id.insertButton);
listAllButton = (Button) findViewById(R.id.listAllButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
backupDbButton = (Button) findViewById(R.id.backupDbButton);
restoreButton = (Button) findViewById(R.id.restoreButton);
memsizeButton = (Button) findViewById(R.id. memsizeButton);
insertButton.setOnClickListener(this); //insert record into DB
listAllButton.setOnClickListener(this); //list ALL records from DB
cancelButton.setOnClickListener(this); //cancel the program
backupDbButton.setOnClickListener(this); //request backup to sdcard
restoreButton.setOnClickListener(this); //request restore from sdcard
memsizeButton.setOnClickListener(this); //Get Meory sizes
public void onClick(View v ) {
if (v == insertButton) {
startActivity(new Intent(getApplicationContext(), Insert.class));
}else if (v == listAllButton){
startActivity (new Intent(MainActivity.this, ListDr.class));
}else if (v == backupDbButton){
**Intent checksd = new Intent(this,CheckSDcard.class);**
**startActivityForResult(checksd, SD_CHECK);**
}else if (v == restoreButton) {
startActivity (new Intent(MainActivity.this,RestoreDB.class));
}else if (v == memsizeButton) {
startActivity (new Intent(MainActivity.this,GetMemorySizes.class));
}else if (v == cancelButton){
finish();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SD_CHECK && resultCode == RESULT_OK) {
Intent checkdb = new Intent(MainActivity.this,CheckDatabase.class);
startActivityForResult(checkdb, DB_CHECK);
}else if (requestCode == DB_CHECK && resultCode == RESULT_OK){
**Intent backup = new Intent(MainActivity.this,BackupDB.class);**
**startActivityForResult(backup, BK_CHECK);**
}else if (requestCode == BK_CHECK && resultCode == RESULT_OK){
message = BKP_OK;
SendMessageDialog(message);
finish();
}
if(resultCode == RESULT_CANCELED && resultCode == -1){
message = NO_DB;
SendMessageDialog(message);
finish();
}else if(resultCode == RESULT_CANCELED && resultCode == -2) {
message = DB_PB;
SendMessageDialog(message);
finish();
}
}
BackupDb: Copies the database to the SDCARD.
package com.peter.databasetest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import com.peter.databasetest.DBAdapter;
public class BackupDB extends AsyncTask<Void, Void, Integer> {
DBAdapter db;
intrc= -10;
intretcode;
intchk;
Stringmessage;
String mypackage;
public Context context;
public static String FOLDER_NAME = "DBfolder";
public static final String DATABASE_NAME = "UserDB.db";
public static final String DATABASE_BACKUP= "UserDB.db";
public static final String BKP_OK = "Backup was SUCCESSFUL.";
public static final String BKP_NOK = "Backup FAILED. ";
#Override
protected void onPreExecute() {
// GET PACKAGE NAME
mypackage = context.getApplicationContext().getPackageName() ;
}
// START BACKUP TO SDCARD
#Override
protected Integer doInBackground(Void... params) {
// DOING BACKUP
Log.i("00000" , "STARTING BACKUP...BACKUP ");
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
CREATE A FOLDER /mnt/sdcard<packagename>FOLDER_NAME if it does not exist
File folder = new File(Environment.getExternalStorageDirectory()
+ "/"
+ mypackage
+ "/"
+ FOLDER_NAME);
if(!folder.exists()) {
if (folder.mkdirs()) ;
}
// GET THE PATH OF THE BACKUP ON THE SDCARD
FilefileBackupDir = new File(Environment.getExternalStorageDirectory()
+ "/"
+mypackage
+ "/"
+ FOLDER_NAME
+"/"
+ DATABASE_BACKUP) ;
// IF WE HAVE A BACKUP ON SDCARD, DELETE IT TO MAKE ROOM FOR THE NEW BACKUP
if (fileBackupDir.exists()) {
fileBackupDir.delete();
}else {
* DO NOTHING */
}
// GET CURRENT DB PATH FOR THE COPY
String currentDBPath = "/data/" + mypackage + "/databases/"+ DATABASE_NAME;
// GET CURRENT DB PATH FOR THE BACKUP
String backupDBPath = "/" + mypackage + "/" +FOLDER_NAME + "/" + DATABASE_BACKUP;
FilecurrDB = new File(data, currentDBPath) ;
FilebkpDB = new File(sd, backupDBPath);
FileChannel from = null;
try {
from = new FileInputStream(currDB).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileChannel to = null;
try {
to = new FileOutputStream(bkpDB).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
to.transferFrom(from, 0, from.size());
} catch (IOException e) {
e.printStackTrace();
}
try {
from.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
to.close();
} catch (IOException e) {
e.printStackTrace();
}
retcode = 0;
returnretcode;
// end DoInBackgroung
protectedvoid onPostExecute(Integer retcode, String message) {
if(retcode == 0) {
message = BKP_OK;
SendMessageDialog(message);
}else {
message = BKP_NOK;
SendMessageDialog(message);
}
}
public void SendMessageDialog(String message) {
if (message == BKP_OK ) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Database")
.setMessage(message) // Title of the dialog
.setCancelable(true) // Does allow the use of Back Button on the hardware
.setIcon(R.drawable.ecg)// da picture
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Database")
.setMessage(message) // Title of the dialog
.setCancelable(true) // Does allow the use of Back Button on the hardware
.setIcon(R.drawable.bad)// da picture
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
}
Logcat:
02-12 07:36:06.015: E/AndroidRuntime(987): FATAL EXCEPTION: main
02-12 07:36:06.015: E/AndroidRuntime(987): java.lang.RuntimeException: Unable to instantiate application com.peter.databasetest.BackupDB:
: com.peter.databasetest.BackupDB cannot be cast to android.app.Application
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.LoadedApk.makeApplication(LoadedApk.java:501)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4124)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.access$1300(ActivityThread.java:130)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1255)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.os.Looper.loop(Looper.java:137)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 07:36:06.015: E/AndroidRuntime(987): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 07:36:06.015: E/AndroidRuntime(987): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 07:36:06.015: E/AndroidRuntime(987): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 07:36:06.015: E/AndroidRuntime(987): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 07:36:06.015: E/AndroidRuntime(987): at dalvik.system.NativeStart.main(Native Method)
02-12 07:36:06.015: E/AndroidRuntime(987): Caused by: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Application
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.Instrumentation.newApplication(Instrumentation.java:982)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.Instrumentation.newApplication(Instrumentation.java:967)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
02-12 07:36:06.015: E/AndroidRuntime(987): ... 11 more
Comment:
I removed the BackupDb from the application and reinstated it as activity.
<activity
android:name=".BackupDB"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.peter.databasetest.BACKUPDB" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
The program now brings up the buttons as expected, but when trying the backup I still get the same message as in the earlier log. (Catch-22?)
Most current log:
02-12 13:00:16.569: W/dalvikvm(30656): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
02-12 13:00:16.650: E/AndroidRuntime(30656): FATAL EXCEPTION: main
02-12 13:00:16.650: E/AndroidRuntime(30656): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.peter.databasetest/com.peter.databasetest.BackupDB}: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Activity
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.os.Looper.loop(Looper.java:137)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 13:00:16.650: E/AndroidRuntime(30656): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 13:00:16.650: E/AndroidRuntime(30656): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 13:00:16.650: E/AndroidRuntime(30656): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 13:00:16.650: E/AndroidRuntime(30656): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 13:00:16.650: E/AndroidRuntime(30656): at dalvik.system.NativeStart.main(Native Method)
02-12 13:00:16.650: E/AndroidRuntime(30656): Caused by: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Activity
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
02-12 13:00:16.650: E/AndroidRuntime(30656): ... 11 more
>Question:
>Is there any known limitation calling an AsyncTask by way of startActivityForResult?
>Could this be a factor?
The problem is in the Manifest file, you are setting your application:name to be te BackupDB class and this class is only an AsyncTask not an Application.
As can be seen on the explanation of "android:name":
An optional name of a class implementing the overall
android.app.Application for this package. [string]

Android - java.lang.RuntimeException:App is crashing as soon as it launches

I am trying to send GPS coordinates to server in android, but my app is crashing as soon as i run it, i am new to android so i'm not getting how to resolve this
Here is my logcat file
01-23 14:03:40.220: E/AndroidRuntime(880): FATAL EXCEPTION: main
01-23 14:03:40.220: E/AndroidRuntime(880): Process: com.example.server2, PID: 880
01-23 14:03:40.220: E/AndroidRuntime(880): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.server2/com.example.server2.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-23 14:03:40.220: E/AndroidRuntime(880):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Handler.dispatchMessage(Handler.java:102)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Looper.loop(Looper.java:136)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-23 14:03:40.220: E/AndroidRuntime(880): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): at java.lang.reflect.Method.invoke(Method.java:515)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-23 14:03:40.220: E/AndroidRuntime(880): at dalvik.system.NativeStart.main(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): Caused by: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.location.LocationManager.checkProvider(LocationManager.java:1623)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1167)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.example.server2.MainActivity.onCreate(MainActivity.java:71)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.Activity.performCreate(Activity.java:5231)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
And here is my MainActivity.java:
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
String lat,lng;
EditText etResponse;
TextView tvIsConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://182.18.144.140:80");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onLocationChanged(Location location) {
lat = Double.toString(location.getLatitude());
lng = Double.toString (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
// 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
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://182.18.144.140:80");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// nameValuePairs.add(new BasicNameValuePair("android", editText1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("LAT", lat));
nameValuePairs.add(new BasicNameValuePair("LON", lng));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("HTTP Failed", e.toString());
}
return null;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}
}
And my manifest.xml is like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.server2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.server2.MainActivity"
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>
</manifest>
provider is null. You declare it here
private String provider;
but you never initialize it properly.
This line is returning null
provider = locationManager.getBestProvider(criteria, false);
which is causing your initial exception at this line
Location location = locationManager.getLastKnownLocation(provider);
you can see that by stepping back through the stacktrace.
Debug that and see why provider is null.
i can see a couple things that might have a problem here:
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
provider is null at this point, and also you need to set the permissions to get fine or coarse user location.

Application code used to work but now crashes

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

Categories