SMS Receiver - Force closes everytime I receive a sms - java

I am trying to create a phone locator using SMS as an activator, but when I'm sending a sms to the phone, the application always crashes(force close):
Here is my code for the class:
public class SMSReceiver extends BroadcastReceiver{
private static final String FAR_MODE_KEY = "farmode";
private String FarModeKeyword;
#Override
public void onReceive(Context context, Intent intent) {
prefs = getSharedPreferences(Keywords, MODE_PRIVATE);
FarModeKeyword = prefs.getString(FAR_MODE_KEY, "");
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String message = "";
String number = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
message += msgs[i].getMessageBody().toString();
}
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
number += msgs[i].getOriginatingAddress();
}
}
if (message == FarModeKeyword)
{
Toast.makeText(getBaseContext(),
message,
Toast.LENGTH_SHORT).show();
String loc = "";
loc = getLocation();
Toast.makeText(getBaseContext(),
loc,
Toast.LENGTH_SHORT).show();
sendSMS(number, loc);
}
}
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
private String getLocation ()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria ();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener MyLocListener = new loc_listener();
locationManager.requestLocationUpdates(bestProvider, 1000, 1, MyLocListener);
String add = "";
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try
{
List<Address> addresses = geoCoder.getFromLocation(lat,lon, 1);
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
}
catch (IOException e)
{
e.printStackTrace();
}
locationManager.removeUpdates(MyLocListener);
return add;
}
public class loc_listener implements LocationListener
{
public void onLocationChanged(Location l) {
lat = l.getLatitude();
lon = l.getLongitude();
}
public void onProviderEnabled(String p) {
}
public void onProviderDisabled(String p) {
}
public void onStatusChanged(String p, int status, Bundle extras){
}
}
}
Here is the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="locateodroid.james"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="locateodroid.james.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBBo4h4fDksXasHd7iCgIg0A5wTriToW8w"/>
<permission
android:name="locateodroid.james.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="locateodroid.james.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>
<receiver
android:name=".receiver.StartMyServiceAtBootReceiver"
android:enabled="true"
android:exported="true"
class="locateodroid.james.receiver.StartMyServiceAtBootReceiver"
android:label="StartMyServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="locateodroid.james.sms.SMSReceiver"
class="locateodroid.james.sms.SmsReceiver"
android:label="SMSReceiver">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Here is the logcat of error:
02-05 04:03:25.169: E/AndroidRuntime(430): FATAL EXCEPTION: main
02-05 04:03:25.169: E/AndroidRuntime(430): java.lang.RuntimeException: Unable to instantiate receiver locateodroid.james.sms.SMSReceiver: java.lang.ClassNotFoundException: locateodroid.james.sms.SMSReceiver in loader dalvik.system.PathClassLoader[/data/app/locateodroid.james-1.apk]
02-05 04:03:25.169: E/AndroidRuntime(430): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1773)
02-05 04:03:25.169: E/AndroidRuntime(430): at android.app.ActivityThread.access$2400(ActivityThread.java:117)
02-05 04:03:25.169: E/AndroidRuntime(430): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:981)
02-05 04:03:25.169: E/AndroidRuntime(430): at android.os.Handler.dispatchMessage(Handler.java:99)
02-05 04:03:25.169: E/AndroidRuntime(430): at android.os.Looper.loop(Looper.java:123)
02-05 04:03:25.169: E/AndroidRuntime(430): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-05 04:03:25.169: E/AndroidRuntime(430): at java.lang.reflect.Method.invokeNative(Native Method)
02-05 04:03:25.169: E/AndroidRuntime(430): at java.lang.reflect.Method.invoke(Method.java:507)
02-05 04:03:25.169: E/AndroidRuntime(430): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-05 04:03:25.169: E/AndroidRuntime(430): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-05 04:03:25.169: E/AndroidRuntime(430): at dalvik.system.NativeStart.main(Native Method)
02-05 04:03:25.169: E/AndroidRuntime(430): Caused by: java.lang.ClassNotFoundException: locateodroid.james.sms.SMSReceiver in loader dalvik.system.PathClassLoader[/data/app/locateodroid.james-1.apk]
02-05 04:03:25.169: E/AndroidRuntime(430): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
02-05 04:03:25.169: E/AndroidRuntime(430): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
02-05 04:03:25.169: E/AndroidRuntime(430): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
02-05 04:03:25.169: E/AndroidRuntime(430): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1764)
02-05 04:03:25.169: E/AndroidRuntime(430): ... 10 more
I'm working on this error for almost 2 days and still I've got no answer for this, can someone help me on this matter? THANKS IN ADVANCE!
UPDATE
The first problem was now resolved, but another error aries, a NullPointerException is throwned when I received a sms
package locateodroid.james;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.EditText;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver{
public SharedPreferences prefs;
private String FarModeKeyword;
private String Keywords = "prefmode";
private Double lat;
private Double lon;
private static final String FAR_MODE_KEY = "farmode";
private Context con;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,
"test",
Toast.LENGTH_SHORT).show();
con = context;
prefs = getSharedPreferences(Keywords, Context.MODE_PRIVATE);
FarModeKeyword = prefs.getString(FAR_MODE_KEY, "");
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String message = "";
String number = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
message += msgs[i].getMessageBody().toString();
}
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
number += msgs[i].getOriginatingAddress();
}
}
if (message == FarModeKeyword)
{
Toast.makeText(context,
message,
Toast.LENGTH_SHORT).show();
String loc = "";
loc = getLocation();
Toast.makeText(context,
loc,
Toast.LENGTH_SHORT).show();
sendSMS(number, loc);
}
}
private SharedPreferences getSharedPreferences(String keywords2,
int modePrivate) {
// TODO Auto-generated method stub
return null;
}
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
private String getLocation ()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria ();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener MyLocListener = new loc_listener();
locationManager.requestLocationUpdates(bestProvider, 1000, 1, MyLocListener);
String add = "";
Geocoder geoCoder = new Geocoder(con, Locale.getDefault());
try
{
List<Address> addresses = geoCoder.getFromLocation(lat,lon, 1);
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
}
catch (IOException e)
{
e.printStackTrace();
}
locationManager.removeUpdates(MyLocListener);
return add;
}
private LocationManager getSystemService(String locationService) {
// TODO Auto-generated method stub
return null;
}
public class loc_listener implements LocationListener
{
public void onLocationChanged(Location l) {
lat = l.getLatitude();
lon = l.getLongitude();
}
public void onProviderEnabled(String p) {
}
public void onProviderDisabled(String p) {
}
public void onStatusChanged(String p, int status, Bundle extras) {
}
}
}
The class is returning a NullPointerException error now :(

Its unable to find the class:
Caused by: java.lang.ClassNotFoundException: locateodroid.james.sms.SMSReceiver
Are you sure about the package reference?
This is likely coming from the class line in your receiever:
class="locateodroid.james.sms.SmsReceiver"
update
The reason you can't those context properties is because they are STATIC constants
meaning that you grab them from the base class (without the need for an instance) like so:
Context.MODE_PRIVATE

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.

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]

How to pass get text from userinput (edittext) and put into a textview in another activity?

I would like to take user input entered in the EditTextField(in the EnterNewFile class) and put it into the TextField (in the NoteEdit class). Please help! Thanks! FYI- I use XML files for the layouts of these two classes.
***********EnterNewFile.class*********
package com.example.note;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EnterNewFile extends Activity {
public EditText mText;
public Button mButton;
public final static String EXTRA_MESSAGE = "com.example.note.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.new_file_start);
mText = (EditText)findViewById(R.id.file_name_edittext);
mButton = (Button)findViewById(R.id.next_button);
}
public void nextButton(View view)
{
/** Called when the user clicks the Next button */
Log.d("EditText", mText.getText().toString());
mText.getText().toString();
Intent intent = new Intent(this, NoteEdit.class);
EditText editText = (EditText) findViewById(R.id.file_name_edittext);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
//
}
}
******************************************
********NoteEdit.class************
package com.example.note;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class NoteEdit extends Activity{
public static int numTitle = 1;
public static String curDate = "";
public static String curText = "";
private TextView mTitleText;
private EditText mBodyText;
private TextView mDateText;
private Long mRowId;
private Cursor note;
private NotesDbAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit_add);
setTitle(R.string.app_name);
mTitleText = (TextView) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateText = (TextView) findViewById(R.id.notelist_date);
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("M'/'d'/'y");
curDate = formatter.format(curDateTime);
mDateText.setText(""+curDate);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(EnterNewFile.EXTRA_MESSAGE);
// Create the text view
// TextView textView = new TextView(this);
mTitleText.setText(message);
// Set the text view as the activity layout
// setContentView(textView);
// mTitleText.setText(dana);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
}
public void addFiles(View view)
{
/*Intent addFilesTarget = new Intent(this, Welcome.class);
startActivity(addFilesTarget);*/
}
public static class LineEditText extends EditText{
// we need this constructor for LayoutInflater
public LineEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(Color.BLUE);
}
private Rect mRect;
private Paint mPaint;
#Override
protected void onDraw(Canvas canvas) {
int height = getHeight();
int line_height = getLineHeight();
int count = height / line_height;
if (getLineCount() > count)
count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
int baseline = getLineBounds(0, r);
for (int i = 0; i < count; i++) {
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
baseline += getLineHeight();
super.onDraw(canvas);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.noteedit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_about:
/* Here is the intro about myself */
AlertDialog.Builder dialog = new AlertDialog.Builder(NoteEdit.this);
dialog.setTitle("About");
dialog.setMessage("Hello! I'm Dana, creator of this application. This is for documenting research."
+"\n melaninabeauty#gmail.com");
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
return true;
case R.id.menu_delete:
if(note != null){
note.close();
note = null;
}
if(mRowId != null){
mDbHelper.deleteNote(mRowId);
}
finish();
return true;
case R.id.menu_save:
saveState();
finish();
default:
return super.onOptionsItemSelected(item);
}
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if(mRowId == null){
mDbHelper.createNote(title, body, curDate);
}else{
mDbHelper.updateNote(mRowId, title, body, curDate);
}
}
private void populateFields() {
if (mRowId != null) {
note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
curText = note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
}
}
}
***********************************
****AndroidManifest.xml****
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.note"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.note.Welcome"
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="com.example.note.NoteList">
</activity>
<activity
android:name="com.example.note.NoteEdit">
</activity>
<activity
android:name="com.example.note.Export">
</activity>
<activity
android:name="com.example.note.NoteEditAdd">
</activity>
<activity
android:name="com.example.note.EnterNewFile">
</activity>
</application>
</manifest>
<!--
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.note"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name="com.example.note.Welcome">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.note.NoteList"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.note.NoteEdit"
android:label="#string/edit_note"
android:parentActivityName="com.example.note.Welcome" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.note.Welcome" />
</activity>
</application>
</manifest>
-->
<!--
activity 2 android:name= com.example.note.NoteEdit
android:label=#string/app_name
android:windowSoftInputMode="djustUnspecified/>
-->
*****************************
> *****LogCat of crash**** Crash occurs after nextButton is clicked****(I inputted the text "nouy", clicked nextButton, then application crashes.********************
LogCat of crash** Crash occurs after nextButton is clicked*(I inputted the text "nouy", clicked nextButton, then application crashees.**
08-02 20:48:36.703: D/EditText(3575): nouy
08-02 20:48:36.793: I/Choreographer(3575): Skipped 68 frames! The application may be doing too much work on its main thread.
08-02 20:48:37.143: D/dalvikvm(3575): GC_CONCURRENT freed 1331K, 34% free 2956K/4428K, paused 4ms+59ms, total 137ms
08-02 20:48:37.353: D/AndroidRuntime(3575): Shutting down VM
08-02 20:48:37.394: W/dalvikvm(3575): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-02 20:48:37.443: E/AndroidRuntime(3575): FATAL EXCEPTION: main
08-02 20:48:37.443: E/AndroidRuntime(3575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.note/com.example.note.NoteEdit}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.os.Handler.dispatchMessage(Handler.java:99)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.os.Looper.loop(Looper.java:137)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-02 20:48:37.443: E/AndroidRuntime(3575): at java.lang.reflect.Method.invokeNative(Native Method)
08-02 20:48:37.443: E/AndroidRuntime(3575): at java.lang.reflect.Method.invoke(Method.java:511)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-02 20:48:37.443: E/AndroidRuntime(3575): at dalvik.system.NativeStart.main(Native Method)
08-02 20:48:37.443: E/AndroidRuntime(3575): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.example.note.NoteEdit.populateFields(NoteEdit.java:231)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.example.note.NoteEdit.onCreate(NoteEdit.java:99)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.Activity.performCreate(Activity.java:5104)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-02 20:48:37.443: E/AndroidRuntime(3575): ... 11 more
08-02 20:48:40.073: E/Trace(3598): error opening trace file: No such file or directory
(2)
Take the input from Edittext send it through the Intent to your destination activity and then set it in the TextView there.
I think you seem to already be doing that in your code:
The issue might be the you've not defined in your XML that nextButton function should be call on click ( inside android:onClick: inside your Button).
What you can also do is, in your onCreate funcion set up a listener which listens to the button click and call the intent from within it.
final EditText editText = (EditText) findViewById(R.id.file_name_edittext);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/** Called when the user clicks the Next button */
Log.d("EditText", mText.getText().toString());
Intent intent = new Intent(EnterNewFile.this, NoteEdit.class);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
//here you are taking value from EditText and send it to other activity:
Instead of
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(EnterNewFile.EXTRA_MESSAGE);
use following in onCreate() of your other NoteEdit activity:
Intent intent = getIntent();
if((intent.getExtras()!=null) && !intent.getExtras().isEmpty()){
String message = intent.getExtras().getString(EnterNewFile.EXTRA_MESSAGE);
}
this code is working:-
scrollview=(ScrollView)findViewById(R.id.scrollview1);
tb2.setTextSize(30);
tb2.setMovementMethod(new ScrollingMovementMethod());
scrollview.post(new Runnable() {
public void run() {
scrollview.fullScroll(View.FOCUS_DOWN);
}
});
chat1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
{
textsaring1=edt1.getText().toString();
tb2.setText(tb2.getText()+" "+textsaring1);
edt1.setText("");
}
}
});

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

Read and display incoming message text android

I am new to android development.I am developing small android application. In my application I want to retrieve newly coming sms and display this message to user. My code looks like
// HellowordActivity.java
package com.example.helloword;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class HellowordActivity extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String strMessage = "";
if (myBundle != null)
{
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody().toString();
strMessage += "\n";
}
// Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
Intent _intent = new Intent(context, PopupActivity.class);
_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
_intent.putExtra("strMessage", strMessage);
startActivity(_intent);
}
}
}
I added receiver and permission in Android Manifest.xml
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<receiver android:name=".HellowordActivity" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
<activity android:name=".PopupActivity" android:launchMode="singleTop" />
I am not doing any thing in layout part.What I want as an output when new message will come;
message text display to user with simple popup.
Need Help.. Thank you...
Try this it works for me you will get a toast shown to you with the content of the message received:
package com.example.a;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show();
}
}
}
}
}
The AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.HARDWARE_TEST"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name=".SMSBroadcastReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Use DDMS to send sms to your emulator via Telnet
if you want to show an popup when SMS is Recived then you will need to Create an Activity with android:launchMode="singleTop" as:
In manifast declare Activity as:
<activity android:name=".PopupActivity" android:launchMode="singleTop" />
From HellowordActivity BroadcastReceiver start Activity as:
Intent intent = new Intent(context, PopupActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent .putExtra("strMessage", strMessage);
context.startActivity(intent);
And in your PopupActivity.class:
public class PopupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
Intent intent= getIntent();//get message here
String strMessage = intent.getStringExtra("strMessage");
//NOW YOU CAN SHOW THIS MESSAGE IN POPUP
}
#Override
protected void onStop() {
super.onStop();
this.finish();
// The activity is no longer visible (it is now "stopped")
}
You can also checkout these Smspopup apps source code:
android-smspopup
sms-enhancer

Categories