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

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.

Related

FATAL EXCEPTION: main on Android App

I'm getting this fatal exception: main error. It is only when I click on the 'Pick A Place' button on my app.
The logcat report when clicking on the 'Pick A Place' button is below:
04-13 13:52:19.418 10737-10737/cct.mad.lab E/AndroidRuntime: FATAL EXCEPTION: main
Process: cct.mad.lab, PID: 10737
java.lang.NoSuchMethodError: cct.mad.lab.SettingsActivity.checkSelfPermission
at cct.mad.lab.SettingsActivity.calculateCurrentCoordinates(SettingsActivity.java:679)
at cct.mad.lab.SettingsActivity.onPrepareDialog(SettingsActivity.java:581)
at android.app.Activity.onPrepareDialog(Activity.java:3061)
at android.app.Activity.showDialog(Activity.java:3124)
at android.app.Activity.showDialog(Activity.java:3075)
at cct.mad.lab.SettingsActivity$8.onClick(SettingsActivity.java:374)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
The logcat points to a 'NoSuchMethodError' when checking for 'self permission' to do with the method 'calculateCurrentCooridnates'. This method is below:
#TargetApi(Build.VERSION_CODES.M)
private void calculateCurrentCoordinates() {
float lat = 0, lon = 0;
try {
LocationManager locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat = (float) recentLoc.getLatitude();
lon = (float) recentLoc.getLongitude();
} catch (Exception e) {
Log.e(DEBUG_TAG, "Location failed", e);
}
mFavPlaceCoords = new GPSCoords(lat, lon);
}
The ToDo was automatically generated when Android Studio automatically added the '#TargetAPI' bit. With this in mind I added the following to the manifest and as I got no more errors I thought this would be enough:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
However, the app just crashes.
Any help greatly appreciated.
Thanks
Extending AppCompatActivity will solve the issue.
Do like this
public class SettingsActivity extends AppCompatActivity {

Android communication between activity and service

I'm trying to implement a system service on Android with inter-process communication based on binding a messenger. For this I'm following this tutorial:
http://www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger.html
But no matter what I'm trying, i can't get it to work.
I found different tutorials online but in the end they are all based on the same procedure.
The app will crash right away when I'm trying to communicate with the service.
Error message
10-09 15:40:33.490 3468-3468/com.example.stenosis.testservice E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.stenosis.testservice, PID: 3468
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stenosis.testservice/com.example.stenosis.testservice.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.stenosis.testservice.MyActivity.sendMsg(MyActivity.java:87)
at com.example.stenosis.testservice.MyActivity.onCreate(MyActivity.java:49)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
MyActivity.java:
public class MyActivity extends Activity {
private ServiceConnection sConn;
private Messenger messenger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Service Connection to handle system callbacks
sConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
messenger = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We are conntected to the service
messenger = new Messenger(service);
}
};
// We bind to the service
bindService(new Intent(this, MyService.class), sConn, Context.BIND_AUTO_CREATE);
// Try to send a message to the service
sendMsg();
}
// This class handles the Service response
class ResponseHandler extends Handler {
#Override
public void handleMessage(Message msg) {
int respCode = msg.what;
String result = "";
switch (respCode) {
case MyService.TO_UPPER_CASE_RESPONSE: {
result = msg.getData().getString("respData");
System.out.println("result");
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
}
}
public void sendMsg() {
String val = "This is a test";
Message msg = Message
.obtain(null, MyService.TO_UPPER_CASE);
msg.replyTo = new Messenger(new ResponseHandler());
// We pass the value
Bundle b = new Bundle();
b.putString("data", val);
msg.setData(b);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
MyService.java
public class MyService extends Service {
public static final int TO_UPPER_CASE = 0;
public static final int TO_UPPER_CASE_RESPONSE = 1;
private Messenger msg = new Messenger(new ConvertHanlder());;
#Override
public IBinder onBind(Intent intent) {
return msg.getBinder();
}
class ConvertHanlder extends Handler {
#Override
public void handleMessage(Message msg) {
// This is the action
int msgType = msg.what;
switch (msgType) {
case TO_UPPER_CASE: {
try {
// Incoming data
String data = msg.getData().getString("data");
Message resp = Message.obtain(null, TO_UPPER_CASE_RESPONSE);
Bundle bResp = new Bundle();
bResp.putString("respData", data.toUpperCase());
resp.setData(bResp);
msg.replyTo.send(resp);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
}
default:
super.handleMessage(msg);
}
}
}
}
AndroidManifest.xml
<service android:name=".MyService" android:process=":convertprc"/>
Your problem is that the messanger property is null. You are experiencing concurrency problem. The bindService method is asynchronous - it returns immediately and performs the binding in a background thread. When the binding is done, the onServiceConnected method is invoked. When you try to send the message, the messanger is still not initialized because the onServiceConnected method is hasn't been executed yet.

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

How to upload images to dropbox?

i am trying to upload selected image to dropbox from gallery.I am being stuck up from days because i am getting unable to resume Runtime Exception
My onActivityResult() is
if(requestCode == PIC_UPLOAD) {
System.out.println("Reahced 1");
Uri selectedImage = data.getData();
String[] filePathColumn ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null); cursor.moveToFirst();
System.out.println("Reahced 2");
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Uri imageUri=data.getData();
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("image", imageUri.getPath()));
System.out.println("Reahced 3");
/* String outPath = imageUri.toString(); File outFile = new
File(outPath); FileInputStream fis = new FileInputStream(outFile);
mDBApi.putFileOverwriteRequest("/Pic1", fis, outFile.length(),null);
*/
Uri photoUri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA };
Cursor actualimagecursor = managedQuery(photoUri, proj,null, null, null);
int actual_image_column_index =
actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path =actualimagecursor.getString(actual_image_column_index);
System.out.println("Image location: " + img_path);
System.out.println("Reached 1");
uploadDropbox(img_path);
}
And uploadDropbox body is:
private void uploadDropbox(String URL) {
// TODO Auto-generated method stub
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
System.out.println(URL);
System.out.println("Reahced 4");
mDBApi.getSession().startAuthentication(MyCamActivity.this);
System.out.println("Reahced 5");
// AccessTokenPair access = getStoredKeys();
// mDBApi.getSession().setAccessTokenPair(access);
FileInputStream inputStream = null;
try {
File file = new File(URL.toString());
inputStream = new FileInputStream(file);
com.dropbox.client2.DropboxAPI.Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
}
onResume method body:
protected void onResume() {
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// MANDATORY call to complete auth.
// Sets the access token on the session
mDBApi.getSession().finishAuthentication();
AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair();
// Provide your own storeKeys to persist the access token pair
// A typical way to store tokens is using SharedPreferences
storeKeys(tokens.key, tokens.secret);
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
private AccessTokenPair getStoredKeys() {
// TODO Auto-generated method stub
return mDBApi.getSession().getAccessTokenPair();
}
private void storeKeys(String key, String secret) {
// TODO Auto-generated method stub
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
AndroidManifest.xml
<activity
android:name="com.dropbox.client2.android.AuthActivity"
android:launchMode="singleTask"
android:configChanges="orientation|keyboard">
<intent-filter>
<!-- Change this to be db- followed by your app key -->
<data android:scheme="db-MyKey" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MyCamActivity"
android:label="#string/app_name"
android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"
android:uiOptions="splitActionBarWhenNarrow"
android:clearTaskOnLaunch="true"
>
Error**:
01-23 14:58:00.855: D/dalvikvm(4238): GC_FOR_ALLOC freed 104K, 2% free 12729K/12935K, paused 16ms
01-23 14:58:00.894: I/System.out(4238): Its not null
01-23 14:58:00.901: D/AndroidRuntime(4238): Shutting down VM
01-23 14:58:00.901: W/dalvikvm(4238): threadid=1: thread exiting with uncaught exception (group=0x40a511f8)
01-23 14:58:00.901: E/AndroidRuntime(4238): FATAL EXCEPTION: main
01-23 14:58:00.901: E/AndroidRuntime(4238): java.lang.RuntimeException: Unable to resume activity {cam.pack/cam.pack.MyCamActivity}: java.lang.NullPointerException
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2444)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2472)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.os.Looper.loop(Looper.java:137)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-23 14:58:00.901: E/AndroidRuntime(4238): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:58:00.901: E/AndroidRuntime(4238): at java.lang.reflect.Method.invoke(Method.java:511)
01-23 14:58:00.901: E/AndroidRuntime(4238): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-23 14:58:00.901: E/AndroidRuntime(4238): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-23 14:58:00.901: E/AndroidRuntime(4238): at dalvik.system.NativeStart.main(Native Method)
01-23 14:58:00.901: E/AndroidRuntime(4238): Caused by: java.lang.NullPointerException
01-23 14:58:00.901: E/AndroidRuntime(4238): at cam.pack.MyCamActivity.onResume(MyCamActivity.java:571)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1154)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.Activity.performResume(Activity.java:4539)
01-23 14:58:00.901: E/AndroidRuntime(4238): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2434)
01-23 14:58:00.901: E/AndroidRuntime(4238): ... 12 more
I have made a mistake, i have put dropbox session in my own defined function uploadDropbox(), and thats a an error causes NullPointerException, because if i print mDBApi so its NULL. Its not been intialized. We have to put these lines in onCreate() and now its working, images are uploading in CameraUploads folder in Dropbox.
Thanks for comments.

how to send an email?

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

Categories